diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..0d08e261a2 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "github-actions" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/workflows/branchNameValidation.yml b/.github/workflows/branchNameValidation.yml index 239d1c9dbf..6249133c10 100644 --- a/.github/workflows/branchNameValidation.yml +++ b/.github/workflows/branchNameValidation.yml @@ -11,6 +11,6 @@ jobs: - name: Verify branch name run: | - if ! [[ "$GITHUB_REF_NAME" =~ ^feature/.*|^features/.*|^fix/.*|^release/.*|^doc/.*|develop|^issue-* ]]; then + if ! [[ "$GITHUB_REF_NAME" =~ ^feature/.*|^features/.*|^fix/.*|^release/.*|^doc/.*|develop|^issue-*|^dependabot/* ]]; then exit 1 fi diff --git a/.github/workflows/build-userguide.yml b/.github/workflows/build-userguide.yml index c8752df8f3..599fdbd663 100644 --- a/.github/workflows/build-userguide.yml +++ b/.github/workflows/build-userguide.yml @@ -6,28 +6,40 @@ on: push: branches: - release/* + - feature/* + - features/* + - fix/* + - issue-* - doc/* + - dependabot/* + workflow_call: + inputs: + run-tests: + required: true + type: string + target_branch: + required: true + type: string env: - IS_RELEASE: ${{ github.event_name == 'release' && github.event.action == 'created' }} + IS_RELEASE: ${{ github.event_name == 'workflow_dispatch' }} jobs: build: - runs-on: ${{ matrix.os }} + runs-on: ubuntu-20.04 if: "!contains(github.event.head_commit.message, '[skip ci]')" - strategy: - matrix: - os: [ubuntu-20.04] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.target_branch}} - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: 3.8 + python-version: 3.12 - name: Install dependencies run: | @@ -50,15 +62,17 @@ jobs: echo "PDF_PATH_ASSET= [\"docs/pdf-doc-generation-with-sphinx/$PDF_NAME\"]" >> $GITHUB_ENV - name: user guide upload - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: pdf-reference-guide path: ${{ env.PDF_PATH }} - - name: Upload user guide as release asset + + - name: Publish assets if: ${{ env.IS_RELEASE == 'true' }} - uses: alexellis/upload-assets@0.4.0 env: - GITHUB_TOKEN: ${{ github.token }} - with: - asset_paths: ${{ env.PDF_PATH_ASSET }} + GITHUB_TOKEN: ${{ github.token }} + tag: ${{ github.event.inputs.release_tag }} + run: | + gh release upload "$tag" ${{ env.PDF_PATH }} + diff --git a/.github/workflows/centos7-system-deps-build.yml b/.github/workflows/centos7-system-deps-build.yml deleted file mode 100644 index 710c89ba09..0000000000 --- a/.github/workflows/centos7-system-deps-build.yml +++ /dev/null @@ -1,82 +0,0 @@ -name: Centos7 CI (deps. compilation) - -on: - schedule: - - cron: '21 2 * * 1' - -jobs: - - build: - - runs-on: ubuntu-latest - container: 'centos:7' - - steps: - - - name: Set up Python - run: | - yum update -y - yum install -y python3 python3-pip - - - name: Install libraries - run: | - yum install -y epel-release - yum install -y git redhat-lsb-core gcc gcc-c++ make wget centos-release-scl scl-utils rpm-build - yum install -y devtoolset-9 - yum install -y rh-git227-git - yum install -y unzip libuuid-devel wxGTK3-devel boost-test boost-devel - - - name: Install cmake - run: | - wget https://github.com/Kitware/CMake/releases/download/v3.25.3/cmake-3.25.3-linux-x86_64.tar.gz - tar xvf cmake-3.25.3-linux-x86_64.tar.gz -C / - echo "/cmake-3.25.3-linux-x86_64/bin" >> $GITHUB_PATH - rm cmake-3.25.3-linux-x86_64.tar.gz - - - name: Checkout - run: | - git clone $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git -b $GITHUB_REF_NAME . - - - name: Init submodule - run: | - git submodule update --init --recursive src/antares-deps - - - name: Install dependencies - run: | - pip3 install -r src/tests/examples/requirements.txt - - - name: Configure - run: | - source /opt/rh/devtoolset-9/enable - #git 2.x must be enabled for Coin compilation with CMake ExternalProject_Add - source /opt/rh/rh-git227/enable - cmake -B _build -S src -DCMAKE_BUILD_TYPE=release -DBUILD_TESTING=ON - - - name: Build - run: | - source /opt/rh/devtoolset-9/enable - source /opt/rh/rh-git227/enable - cmake --build _build --config release -j2 - - - name: Installer .rpm creation - run: | - cd _build - cpack -G RPM - - - name: Installer .tar.gz creation - run: | - cd _build - cpack -G TGZ - - - name: Installer archive upload - uses: actions/upload-artifact@v3 - with: - name: antares-centos7-archive - path: _build/*.tar.gz - - - name: Installer rpm upload - uses: actions/upload-artifact@v3 - with: - name: antares-centos7-rpm - path: _build/*.rpm - diff --git a/.github/workflows/centos7.yml b/.github/workflows/centos7.yml index 547c72ad07..573163d105 100644 --- a/.github/workflows/centos7.yml +++ b/.github/workflows/centos7.yml @@ -6,13 +6,23 @@ on: push: branches: - develop + - dependabot/* schedule: - cron: '21 2 * * *' + workflow_call: + inputs: + run-tests: + required: true + type: string + target_branch: + required: true + type: string env: GITHUB_TOKEN: ${{ github.token }} - IS_RELEASE: ${{ github.event_name == 'release' && github.event.action == 'created' }} + IS_RELEASE: ${{ github.event_name == 'workflow_dispatch' }} IS_PUSH: ${{ github.event_name == 'push' }} + REF: ${{ inputs.target_branch =='' && github.ref_name || inputs.target_branch}} jobs: @@ -28,23 +38,43 @@ jobs: - name: Checkout run: | - git clone $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git -b $GITHUB_REF_NAME . + git clone $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git -b ${{ env.REF }} . - - name: Init submodule + - name: Install gcc 10 run: | - git submodule update --init --remote src/antares-deps src/tests/resources/Antares_Simulator_Tests + yum install -y centos-release-scl + yum install -y devtoolset-10-gcc* + + - name: Install cmake 3.28 + run: pip3 install cmake==3.28.4 - - name: Download & extract precompiled deps at root + - name: Install VCPKG + # Note: we need to use environment variables instead of workflow variables + # because github messes up path variables when running in container, + # see https://github.com/actions/runner/issues/2058 run: | - ANTARES_DEPS_VERSION=$(cut -d'"' -f4 antares-deps-version.json | grep -Ev '\{|\}') - cd / - wget https://github.com/AntaresSimulatorTeam/antares-deps/releases/download/v${ANTARES_DEPS_VERSION}/rte-antares-deps-centos7-Release.tar.gz - tar -xvf rte-antares-deps-centos7-Release.tar.gz - rm -rf rte-antares-deps-centos7-Release.tar.gz + git submodule update --init vcpkg && ./vcpkg/bootstrap-vcpkg.sh -disableMetrics + echo "VCPKG_ROOT=$GITHUB_WORKSPACE/vcpkg" >> $GITHUB_ENV + echo "VCPKG_CACHE_DIR=$GITHUB_WORKSPACE/vcpkg_cache" >> $GITHUB_ENV + echo "VCPKG_BINARY_SOURCES=clear;files,$GITHUB_WORKSPACE/vcpkg_cache,readwrite" >> $GITHUB_ENV + + - name: Restore vcpkg binary dir from cache + id: cache-vcpkg-binary + # Note: we are stuck with v3, because v4 is not compatible with oracle8 image + uses: actions/cache/restore@v3 + with: + path: ${{ env.VCPKG_CACHE_DIR }} + key: vcpkg-cache-centos7-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} + # Allows to restore a cache when deps have only partially changed (like adding a dependency) + restore-keys: vcpkg-cache-centos7- + + - name: Init submodule + run: | + git submodule update --init --remote src/tests/resources/Antares_Simulator_Tests - name: Config OR-Tools URL run: | - echo "URL_ORTOOLS=https://github.com/rte-france/or-tools/releases/download/v9.5-rte2.0/ortools_cxx_centos7_static_sirius.zip" >> $GITHUB_ENV + echo "URL_ORTOOLS=https://github.com/rte-france/or-tools/releases/download/$(cat ortools_tag)/ortools_cxx_centos7_static_sirius.zip" >> $GITHUB_ENV - name: Download OR-Tools id: ortools @@ -54,46 +84,55 @@ jobs: unzip -q ortools.zip rm ortools.zip + - name: Install gh if needed + if: ${{ env.IS_RELEASE == 'true' }} + run: | + wget https://github.com/cli/cli/releases/download/v2.52.0/gh_2.52.0_linux_amd64.rpm + rpm -i gh_2.52.0_linux_amd64.rpm + gh --version + - name: Configure run: | - source /opt/rh/devtoolset-9/enable - cmake3 -B _build -S src \ - -DCMAKE_C_COMPILER_LAUNCHER=ccache \ - -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ - -DDEPS_INSTALL_DIR=/rte-antares-deps-Release \ - -DCMAKE_BUILD_TYPE=release \ - -DBUILD_TESTING=ON \ - -DBUILD_not_system=OFF \ - -DBUILD_TOOLS=OFF \ - -DBUILD_UI=OFF \ - -DCMAKE_PREFIX_PATH=${{ env.ORTOOLSDIR }}/install \ + source /opt/rh/devtoolset-10/enable + source /opt/rh/rh-git227/enable + cmake -B _build -S src \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache \ + -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ + -DCMAKE_TOOLCHAIN_FILE=$GITHUB_WORKSPACE/vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-linux-release \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTING=ON \ + -DBUILD_TOOLS=ON \ + -DBUILD_UI=OFF \ + -DCMAKE_PREFIX_PATH=${{ env.ORTOOLSDIR }}/install \ + - name: Build run: | - source /opt/rh/devtoolset-9/enable + source /opt/rh/devtoolset-10/enable source /opt/rh/rh-git227/enable - cmake3 --build _build --config Release -j2 + cmake --build _build --config Release -j$(nproc) ccache -s - name: Installer .rpm creation run: | cd _build - cpack3 -G RPM + cpack -G RPM - name: Solver archive creation run: | cd _build - cmake3 --install . --prefix install + cmake --install . --prefix install pushd . cd install/bin - tar czf ../../antares-solver_centos7.tar.gz antares-*-solver libsirius_solver.so + tar czf ../../antares-solver_centos7.tar.gz antares-solver libsirius_solver.so popd rm -rf install - name: .tar.gz creation run: | cd _build - cpack3 -G TGZ + cpack -G TGZ - name: Installer TGZ push uses: actions/upload-artifact@v3 @@ -105,21 +144,18 @@ jobs: with: path: _build/*.rpm - publish_assets: - name: Publish assets - needs: build - runs-on: ubuntu-latest - - steps: - - name: Download all artifacts - if: ${{ env.IS_RELEASE == 'true' }} - uses: actions/download-artifact@v3 - - - name: Publish assets if: ${{ env.IS_RELEASE == 'true' }} - uses: alexellis/upload-assets@0.4.0 env: - GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ github.token }} + tag: ${{ github.event.inputs.release_tag }} + run: | + gh release upload "$tag" _build/*.tar.gz _build/*.rpm + + - name: Cache vcpkg binary dir + if: always() + id: save-cache-vcpkg-binary + uses: actions/cache/save@v3 with: - asset_paths: '["*/*.tar.gz", "*/*.rpm"]' + path: ${{ env.VCPKG_CACHE_DIR }} + key: vcpkg-cache-centos7-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml new file mode 100644 index 0000000000..9e00892851 --- /dev/null +++ b/.github/workflows/clang-format.yml @@ -0,0 +1,36 @@ +name: Check cpp formatting + +on: + push: + branches: + - develop + - feature/* + - features/* + - fix/* + +jobs: + build: + name: clang-format + + runs-on: ubuntu-24.04 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Print version + run: clang-format --version + + - name: clang-format + run: cd src && ./format-code.sh + + - name: git diff + run: | + DIFF=`git status --porcelain` + if [[ $DIFF ]]; then + echo "The following files are not well formatted" + echo "$DIFF" + exit 1 + else + echo "Code is well formatted, congrats !" + fi diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 906693e951..2ef3c4b3bb 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -3,6 +3,7 @@ on: push: branches: - 'docker/*' + - dependabot/* jobs: docker_publish: @@ -10,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@master + - uses: actions/checkout@v4 - name: Docker file push uses: elgohr/Publish-Docker-Github-Action@master diff --git a/.github/workflows/download-extract-precompiled-libraries-tgz/action.yml b/.github/workflows/download-extract-precompiled-libraries-tgz/action.yml index 723a604115..d6b87bcaa5 100644 --- a/.github/workflows/download-extract-precompiled-libraries-tgz/action.yml +++ b/.github/workflows/download-extract-precompiled-libraries-tgz/action.yml @@ -1,9 +1,6 @@ name: "Download extract .tgz precompiled libraries" description: "Download and extract .tgz precompiled libraries from antares-deps and antares-simulator repository" inputs: - antares-deps-version: - description: 'antares-deps version' - required: true os: description: 'operational system used for github action' required: true @@ -20,18 +17,12 @@ inputs: runs: using: "composite" - steps: - - name: Download & extract antares-deps - shell: bash - run: | - wget https://github.com/AntaresSimulatorTeam/antares-deps/releases/download/v${{inputs.antares-deps-version}}/rte-antares-deps-${{inputs.os}}-${{inputs.buildtype}}.tar.gz - tar -xvf rte-antares-deps-${{inputs.os}}-${{inputs.buildtype}}.tar.gz - rm -rf rte-antares-deps-${{inputs.os}}-${{inputs.buildtype}}.tar.gz + steps: - name: Download & extract OR-Tools shell: bash run: | - mkdir ${{inputs.ortools-dir}} + mkdir -p ${{inputs.ortools-dir}} cd ${{inputs.ortools-dir}} wget ${{inputs.ortools-url}} -O ortools.zip unzip ortools.zip diff --git a/.github/workflows/download-extract-precompiled-libraries-zip/action.yml b/.github/workflows/download-extract-precompiled-libraries-zip/action.yml index d849dec71f..52eec0beea 100644 --- a/.github/workflows/download-extract-precompiled-libraries-zip/action.yml +++ b/.github/workflows/download-extract-precompiled-libraries-zip/action.yml @@ -1,9 +1,6 @@ name: "Download extract .zip precompiled libraries" description: "Download and extract .zip precompiled libraries from antares-deps and antares-simulator repository" inputs: - antares-deps-version: - description: 'antares-deps version' - required: true os: description: 'operational system used for github action' required: true @@ -20,14 +17,7 @@ inputs: runs: using: "composite" - steps: - - name: Download & extract antares-deps - shell: bash - run: | - wget https://github.com/AntaresSimulatorTeam/antares-deps/releases/download/v${{inputs.antares-deps-version}}/rte-antares-deps-${{inputs.os}}-${{inputs.buildtype}}.zip - unzip rte-antares-deps-${{inputs.os}}-${{inputs.buildtype}}.zip - rm -rf rte-antares-deps-${{inputs.os}}-${{inputs.buildtype}}.zip - + steps: - name: Download & extract OR-Tools shell: bash run: | diff --git a/.github/workflows/doxygen.yml b/.github/workflows/doxygen.yml index 9b91102fa0..ed2bff5fa5 100644 --- a/.github/workflows/doxygen.yml +++ b/.github/workflows/doxygen.yml @@ -4,6 +4,7 @@ on: push: branches: - develop # Set a branch name to trigger deployment + - dependabot/* jobs: deploy: @@ -13,7 +14,7 @@ jobs: concurrency: group: ${{ github.workflow }}-${{ github.ref }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: true # Fetch Hugo themes (true OR recursive) fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod @@ -23,21 +24,21 @@ jobs: git clone https://github.com/jothepro/doxygen-awesome-css.git cd doxygen-awesome-css git checkout v2.2.1 + git apply ../docs/antares-simulator-doxygen.patch - name: Doxygen - uses: mattnotmitt/doxygen-action@1.9.5 + uses: mattnotmitt/doxygen-action@v1.9.8 with: doxyfile-path: docs/Doxyfile - name: Deploy - uses: peaceiris/actions-gh-pages@v3 + uses: peaceiris/actions-gh-pages@v4 # If you're changing the branch from main, # also change the `main` in `refs/heads/main` # below accordingly. - if: github.ref == 'refs/heads/develop' with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./html - + destination_dir: ./doxygen + - \ No newline at end of file diff --git a/.github/workflows/install-cmake-328/action.yml b/.github/workflows/install-cmake-328/action.yml new file mode 100644 index 0000000000..1cf045dbee --- /dev/null +++ b/.github/workflows/install-cmake-328/action.yml @@ -0,0 +1,17 @@ +name: "Install cmake 3.28 using devtoolset 10 if possible" +description: "Download and install system wide cmake 3.28" + +runs: + using: "composite" + steps: + - name: Build cmake + shell: bash + run: | + source /opt/rh/devtoolset-10/enable || true # Ignore error if devtoolset-10 is not available + yum -y install openssl-devel + wget https://github.com/Kitware/CMake/releases/download/v3.28.2/cmake-3.28.2.tar.gz + tar -xvf cmake-3.28.2.tar.gz + cd cmake-3.28.2 + ./bootstrap + make -j$(nproc) + make install diff --git a/.github/workflows/new_release.yml b/.github/workflows/new_release.yml new file mode 100644 index 0000000000..1f3c31f0c3 --- /dev/null +++ b/.github/workflows/new_release.yml @@ -0,0 +1,83 @@ +name: Create new release + +on: + workflow_dispatch: + inputs: + target_branch: + description: "Target branch or full commit SHA" + required: true + release_tag: + description: "Release tag" + required: true + release_name: + description: "Release name" + required: true + run-tests: + description: "Run all tests (true/false)" + required: true + type: string + set_latest: + description: "Set the release as latest" + required: true + type: boolean +jobs: + release: + name: Release pushed tag + runs-on: ubuntu-20.04 + steps: + - name: Create release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + tag: ${{ github.event.inputs.release_tag }} + title: ${{ github.event.inputs.release_name }} + tests: ${{ github.event.inputs.run-tests }} + target_branch: ${{ github.event.inputs.target_branch }} + latest: ${{ github.event.inputs.set_latest }} + run: | + gh release create "$tag" \ + --repo="$GITHUB_REPOSITORY" \ + --title="$title" \ + --notes="Run tests: $tests"\ + --target="$target_branch" \ + --latest=$latest + + + ubuntu: + name: Release - Ubuntu + needs: release + uses: ./.github/workflows/ubuntu.yml + with: + run-tests: ${{ inputs.run-tests }} + target_branch: ${{ inputs.target_branch }} + + windows: + name: Release - Windows + needs: release + uses: ./.github/workflows/windows-vcpkg.yml + with: + run-tests: ${{ inputs.run-tests }} + target_branch: ${{ inputs.target_branch }} + + centos7: + name: Release - centos7 + needs: release + uses: ./.github/workflows/centos7.yml + with: + run-tests: ${{ inputs.run-tests }} + target_branch: ${{ inputs.target_branch }} + + oracle8: + name: Release - oracle8 + needs: release + uses: ./.github/workflows/oracle8.yml + with: + run-tests: ${{ inputs.run-tests }} + target_branch: ${{ inputs.target_branch }} + + user_guide: + name: User Guide + needs: release + uses: ./.github/workflows/build-userguide.yml + with: + run-tests: ${{ inputs.run-tests }} + target_branch: ${{ inputs.target_branch }} diff --git a/.github/workflows/oracle8.yml b/.github/workflows/oracle8.yml index efbff48a81..92b65a9a72 100644 --- a/.github/workflows/oracle8.yml +++ b/.github/workflows/oracle8.yml @@ -6,20 +6,31 @@ on: push: branches: - develop + - dependabot/* + schedule: - cron: '21 2 * * *' + workflow_call: + inputs: + run-tests: + required: true + type: string + target_branch: + required: true + type: string env: GITHUB_TOKEN: ${{ github.token }} - IS_RELEASE: ${{ github.event_name == 'release' && github.event.action == 'created' }} + IS_RELEASE: ${{ github.event_name == 'workflow_dispatch' }} IS_PUSH: ${{ github.event_name == 'push' }} + REF: ${{ inputs.target_branch =='' && github.ref_name || inputs.target_branch}} jobs: build: name: Build env: - ORTOOLSDIR: ${{ github.workspace }}/or-tools + ORTOOLS_DIR: ${{ github.workspace }}/or-tools runs-on: ubuntu-latest container: 'oraclelinux:8' @@ -34,34 +45,75 @@ jobs: - name: Install libraries run: | dnf install -y epel-release git cmake wget rpm-build redhat-lsb-core - dnf install -y unzip libuuid-devel boost-test boost-devel gcc-toolset-9-toolchain + dnf install -y unzip libuuid-devel boost-test boost-devel gcc-toolset-11 zlib-devel - name: Checkout run: | - git clone $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git -b $GITHUB_REF_NAME . + git clone $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git -b ${{ env.REF }} . + git config --global safe.directory '*' - - name: Init submodule + - name: Install VCPKG + # Note: we need to use environment variables instead of workflow variables + # because github messes up path variables when running in container, + # see https://github.com/actions/runner/issues/2058 + run: | + git submodule update --init vcpkg && ./vcpkg/bootstrap-vcpkg.sh -disableMetrics + echo "VCPKG_ROOT=$GITHUB_WORKSPACE/vcpkg" >> $GITHUB_ENV + echo "VCPKG_CACHE_DIR=$GITHUB_WORKSPACE/vcpkg_cache" >> $GITHUB_ENV + echo "VCPKG_BINARY_SOURCES=clear;files,$GITHUB_WORKSPACE/vcpkg_cache,readwrite" >> $GITHUB_ENV + + - name: Restore vcpkg binary dir from cache + id: cache-vcpkg-binary + # Note: we are stuck with v3, because v4 is not compatible with oracle8 image + uses: actions/cache/restore@v3 + with: + path: ${{ env.VCPKG_CACHE_DIR }} + key: vcpkg-cache-oracle8-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} + # Allows to restore a cache when deps have only partially changed (like adding a dependency) + restore-keys: vcpkg-cache-oracle8- + + - name: Config OR-Tools URL run: | - git config --global safe.directory '*' - git submodule update --init --remote src/antares-deps src/tests/resources/Antares_Simulator_Tests + echo "ORTOOLS_URL=https://github.com/rte-france/or-tools/releases/download/$(cat ortools_tag)/ortools_cxx_oraclelinux-8_static_sirius.zip" >> $GITHUB_ENV + + - name: Download & extract OR-Tools + run: | + mkdir -p ${{env.ORTOOLS_DIR}} + cd ${{env.ORTOOLS_DIR}} + wget ${{env.ORTOOLS_URL}} -O ortools.zip + unzip ortools.zip + rm ortools.zip + + - name: Init submodule + run: git submodule update --init --remote src/tests/resources/Antares_Simulator_Tests - name: Install dependencies run: | pip3 install -r src/tests/examples/requirements.txt + - name: Install gh if needed + if: ${{ env.IS_RELEASE == 'true' }} + run: | + dnf -y install 'dnf-command(config-manager)' + dnf -y config-manager --add-repo https://cli.github.com/packages/rpm/gh-cli.repo + dnf -y install gh + - name: Configure run: | - source /opt/rh/gcc-toolset-9/enable - cmake -B _build -S src \ - -DCMAKE_BUILD_TYPE=release \ - -DBUILD_TESTING=ON \ - -DBUILD_TOOLS=OFF \ - -DBUILD_UI=OFF \ + source /opt/rh/gcc-toolset-11/enable + cmake -B _build -S src \ + -DCMAKE_TOOLCHAIN_FILE=$GITHUB_WORKSPACE/vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-linux-release \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTING=ON \ + -DBUILD_TOOLS=ON \ + -DBUILD_UI=OFF \ + -DCMAKE_PREFIX_PATH=${{ env.ORTOOLS_DIR }}/install - name: Build run: | - source /opt/rh/gcc-toolset-9/enable - cmake --build _build --config Release -j2 + source /opt/rh/gcc-toolset-11/enable + cmake --build _build --config Release -j$(nproc) - name: Run unit and end-to-end tests if: ${{ env.IS_PUSH == 'true' }} @@ -80,7 +132,7 @@ jobs: cmake --install . --prefix install pushd . cd install/bin - tar czf ../../antares-solver_oracle8.tar.gz antares-*-solver libsirius_solver.so + tar czf ../../antares-solver_oracle8.tar.gz antares-solver libsirius_solver.so popd rm -rf install @@ -99,21 +151,18 @@ jobs: with: path: _build/*.rpm - publish_assets: - name: Publish assets - needs: build - runs-on: ubuntu-latest - - steps: - - name: Download all artifacts - if: ${{ env.IS_RELEASE == 'true' }} - uses: actions/download-artifact@v3 - - - name: Publish assets if: ${{ env.IS_RELEASE == 'true' }} - uses: alexellis/upload-assets@0.4.0 env: - GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ github.token }} + tag: ${{ github.event.inputs.release_tag }} + run: | + gh release upload "$tag" _build/*.tar.gz _build/*.rpm + + - name: Cache vcpkg binary dir + if: always() + id: save-cache-vcpkg-binary + uses: actions/cache/save@v3 with: - asset_paths: '["*/*.tar.gz", "*/*.rpm"]' + path: ${{ env.VCPKG_CACHE_DIR }} + key: vcpkg-cache-oracle8-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 91d574200a..4587c17919 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -3,10 +3,8 @@ name: SonarCloud on: push: branches: - - main - develop - - release/* - pull_request: + pull_request: jobs: sonarcloud: @@ -15,20 +13,37 @@ jobs: if: "!contains(github.event.head_commit.message, '[skip ci]')" strategy: matrix: - os: [ubuntu-20.04] + os: [ ubuntu-20.04 ] env: SONAR_SERVER_URL: "https://sonarcloud.io" ORTOOLS_DIR: ${{ github.workspace }}/or-tools - ORTOOLS_URL: "https://github.com/rte-france/or-tools/releases/download/v9.5-rte2.0/ortools_cxx_ubuntu-20.04_static_sirius.zip" + # Caching strategy of VCPKG dependencies + VCPKG_BINARY_SOURCES: "clear;files,${{ github.workspace }}/vcpkg_cache,readwrite" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: Install VCPKG + run: git submodule update --init vcpkg && ./vcpkg/bootstrap-vcpkg.sh -disableMetrics + + - name: Restore vcpkg binary dir from cache + id: cache-vcpkg-binary + uses: actions/cache/restore@v4 + with: + path: ${{ github.workspace }}/vcpkg_cache + key: vcpkg-cache-ubuntu-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} + # Allows to restore a cache when deps have only partially changed (like adding a dependency) + restore-keys: vcpkg-cache-ubuntu- + + - name: Config OR-Tools URL + run: | + echo "ORTOOLS_URL=https://github.com/rte-france/or-tools/releases/download/$(cat ortools_tag)/ortools_cxx_ubuntu-20.04_static_sirius.zip" >> $GITHUB_ENV + - name: Install sonar-scanner and build-wrapper - uses: SonarSource/sonarcloud-github-c-cpp@v2 + uses: SonarSource/sonarcloud-github-c-cpp@v3 - name: ccache uses: hendrikmuhs/ccache-action@v1.2 @@ -37,60 +52,55 @@ jobs: - name: Install libraries run: | - sudo apt-get update - sudo apt-get install uuid-dev libwxgtk3.0-gtk3-dev - sudo apt-get install libboost-test-dev - - - name: Read antares-deps version - id: antares-deps-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'antares-deps-version.json' - prop_path: 'antares_deps_version' + sudo apt-get update + sudo apt-get install uuid-dev libwxgtk3.0-gtk3-dev + sudo apt-get install libboost-test-dev + sudo apt-get install g++-10 gcc-10 - name: Download pre-compiled librairies uses: ./.github/workflows/download-extract-precompiled-libraries-tgz with: - antares-deps-version: ${{steps.antares-deps-version.outputs.prop}} os: ${{matrix.os}} buildtype: Debug ortools-url: ${{env.ORTOOLS_URL}} ortools-dir: ${{env.ORTOOLS_DIR}} - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: 3.8 + python-version: 3.12 - name: Install gcovr run: sudo pip install gcovr==5.0 #5.1 generate issues with sonarcloud report parsing - name: Install dependencies run: | - python -m pip install --upgrade pip - pip3 install -r src/tests/examples/requirements.txt + python -m pip install --upgrade pip + pip3 install -r src/tests/examples/requirements.txt - name: Init submodule run: | - git submodule update --init src/antares-deps git submodule update --init --remote src/tests/resources/Antares_Simulator_Tests - name: Configure run: | - cmake -B _build -S src \ - -DCMAKE_C_COMPILER_LAUNCHER=ccache \ - -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ - -DDEPS_INSTALL_DIR=./rte-antares-deps-Debug \ - -DCODE_COVERAGE=ON \ - -DCMAKE_BUILD_TYPE=debug \ - -DCMAKE_PREFIX_PATH="../install;${{ env.ORTOOLS_DIR }}/install" \ - -DBUILD_TESTING=ON \ - -DMZ_CODE_COVERAGE=ON \ - -DBUILD_not_system=OFF + cmake -B _build -S src \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache \ + -DCMAKE_C_COMPILER=/usr/bin/gcc-10 \ + -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ + -DCMAKE_CXX_COMPILER=/usr/bin/g++-10 \ + -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-linux-release \ + -DCODE_COVERAGE=ON \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_PREFIX_PATH="../install;${{ env.ORTOOLS_DIR }}/install" \ + -DBUILD_TESTING=ON \ + -DMZ_CODE_COVERAGE=ON \ + -DPython3_EXECUTABLE='${{ steps.setup-python.outputs.python-path }}' - name: Build run: | - build-wrapper-linux-x86-64 --out-dir $GITHUB_WORKSPACE/_build/output cmake --build _build --config release -j2 + build-wrapper-linux-x86-64 --out-dir $GITHUB_WORKSPACE/_build/output cmake --build _build --config release -j$(nproc) - name: Test and generate coverage continue-on-error: true @@ -107,3 +117,11 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} run: sonar-scanner --define sonar.host.url="${{ env.SONAR_SERVER_URL }}" + + - name: Cache vcpkg binary dir + if: always() + id: save-cache-vcpkg-binary + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/vcpkg_cache + key: vcpkg-cache-ubuntu-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} diff --git a/.github/workflows/ubuntu-system-deps-build.yml b/.github/workflows/ubuntu-system-deps-build.yml deleted file mode 100644 index 34fcc2d91a..0000000000 --- a/.github/workflows/ubuntu-system-deps-build.yml +++ /dev/null @@ -1,71 +0,0 @@ -name: Ubuntu CI (deps. compilation) - -on: - schedule: - - cron: '21 2 * * 1' - -jobs: - - linux: - - runs-on: ${{ matrix.os }} - if: "!contains(github.event.head_commit.message, '[skip ci]')" - strategy: - matrix: - os: [ubuntu-20.04] - - steps: - - uses: actions/checkout@v3 - - - name: ccache - uses: hendrikmuhs/ccache-action@v1.2 - - - name: Install libraries - run: | - sudo apt-get update - sudo apt-get install uuid-dev libwxgtk3.0-gtk3-dev - sudo apt-get install libboost-test-dev - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: 3.8 - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip3 install -r src/tests/examples/requirements.txt - - - name: Init submodule - run: | - git submodule update --init --recursive src - - - name: Configure - run: | - cmake -B _build -S src -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_BUILD_TYPE=release -DBUILD_TESTING=ON - - - name: Build - run: | - cmake --build _build --config release -j2 - - - name: Installer .deb creation - run: | - cd _build - cpack -G DEB - - - name: Installer .tar.gz creation - run: | - cd _build - cpack -G TGZ - - - name: Installer archive upload - uses: actions/upload-artifact@v3 - with: - name: antares-ubuntu-archive - path: _build/*.tar.gz - - - name: Installer deb upload - uses: actions/upload-artifact@v3 - with: - name: antares-ubuntu-deb - path: _build/*.deb diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 07941c0e6d..88fc65ceac 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -1,8 +1,6 @@ name: Ubuntu CI (push and/or release) on: - release: - types: [created] push: branches: - develop @@ -12,14 +10,27 @@ on: - issue-* - release/* - doc/* + - dependabot/* schedule: - cron: '21 2 * * *' + workflow_call: + inputs: + run-tests: + required: true + type: string + target_branch: + required: true + type: string env: GITHUB_TOKEN: ${{ github.token }} - IS_RELEASE: ${{ github.event_name == 'release' && github.event.action == 'created' }} - IS_PUSH: ${{ github.event_name == 'push' }} - RUN_EXTENDED_TESTS: ${{ github.event_name == 'schedule' || github.event_name == 'release' }} + IS_RELEASE: ${{ github.event_name == 'workflow_dispatch' }} + RUN_SIMPLE_TESTS: ${{ github.event_name == 'push' || inputs.run-tests == 'true' }} + RUN_EXTENDED_TESTS: ${{ github.event_name == 'schedule' || inputs.run-tests == 'true' }} + REF: ${{ inputs.target_branch =='' && github.ref || inputs.target_branch}} + VCPKG_ROOT: ${{ github.workspace }}/vcpkg + triplet: x64-linux + WX_CONFIG: /usr/bin/wx-config jobs: @@ -27,243 +38,300 @@ jobs: name: Build env: ORTOOLS_DIR: ${{ github.workspace }}/or-tools + os: ubuntu-20.04 + # Caching strategy of VCPKG dependencies + VCPKG_BINARY_SOURCES: "clear;files,${{ github.workspace }}/vcpkg_cache,readwrite" - outputs: - os: ${{ matrix.os }} - - runs-on: ${{ matrix.os }} + runs-on: ubuntu-20.04 if: "!contains(github.event.head_commit.message, '[skip ci]')" - strategy: - matrix: - os: [ubuntu-20.04] - test-platform: [ubuntu-20.04] steps: - - uses: actions/checkout@v3 - - - name: ccache - uses: hendrikmuhs/ccache-action@v1.2 - with: - key: ${{ matrix.os }} - - - name: Install libraries - run: | - sudo apt-get update - sudo apt-get install uuid-dev libwxgtk3.0-gtk3-dev - sudo apt-get install libboost-test-dev - - - name: Read antares-deps version - id: antares-deps-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'antares-deps-version.json' - prop_path: 'antares_deps_version' - - - - name: Config OR-Tools URL - run: | - echo "ORTOOLS_URL=https://github.com/rte-france/or-tools/releases/download/v9.5-rte2.0/ortools_cxx_ubuntu-20.04_static_sirius.zip" >> $GITHUB_ENV - - - name: Download pre-compiled librairies - uses: ./.github/workflows/download-extract-precompiled-libraries-tgz - with: - antares-deps-version: ${{steps.antares-deps-version.outputs.prop}} - os: ${{matrix.os}} - ortools-url: ${{env.ORTOOLS_URL}} - ortools-dir: ${{env.ORTOOLS_DIR}} - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: 3.x - - - name: Install dependencies - run: | + - uses: actions/checkout@v4 + with: + ref: ${{ env.REF }} + + - name: Install VCPKG + run: git submodule update --init vcpkg && ./vcpkg/bootstrap-vcpkg.sh -disableMetrics + + - name: Restore vcpkg binary dir from cache + id: cache-vcpkg-binary + uses: actions/cache/restore@v4 + with: + path: ${{ github.workspace }}/vcpkg_cache + key: vcpkg-cache-ubuntu-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} + # Allows to restore a cache when deps have only partially changed (like adding a dependency) + restore-keys: vcpkg-cache-ubuntu- + + - name: ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ${{ env.os }} + + - name: Install libraries + run: | + sudo apt-get update + sudo apt-get install uuid-dev libwxgtk3.0-gtk3-dev + sudo apt-get install g++-10 gcc-10 + + - name: Config OR-Tools URL + run: | + echo "ORTOOLS_URL=https://github.com/rte-france/or-tools/releases/download/$(cat ortools_tag)/ortools_cxx_ubuntu-20.04_static_sirius.zip" >> $GITHUB_ENV + + - name: Download pre-compiled librairies + uses: ./.github/workflows/download-extract-precompiled-libraries-tgz + with: + os: ${{env.os}} + ortools-url: ${{env.ORTOOLS_URL}} + ortools-dir: ${{env.ORTOOLS_DIR}} + + - name: Set up Python + id: setup-python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install dependencies + run: | python -m pip install --upgrade pip pip3 install -r src/tests/examples/requirements.txt - - name: Init submodule - run: | - git submodule update --init src/antares-deps - git submodule update --init --remote --recursive src/tests/resources/Antares_Simulator_Tests - - - name: Configure push - run: | - cmake -B _build -S src \ + - name: Configure + run: | + cmake -B _build -S src \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache \ + -DCMAKE_C_COMPILER=/usr/bin/gcc-10 \ + -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ + -DCMAKE_CXX_COMPILER=/usr/bin/g++-10 \ + -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-linux-release \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTING=ON \ + -DBUILD_TOOLS=ON \ + -DCMAKE_PREFIX_PATH=${{ env.ORTOOLS_DIR }}/install \ + -DPython3_EXECUTABLE="${{ env.Python3_ROOT_DIR }}/bin/python" + + - name: Build + run: | + cmake --build _build -j$(nproc) + + - name: Run API tests + run: | + cmake --install _build --prefix antares_install + cd src/api_client_example + cmake -B _build -S . \ -DCMAKE_C_COMPILER_LAUNCHER=ccache \ + -DCMAKE_C_COMPILER=/usr/bin/gcc-10 \ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ - -DDEPS_INSTALL_DIR=${{github.workspace}}/rte-antares-deps-Release \ - -DCMAKE_BUILD_TYPE=release \ + -DCMAKE_CXX_COMPILER=/usr/bin/g++-10 \ + -DCMAKE_BUILD_TYPE=Release \ -DBUILD_TESTING=ON \ - -DBUILD_not_system=OFF \ - -DBUILD_TOOLS=ON \ - -DCMAKE_PREFIX_PATH=${{ env.ORTOOLS_DIR }}/install \ - - - name: Build - run: | - cmake --build _build --config release -j2 - - - # simtest - - name: Read simtest version - id: simtest-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'simtest.json' - prop_path: 'version' - - - name: Run named mps tests - if: ${{ env.IS_PUSH == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-named-mps - os: ${{ matrix.test-platform }} - variant: "named-mps" - - - name: Run unfeasibility-related tests - if: ${{ env.IS_PUSH == 'true' }} - run: | - cd _build - ctest -C Release --output-on-failure -R unfeasible - - - name: Run unit and end-to-end tests - if: ${{ env.IS_PUSH == 'true' }} - run: | - cd _build - ctest -C ${{ matrix.buildtype }} --output-on-failure -L "unit|end-to-end" - - - name: Run kirchhoff constraints tests - if: ${{ false }} - shell: bash - run: | - tar xvf src/tests/kirchhoff-cbuilder/reference.tar.gz -C src/tests/kirchhoff-cbuilder/ - cd _build - ctest -C Release --output-on-failure -R kirchhoff - - - name: Upload logs for failed tests - if: ${{ failure() }} - uses: actions/upload-artifact@v3 - with: - name: test-log - path: ${{ github.workspace }}/_build/Testing/Temporary/LastTest.log - - - name: Run tests about infinity on BCs RHS - if: ${{ env.IS_PUSH == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-v830 - os: ${{ matrix.test-platform }} - - - name: Run tests introduced in v860 - if: ${{ env.IS_PUSH == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-v860 - os: ${{ matrix.test-platform }} - - - name: Run short-tests - if: ${{ env.IS_PUSH == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: short-tests - os: ${{ matrix.test-platform }} - - - name: Run mps tests - if: ${{ env.IS_PUSH == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-mps - os: ${{ matrix.test-platform }} - - - name: Run tests for adequacy patch (CSR) - if: ${{ env.IS_PUSH == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: adequacy-patch-CSR - os: ${{ matrix.test-platform }} - - - name: Run medium-tests - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: medium-tests - os: ${{ matrix.test-platform }} - - - name: Run long-tests-1 - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-1 - os: ${{ matrix.test-platform }} - - - name: Run long-tests-2 - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-2 - os: ${{ matrix.test-platform }} - - - name: Run long-tests-3 - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-3 - os: ${{ matrix.test-platform }} - - - name: Installer .deb creation - run: | + -DCMAKE_TOOLCHAIN_FILE=${{github.workspace}}/vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-linux-release \ + -DCMAKE_PREFIX_PATH="${{github.workspace}}/rte-antares-deps-Release;${{github.workspace}}/install;${{ env.ORTOOLS_DIR }}/install;${{github.workspace}}/antares_install;${{github.workspace}}/rte-antares-deps-Release;${{github.workspace}}/_build/vcpkg_installed/x64-linux-release" + cmake --build _build -j$(nproc) cd _build - cpack -G DEB - - - name: .tar.gz creation - run: | - cd _build - cpack -G TGZ - - - name: Solver archive creation - run: | - cd _build - cmake --install . --prefix install - pushd . - cd install/bin - tar czf ../../antares-solver_ubuntu20.04.tar.gz antares-*-solver libsirius_solver.so - popd - rm -rf install - - - name: Installer archive upload push - uses: actions/upload-artifact@v3 - with: - path: _build/*.tar.gz - - - name: Installer deb upload push - uses: actions/upload-artifact@v3 - with: - path: _build/*.deb - - publish_assets: - name: Publish assets - needs: build - runs-on: ${{needs.build.outputs.os}} - steps: - - name: Download all artifacts - if: ${{ env.IS_RELEASE == 'true' }} - uses: actions/download-artifact@v3 - + ctest -C Release --output-on-failure + + # simtest + - name: Read simtest version + id: simtest-version + uses: notiz-dev/github-action-json-property@release + with: + path: 'simtest.json' + prop_path: 'version' + + - name: Init submodule + run: | + git submodule update --init --remote --recursive src/tests/resources/Antares_Simulator_Tests - - name: Publish assets - if: ${{ env.IS_RELEASE == 'true' }} - uses: alexellis/upload-assets@0.4.0 - env: + - name: Run named mps tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-named-mps + os: ${{ env.os }} + variant: "named-mps" + + - name: Run unfeasibility-related tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + run: | + cd _build + ctest -C Release --output-on-failure -R "^unfeasible$" + + - name: Run unit and end-to-end tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + run: | + cd _build + ctest -C Release --output-on-failure -L "unit|end-to-end" + + - name: Upload logs for failed tests + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: test-log + path: ${{ github.workspace }}/_build/Testing/Temporary/LastTest.log + + - name: Run tests about infinity on BCs RHS + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v830 + os: ${{ env.os }} + + - name: Run MILP with CBC + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-milp + variant: "milp-cbc" + os: ${{ env.os }} + + - name: Run tests introduced in v860 + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v860 + os: ${{ env.os }} + + - name: Run tests introduced in v870 + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v870 + os: ${{ env.os }} + + - name: Run tests introduced in v910 + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v910 + os: ${{ env.os }} + + - name: Run short-tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: short-tests + os: ${{ env.os }} + + - name: Run mps tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-mps + os: ${{ env.os }} + + - name: Run tests for adequacy patch (CSR) + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: adequacy-patch-CSR + os: ${{ env.os }} + + - name: Run parallel tests + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-parallel + os: ${{ env.os }} + variant: "parallel" + + - name: Run tests for time series generator tool + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: ts-generator + os: ${{ env.os }} + variant: "tsgenerator" + + - name: Run medium-tests + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: medium-tests + os: ${{ env.os }} + + - name: Run long-tests-1 + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: long-tests-1 + os: ${{ env.os }} + + - name: Run long-tests-2 + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: long-tests-2 + os: ${{ env.os }} + + - name: Run long-tests-3 + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: long-tests-3 + os: ${{ env.os }} + + - name: Installer .deb creation + run: | + cd _build + cpack -G DEB + + - name: .tar.gz creation + run: | + cd _build + cpack -G TGZ + + - name: Solver archive creation + run: | + cd _build + cmake --install . --prefix install + pushd . + cd install/bin + tar czf ../../antares-solver_ubuntu20.04.tar.gz antares-solver libsirius_solver.so + popd + rm -rf install + + - name: Installer archive upload push + uses: actions/upload-artifact@v4 + with: + name: targz + path: _build/*.tar.gz + + - name: Installer deb upload push + uses: actions/upload-artifact@v4 + with: + name: deb + path: _build/*.deb + + + - name: Publish assets + if: ${{ env.IS_RELEASE == 'true' }} + env: GITHUB_TOKEN: ${{ github.token }} - with: - asset_paths: '["*/*.tar.gz", "*/*.deb"]' + tag: ${{ github.event.inputs.release_tag }} + run: | + gh release upload "$tag" _build/*.tar.gz _build/*.deb + + - name: Cache vcpkg binary dir + if: always() + id: save-cache-vcpkg-binary + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/vcpkg_cache + key: vcpkg-cache-ubuntu-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} diff --git a/.github/workflows/windows-release.yml b/.github/workflows/windows-release.yml deleted file mode 100644 index cdd36467db..0000000000 --- a/.github/workflows/windows-release.yml +++ /dev/null @@ -1,205 +0,0 @@ -name: Windows CI (Release) - -on: - release: - types: [created] - -jobs: - windows: - - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [windows-latest] - include: - - os: windows-latest - triplet: x64-windows - vcpkgPackages: wxwidgets boost-test - test-platform: windows-2022 - env: - # Indicates the location of the vcpkg as a Git submodule of the project repository. - VCPKG_ROOT: ${{ github.workspace }}/vcpkg - ORTOOLS_DIR: ${{ github.workspace }}/or-tools - ORTOOLS_URL: "https://github.com/rte-france/or-tools/releases/download/v9.5-rte2.0/ortools_cxx_windows-latest_static_sirius.zip" - - steps: - - uses: actions/checkout@v3 - - - name: Pre-requisites - shell: cmd - run: | - choco install wget unzip zip --no-progress - - # Restore both vcpkg and its artifacts from the GitHub cache service. - - name: Restore vcpkg and its artifacts. - uses: actions/cache@v3 - with: - # The first path is the location of vcpkg (it contains the vcpkg executable and data files). - # The other paths starting with '!' are exclusions: they contain termporary files generated during the build of the installed packages. - path: | - ${{ env.VCPKG_ROOT }} - !${{ env.VCPKG_ROOT }}/buildtrees - !${{ env.VCPKG_ROOT }}/packages - !${{ env.VCPKG_ROOT }}/downloads - # The key is composed in a way that it gets properly invalidated: this must happen whenever vcpkg's Git commit id changes, or the list of packages changes. In this case a cache miss must happen and a new entry with a new key with be pushed to GitHub the cache service. - # The key includes: hash of the vcpkg.json file, the hash of the vcpkg Git commit id, and the used vcpkg's triplet. The vcpkg's commit id would suffice, but computing an hash out it does not harm. - # Note: given a key, the cache content is immutable. If a cache entry has been created improperly, in order the recreate the right content the key must be changed as well, and it must be brand new (i.e. not existing already). - key: | - ${{ hashFiles( 'vcpkg_manifest/vcpkg.json' ) }}-${{ hashFiles( '.git/modules/vcpkg/HEAD' )}}-${{ matrix.triplet }} - - - name: Setup Python 3.11 - uses: actions/setup-python@v4 - with: - architecture: 'x64' - python-version: '3.11' - - - name : Install deps with VCPKG - run: | - git submodule update --init vcpkg - cd vcpkg - ./bootstrap-vcpkg.sh - vcpkg install ${{matrix.vcpkgPackages}} --triplet ${{matrix.triplet}} - rm -rf buildtrees packages downloads - shell: bash - - - name: Read antares-deps version - id: antares-deps-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'antares-deps-version.json' - prop_path: 'antares_deps_version' - - - name: Download pre-compiled librairies - uses: ./.github/workflows/download-extract-precompiled-libraries-zip - with: - antares-deps-version: ${{steps.antares-deps-version.outputs.prop}} - os: ${{matrix.os}} - ortools-url: ${{env.ORTOOLS_URL}} - ortools-dir: ${{env.ORTOOLS_DIR}} - - - name: Install pip dependencies if necessary - run: pip install -r src/tests/examples/requirements.txt - - # TODO : don't download submodule Antares_Simulator_Tests - - name: Init submodule - run: | - git submodule update --init --recursive src - - - name: Enable git longpaths - run: git config --system core.longpaths true - - - name: Configure with VCPKG - shell: bash - run: | - cmake -B _build -S src \ - -DDEPS_INSTALL_DIR=rte-antares-deps-Release \ - -DCMAKE_PREFIX_PATH="${{env.ORTOOLS_DIR}}/install" \ - -DVCPKG_ROOT="${{env.VCPKG_ROOT}}" \ - -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} \ - -DCMAKE_BUILD_TYPE=release \ - -DBUILD_TESTING=ON \ - -DBUILD_TOOLS=ON \ - -DBUILD_not_system=OFF - - - name: Build - run: | - cmake --build _build --config release -j2 - - - name: Remove OR-Tools install directory to free some disk space - shell: bash - run: rm -rf ${{env.ORTOOLS_DIR}} - - - name: Remove antares-deps to free some disk space - shell: bash - run: rm -rf ${{ github.workspace }}/src/antares-deps - - # TODO : don't download submodule Antares_Simulator_Tests - - name: Remove Antares_Simulator_Tests to free some disk space - shell: bash - run: rm -rf ${{ github.workspace }}/src/tests/resources/Antares_Simulator_Tests - - - name: Remove _deps to free some disk space - shell: bash - run: rm -rf ${{ github.workspace }}/src/_build/_deps - - # simtest - - name: Read simtest version - id: simtest-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'simtest.json' - prop_path: 'version' - - - name: Run tests for adequacy patch (CSR) - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: adequacy-patch-CSR - os: ${{ matrix.test-platform }} - - - name: Run medium-tests - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: medium-tests - os: ${{ matrix.test-platform }} - - - name: Run long-tests-1 - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-1 - os: ${{ matrix.test-platform }} - - - name: Run long-tests-2 - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-2 - os: ${{ matrix.test-platform }} - - - name: Run long-tests-3 - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-3 - os: ${{ matrix.test-platform }} - - - name: .zip creation - shell: bash - run: | - cd _build - cpack -G ZIP - export ZIP_NAME=$(ls *.zip) - echo "ZIP_NAME=$ZIP_NAME" >> $GITHUB_ENV - - - name: Solver archive creation - shell: bash - run: | - cd _build - zip -r antares-solver_windows.zip solver/Release/antares-*-solver.exe solver/Release/*.dll - - - name: NSIS Installer creation - shell: bash - run: | - rm -rf src/tests/resources/Antares_Simulator_Tests - cd _build - cpack -GNSIS - export NSIS_NAME=$(ls *.exe) - echo "NSIS_NAME=$NSIS_NAME" >> $GITHUB_ENV - - - name: Upload NSIS logs - if: ${{ failure() }} - uses: actions/upload-artifact@v3 - with: - name: NSISOutput.log - path: _build/_CPack_Packages/win64/NSIS/NSISOutput.log - - - name: Upload release assets - uses: softprops/action-gh-release@v0.1.15 - if: startsWith(github.ref, 'refs/tags/') - with: - files: | - _build/${{env.NSIS_NAME}} - _build/${{env.ZIP_NAME}} - _build/solver.zip diff --git a/.github/workflows/windows-vcpkg.yml b/.github/workflows/windows-vcpkg.yml index 3a9bc71d65..59e931e6a8 100644 --- a/.github/workflows/windows-vcpkg.yml +++ b/.github/workflows/windows-vcpkg.yml @@ -10,257 +10,329 @@ on: - issue-* - release/* - doc/* + - dependabot/* schedule: - cron: '21 2 * * *' + workflow_call: + inputs: + run-tests: + required: true + type: string + target_branch: + required: true + type: string + +env: + GITHUB_TOKEN: ${{ github.token }} + IS_RELEASE: ${{ github.event_name == 'workflow_dispatch' }} + RUN_SIMPLE_TESTS: ${{ github.event_name == 'push' || inputs.run-tests == 'true' }} + RUN_EXTENDED_TESTS: ${{ github.event_name == 'schedule' || inputs.run-tests == 'true' }} + REF: ${{ inputs.target_branch =='' && github.ref || inputs.target_branch}} + jobs: - windows: - - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [windows-latest] - buildtype: [release] - include: - - os: windows-latest - triplet: x64-windows - vcpkgPackages: wxwidgets boost-test - test-platform: windows-2022 + build: + env: # Indicates the location of the vcpkg as a Git submodule of the project repository. VCPKG_ROOT: ${{ github.workspace }}/vcpkg ORTOOLS_DIR: ${{ github.workspace }}/or-tools - ORTOOLS_URL: "https://github.com/rte-france/or-tools/releases/download/v9.5-rte2.0/ortools_cxx_windows-latest_static_sirius.zip" - RUN_EXTENDED_TESTS: ${{ github.event_name == 'schedule'}} + os: windows-latest + test-platform: windows-2022 + vcpkgPackages: wxwidgets boost-test + triplet: x64-windows-release + # Caching strategy of VCPKG dependencies + VCPKG_BINARY_SOURCES: "clear;files,${{ github.workspace }}/vcpkg_cache,readwrite" + + runs-on: windows-latest steps: - - uses: actions/checkout@v3 - - name: Pre-requisites - shell: cmd - run: | + - uses: actions/checkout@v4 + with: + ref: ${{ env.REF }} + + - name: Config OR-Tools URL + run: | + echo "ORTOOLS_URL=https://github.com/rte-france/or-tools/releases/download/$(cat ortools_tag)/ortools_cxx_windows-latest_static_sirius.zip" >> $GITHUB_ENV + shell: bash + + - name: Pre-requisites + shell: cmd + run: | choco install wget unzip zip --no-progress - - name : Init VCPKG submodule - run: | - git submodule update --init vcpkg - - # Restore both vcpkg and its artifacts from the GitHub cache service. - - name: Restore vcpkg and its artifacts. - uses: actions/cache@v3 - with: - # The first path is the location of vcpkg (it contains the vcpkg executable and data files). - # The other paths starting with '!' are exclusions: they contain termporary files generated during the build of the installed packages. - path: | - ${{ env.VCPKG_ROOT }} - !${{ env.VCPKG_ROOT }}/buildtrees - !${{ env.VCPKG_ROOT }}/packages - !${{ env.VCPKG_ROOT }}/downloads - # The key is composed in a way that it gets properly invalidated: this must happen whenever vcpkg's Git commit id changes, or the list of packages changes. In this case a cache miss must happen and a new entry with a new key with be pushed to GitHub the cache service. - # The key includes: hash of the vcpkg.json file, the hash of the vcpkg Git commit id, and the used vcpkg's triplet. The vcpkg's commit id would suffice, but computing an hash out it does not harm. - # Note: given a key, the cache content is immutable. If a cache entry has been created improperly, in order the recreate the right content the key must be changed as well, and it must be brand new (i.e. not existing already). - key: | - ${{ hashFiles( 'vcpkg_manifest/vcpkg.json' ) }}-${{ hashFiles( '.git/modules/vcpkg/HEAD' )}}-${{ matrix.triplet }} - - - name : Install deps with VCPKG - run: | - cd vcpkg - ./bootstrap-vcpkg.sh - vcpkg install ${{matrix.vcpkgPackages}} --triplet ${{matrix.triplet}} - rm -rf buildtrees packages downloads - shell: bash - - - name: Read antares-deps version - id: antares-deps-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'antares-deps-version.json' - prop_path: 'antares_deps_version' - - - name: Download pre-compiled librairies - uses: ./.github/workflows/download-extract-precompiled-libraries-zip - with: - antares-deps-version: ${{steps.antares-deps-version.outputs.prop}} - os: ${{matrix.os}} - ortools-url: ${{env.ORTOOLS_URL}} - ortools-dir: ${{env.ORTOOLS_DIR}} - - - name: Setup Python 3.11 - uses: actions/setup-python@v4 - with: - architecture: 'x64' - python-version: '3.11' - - - name: Install pip dependencies if necessary - run: pip install -r src/tests/examples/requirements.txt - - - name: Init submodule - run: | - git submodule update --init src/antares-deps - git submodule update --init --remote src/tests/resources/Antares_Simulator_Tests - - - name: Enable git longpaths - run: git config --system core.longpaths true - - - name: Configure - shell: bash - run: | - cmake -B _build -S src \ - -DDEPS_INSTALL_DIR=rte-antares-deps-Release \ - -DCMAKE_PREFIX_PATH="${{ env.ORTOOLS_DIR }}/install" \ - -DVCPKG_ROOT="${{env.VCPKG_ROOT}}" \ - -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} \ - -DCMAKE_BUILD_TYPE=release \ - -DBUILD_TESTING=ON \ - -DBUILD_TOOLS=ON \ - -DBUILD_not_system=OFF - - - name: Build - shell: bash - run: | - cmake --build _build --config release -j2 - - - name: Run unfeasibility-related tests - run: | - cd _build - ctest -C Release --output-on-failure -R unfeasible - - - name: Run unit and end-to-end tests - run: | - cd _build - ctest -C ${{ matrix.buildtype }} --output-on-failure -L "unit|end-to-end" -LE ortools - - - name: Run kirchhoff-constraint-tests - if: ${{ false }} - shell: bash - run: | - tar xvf src/tests/kirchhoff-cbuilder/reference.tar.gz -C src/tests/kirchhoff-cbuilder/ - cd _build - ctest -C Release --output-on-failure -R kirchhoff - - - name: Upload build on failure - if: ${{ failure() }} - uses: actions/upload-artifact@v3 - with: - name: MPS-diff - path: ${{ github.workspace }}/src/tests/mps - - # simtest - - name: Read simtest version - id: simtest-version - uses: notiz-dev/github-action-json-property@release - with: - path: 'simtest.json' - prop_path: 'version' - - - name: Run named mps tests - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-named-mps - os: ${{ matrix.test-platform }} - variant: "named-mps" - - - name: Run tests for adequacy patch (CSR) - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: adequacy-patch-CSR - os: ${{ matrix.test-platform }} - - - name: Run tests about infinity on BCs RHS - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-v830 - os: ${{ matrix.test-platform }} - - - name: Run tests introduced in v860 - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-v860 - os: ${{ matrix.test-platform }} - - - name: Run short-tests - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: short-tests - os: ${{ matrix.test-platform }} - - - name: Run mps tests - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: valid-mps - os: ${{ matrix.test-platform }} - - - name: Run medium-tests - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: medium-tests - os: ${{ matrix.test-platform }} - - - name: Run long-tests-1 - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-1 - os: ${{ matrix.test-platform }} - - - name: Run long-tests-2 - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-2 - os: ${{ matrix.test-platform }} - - - name: Run long-tests-3 - if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} - uses: ./.github/workflows/run-tests - with: - simtest-tag: ${{steps.simtest-version.outputs.prop}} - batch-name: long-tests-3 - os: ${{ matrix.test-platform }} - - - name: Solver archive creation - shell: bash - run: | - cd _build - zip -r antares-solver_windows.zip solver/Release/antares-*-solver.exe solver/Release/*.dll - - - name: NSIS Installer creation - shell: bash - run: | - rm -rf src/tests/resources/Antares_Simulator_Tests - cd _build - cpack -GNSIS - export NSIS_NAME=$(ls *.exe) - echo "NSIS_NAME=$NSIS_NAME" >> $GITHUB_ENV - - - name: Upload NSIS log on failure - if: ${{ failure() }} - uses: actions/upload-artifact@v3 - with: - name: NSISError.log - path: _build/_CPack_Packages/win64/NSIS/NSISOutput.log - - - name: .zip creation - run: | - cd _build - cpack -G ZIP - - - name: Installer upload - uses: actions/upload-artifact@v3 - with: - path: _build/${{env.NSIS_NAME}} - - - name: Archive upload - uses: actions/upload-artifact@v3 - with: - path: _build/*.zip + # Downloads ccache, and copies it to "cl.exe" in order to trick cmake into using it, + # see ccache wiki for background on using it with MSVC: + # https://github.com/ccache/ccache/wiki/MS-Visual-Studio + - name: Install ccache + shell: bash + run: | + wget https://github.com/ccache/ccache/releases/download/v4.8.3/ccache-4.8.3-windows-x86_64.zip -O ccache.zip + unzip ccache.zip + rm ccache.zip + mv ccache-4.8.3-windows-x86_64 ccache + cp ccache/ccache.exe ccache/cl.exe + echo "${GITHUB_WORKSPACE}/ccache" >> $GITHUB_PATH + + - name: ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: windows + + - name: Install VCPKG + shell: bash + run: | + git submodule update --init vcpkg && ./vcpkg/bootstrap-vcpkg.bat -disableMetrics + + - name: Restore vcpkg binary dir from cache + id: cache-vcpkg-binary + uses: actions/cache/restore@v4 + with: + path: ${{ github.workspace }}/vcpkg_cache + key: vcpkg-cache-windows-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} + # Allows to restore a cache when deps have only partially changed (like adding a dependency) + restore-keys: vcpkg-cache-windows- + + - name: Download pre-compiled librairies + uses: ./.github/workflows/download-extract-precompiled-libraries-zip + with: + os: ${{env.os}} + ortools-url: ${{env.ORTOOLS_URL}} + ortools-dir: ${{env.ORTOOLS_DIR}} + + - name: Setup Python 3.12 + uses: actions/setup-python@v5 + id: setup-python + with: + architecture: 'x64' + python-version: '3.12' + + - name: Install pip dependencies if necessary + run: pip install -r src/tests/examples/requirements.txt + + - name: Init submodule + run: | + git submodule update --init --remote src/tests/resources/Antares_Simulator_Tests + + - name: Enable git longpaths + run: git config --system core.longpaths true + + - name: Configure + shell: bash + run: | + cmake -B _build -S src \ + -DCMAKE_PREFIX_PATH="${{ env.ORTOOLS_DIR }}/install" \ + -DVCPKG_ROOT="${{env.VCPKG_ROOT}}" \ + -DVCPKG_TARGET_TRIPLET=${{ env.triplet }} \ + -DCMAKE_TOOLCHAIN_FILE="${{ env.VCPKG_ROOT }}/scripts/buildsystems/vcpkg.cmake" \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTING=ON \ + -DBUILD_TOOLS=ON \ + -DPython3_EXECUTABLE="${{ env.Python3_ROOT_DIR }}/python.exe" \ + -DCMAKE_VS_GLOBALS="CLToolExe=cl.exe;CLToolPath=${GITHUB_WORKSPACE}/ccache;TrackFileAccess=false;UseMultiToolTask=true;DebugInformationFormat=OldStyle" + + - name: Build + shell: bash + run: | + cmake --build _build --config Release -j$(nproc) + # simtest + - name: Read simtest version + id: simtest-version + uses: notiz-dev/github-action-json-property@release + with: + path: 'simtest.json' + prop_path: 'version' + + - name: Run named mps tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-named-mps + os: ${{ env.test-platform }} + variant: "named-mps" + + - name: Run unfeasibility-related tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + run: | + cd _build + ctest -C Release --output-on-failure -R "^unfeasible$" + + - name: Run unit and end-to-end tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + run: | + cd _build + ctest -C Release --output-on-failure -L "unit|end-to-end" -LE ortools + + - name: Upload build on failure + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: MPS-diff + path: ${{ github.workspace }}/src/tests/mps + + - name: Run tests for adequacy patch (CSR) + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: adequacy-patch-CSR + os: ${{ env.test-platform }} + + - name: Run tests about infinity on BCs RHS + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v830 + os: ${{ env.test-platform }} + + - name: Run MILP with CBC + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-milp + variant: "milp-cbc" + os: ${{ env.test-platform }} + + - name: Run tests introduced in v860 + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v860 + os: ${{ env.test-platform }} + + - name: Run tests introduced in v870 + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v870 + os: ${{ env.test-platform }} + + - name: Run tests introduced in v910 + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-v910 + os: ${{ env.test-platform }} + + - name: Run short-tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: short-tests + os: ${{ env.test-platform }} + + - name: Run mps tests + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-mps + os: ${{ env.test-platform }} + + - name: Run parallel tests + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: valid-parallel + os: ${{ env.test-platform }} + variant: "parallel" + + - name: Run tests for time series generator tool + if: ${{ env.RUN_SIMPLE_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: ts-generator + os: ${{ env.test-platform }} + variant: "tsgenerator" + + - name: Run medium-tests + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: medium-tests + os: ${{ env.test-platform }} + + - name: Run long-tests-1 + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: long-tests-1 + os: ${{ env.test-platform }} + + - name: Run long-tests-2 + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: long-tests-2 + os: ${{ env.test-platform }} + + - name: Run long-tests-3 + if: ${{ env.RUN_EXTENDED_TESTS == 'true' }} + uses: ./.github/workflows/run-tests + with: + simtest-tag: ${{steps.simtest-version.outputs.prop}} + batch-name: long-tests-3 + os: ${{ env.test-platform }} + + - name: Solver archive creation + shell: bash + run: | + cd _build + zip -r antares-solver_windows.zip solver/Release/antares-solver.exe solver/Release/*.dll + + - name: NSIS Installer creation + shell: bash + run: | + rm -rf src/tests/resources/Antares_Simulator_Tests + cd _build + cpack -GNSIS + export NSIS_NAME=$(ls *.exe) + echo "NSIS_NAME=$NSIS_NAME" >> $GITHUB_ENV + + - name: Upload NSIS log on failure + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: NSISError.log + path: _build/_CPack_Packages/win64/NSIS/NSISOutput.log + + - name: .zip creation + run: | + cd _build + cpack -G ZIP + + - name: Installer upload + uses: actions/upload-artifact@v4 + with: + name: installer + path: _build/${{env.NSIS_NAME}} + + - name: Publish assets + if: ${{ env.IS_RELEASE == 'true' }} + env: + GITHUB_TOKEN: ${{ github.token }} + tag: ${{ github.event.inputs.release_tag }} + run: | + gh release upload "$tag" _build/*.zip _build/*.exe + shell: bash + + - name: Cache vcpkg binary dir + if: always() + id: save-cache-vcpkg-binary + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/vcpkg_cache + key: vcpkg-cache-windows-${{ hashFiles('src/vcpkg.json', '.git/modules/vcpkg/HEAD') }} diff --git a/.gitignore b/.gitignore index 1afaf89c00..1a35b988bf 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,7 @@ Makefile *.layout src/.vs -src/config.h +src/config/include/antares/config/config.h # Yuni src/ext/yuni/src/ProfileBuild.cmake diff --git a/.gitmodules b/.gitmodules index 9bee42d242..77fb4921c7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,7 +1,3 @@ -[submodule "src/antares-deps"] - path = src/antares-deps - url = https://github.com/AntaresSimulatorTeam/antares-deps.git - branch = v2.0.2b [submodule "src/tests/resources/Antares_Simulator_Tests"] path = src/tests/resources/Antares_Simulator_Tests url = https://github.com/AntaresSimulatorTeam/Antares_Simulator_Tests.git diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 63485bf851..ba7010934b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,35 +1,55 @@ # How to contribute to Antares Simulator -## Reporting bug -- Make sure that the bug was not already reported by searching on GitHub under [Issues](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues). +## Reporting a bug +- First, please make sure that the bug has not been already reported under [Issues](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues). -- If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/new). You must provide : - - description of bug and unexpected behavior - - expected behavior - - small antares study to reproduce unexpected behavior - - Antares Simulator version and OS used +- If not, [open a new one](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/new). You must provide : + - a description of the bug and its unexpected behavior + - the expected behavior + - a small antares study to reproduce the unexpected behavior + - the version of Antares Simulator and OS used -## Developpement -Antares Simulator team will be pleased to have some developpers join our project. +## Development +Antares Simulator team will be pleased to have developers join our project. -You can find all steps needed for compilation and installation of Antares Simulator in [INSTALL.md](INSTALL.md). +You can find all the steps needed to build & install Antares Simulator in +the [documentation website](https://antares-simulator.readthedocs.io/) +or [its sources](docs/developer-guide/0-Introduction.md). ### Branch names -Currently CI is runned only for specific branch names : +Currently, CI is run only for specific branch names: - `feature/*` - `features/*` - `fix/*` - `release/*` +- `issue-*` +- `doc/*` -If you create a branch with a different name no CI will be runned but you should receive an email indicating that your branch name is incorrect. +If you create a branch with a different name, no CI will be run, but you will receive an email +indicating that your branch name is incorrect. -In order to avoid pushing with invalid branch name, a git hooks is provided for pre-commit check. This hooks is available in `.githooks` directory. +In order to avoid pushing with invalid branch name, a git hook is provided for pre-commit check. +This hook is available in the `.githooks` directory. -By default git use hooks in `.git/hooks` directory which is not under version control. You can define a new hooks directory with this command in Antares Simulator root directory : +By default, git use hooks in `.git/hooks` directory which is not under version control. You can +define a new hooks directory with this command in Antares Simulator root directory : ``` git config core.hooksPath .githooks ``` ### Code formatting We're using [clang-format](https://clang.llvm.org/docs/ClangFormat.html) to format code. Rules are defined in [.clang-format](src/.clang-format) file. + +### Pull Requests + +A pull request name must be self-explanatory: this will be the default commit title when merging. + +Please provide a description in the head comment of the PR. This description will be the details of the merge commit. +The description should be short but proportional to the length or complexity of the PR. Try to explain the motivation +of the PR (why) and the method employed (how). + +When a pull request is opened, please set it to draft if it is still being worked on or not ready for review. + +If your Pull Request changes a part of the code that is [documented](https://antares-simulator.readthedocs.io/), +please update the documentation also, in the ["docs"](docs) directory. \ No newline at end of file diff --git a/COPYING.txt b/COPYING.txt index a7adc9ffa5..c1aabfe8a4 100644 --- a/COPYING.txt +++ b/COPYING.txt @@ -1,725 +1,162 @@ -Valid-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +Valid-License-Identifier: MPL-2.0 License-Text: +Copyright (C) 2007-2024 RTE +Mozilla Public License +Version 2.0 +1. Definitions -Copyright (C) 2007-2018 RTE -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 . - -In accordance with the terms of section 7 (7. Additional Terms.) of -the GNU GPL v3, the copyright holders of this Program add the -following Additional permissions: - -* If you modify this Program, or any covered work, by linking or -combining it with OpenSSL (or a modified version of that library), -containing parts covered by the terms of the OpenSSL license, the -copyright holders of this Program grant you additional permission to -convey the resulting work. Corresponding Source for a non-source form -of such a combination shall include the source code for the parts of -OpenSSL used as well as that of the covered work. - -* The terms "Sirius_Solver Substitution Exception" may be used to -refer to the permission defined in the next two paragraphs. - -In the following paragraph, the terms "Non-GPL code" mean code that is -covered neither by the GNU GPL v3 nor by a GPL-compatible license. -The terms "Eligible Interface" mean the interface definition files of -the Sirius_Solver library (version 6.0.0 or later). - -If you modify this Program, or any covered work, by linking it with -Non-GPL code through an Eligible Interface, the copyright holders of -this Program grant you additional conditional permission to convey the -resulting work. The condition to which the use of the permission is -subject to is that you replace the three characters between brackets -at the end of this line by the version identifiers of the Sirius_Solver -library whose eligible interface you make use of : [X.Y.Z] - -* As a special exception, the copyright holders of this Program give -you permission to link this software with libYuni library, licensed -under MPL-2.0, to produce an executable without applying the GNU GPL -v3 to the library itself providing that you meet the terms and -conditions of the MPL-2.0 on this library. - -### GNU GENERAL PUBLIC LICENSE - -Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. - - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -### Preamble - -The GNU General Public License is a free, copyleft license for -software and other kinds of works. - -The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom -to share and change all versions of a program--to make sure it remains -free software for all its users. We, the Free Software Foundation, use -the GNU General Public License for most of our software; it applies -also to any other work released this way by its authors. You can apply -it to your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you -have certain responsibilities if you distribute copies of the -software, or if you modify it: responsibilities to respect the freedom -of others. - -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - -Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - -Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the -manufacturer can do so. This is fundamentally incompatible with the -aim of protecting users' freedom to change the software. The -systematic pattern of such abuse occurs in the area of products for -individuals to use, which is precisely where it is most unacceptable. -Therefore, we have designed this version of the GPL to prohibit the -practice for those products. If such problems arise substantially in -other domains, we stand ready to extend this provision to those -domains in future versions of the GPL, as needed to protect the -freedom of users. - -Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish -to avoid the special danger that patents applied to a free program -could make it effectively proprietary. To prevent this, the GPL -assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and -modification follow. - -### TERMS AND CONDITIONS - -#### 0. Definitions. - -"This License" refers to version 3 of the GNU General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds -of works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of -an exact copy. The resulting work is called a "modified version" of -the earlier work or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based -on the Program. - -To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - -To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user -through a computer network, with no transfer of a copy, is not -conveying. - -An interactive user interface displays "Appropriate Legal Notices" to -the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -#### 1. Source Code. - -The "source code" for a work means the preferred form of the work for -making modifications to it. "Object code" means any non-source form of -a work. - -A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can -regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same -work. - -#### 2. Basic Permissions. - -All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, -without conditions so long as your license otherwise remains in force. -You may convey covered works to others for the sole purpose of having -them make modifications exclusively for you, or provide you with -facilities for running those works, provided that you comply with the -terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for -you must do so exclusively on your behalf, under your direction and -control, on terms that prohibit them from making any copies of your -copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes -it unnecessary. - -#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - -No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such -circumvention is effected by exercising rights under this License with -respect to the covered work, and you disclaim any intention to limit -operation or modification of the work as a means of enforcing, against -the work's users, your or third parties' legal rights to forbid -circumvention of technological measures. - -#### 4. Conveying Verbatim Copies. - -You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - -#### 5. Conveying Modified Source Versions. - -You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these -conditions: - -- a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. -- b) The work must carry prominent notices stating that it is - released under this License and any conditions added under - section 7. This requirement modifies the requirement in section 4 - to "keep intact all notices". -- c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. -- d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - -A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - -#### 6. Conveying Non-Source Forms. - -You may convey a covered work in object code form under the terms of -sections 4 and 5, provided that you also convey the machine-readable -Corresponding Source under the terms of this License, in one of these -ways: - -- a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. -- b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the Corresponding - Source from a network server at no charge. -- c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. -- d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. -- e) Convey the object code using peer-to-peer transmission, - provided you inform other peers where the object code and - Corresponding Source of the work are being offered to the general - public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, -family, or household purposes, or (2) anything designed or sold for -incorporation into a dwelling. In determining whether a product is a -consumer product, doubtful cases shall be resolved in favor of -coverage. For a particular product received by a particular user, -"normally used" refers to a typical or common use of that class of -product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected -to use, the product. A product is a consumer product regardless of -whether the product has substantial commercial, industrial or -non-consumer uses, unless such uses represent the only significant -mode of use of the product. - -"Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to -install and execute modified versions of a covered work in that User -Product from a modified version of its Corresponding Source. The -information must suffice to ensure that the continued functioning of -the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or -updates for a work that has been modified or installed by the -recipient, or for the User Product in which it has been modified or -installed. Access to a network may be denied when the modification -itself materially and adversely affects the operation of the network -or violates the rules and protocols for communication across the -network. - -Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - -#### 7. Additional Terms. - -"Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders -of that material) supplement the terms of this License with terms: - -- a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or -- b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or -- c) Prohibiting misrepresentation of the origin of that material, - or requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or -- d) Limiting the use for publicity purposes of names of licensors - or authors of the material; or -- e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or -- f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions - of it) with contractual assumptions of liability to the recipient, - for any liability that these contractual assumptions directly - impose on those licensors and authors. - -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; the -above requirements apply either way. - -#### 8. Termination. - -You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - -However, if you cease all violation of this License, then your license -from a particular copyright holder is reinstated (a) provisionally, -unless and until the copyright holder explicitly and finally -terminates your license, and (b) permanently, if the copyright holder -fails to notify you of the violation by some reasonable means prior to -60 days after the cessation. - -Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - -#### 9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or run -a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - -#### 10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - -#### 11. Patents. - -A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned -or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - -If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - -A patent license is "discriminatory" if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on -the non-exercise of one or more of the rights that are specifically -granted under this License. You may not convey a covered work if you -are a party to an arrangement with a third party that is in the -business of distributing software, under which you make payment to the -third party based on the extent of your activity of conveying the -work, and under which the third party grants, to any of the parties -who would receive the covered work from you, a discriminatory patent -license (a) in connection with copies of the covered work conveyed by -you (or copies made from those copies), or (b) primarily for and in -connection with specific products or compilations that contain the -covered work, unless you entered into that arrangement, or that patent -license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - -#### 12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under -this License and any other pertinent obligations, then as a -consequence you may not convey it at all. For example, if you agree to -terms that obligate you to collect a royalty for further conveying -from those to whom you convey the Program, the only way you could -satisfy both those terms and this License would be to refrain entirely -from conveying the Program. - -#### 13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - -#### 14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions -of the GNU General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in -detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or -of any later version published by the Free Software Foundation. If the -Program does not specify a version number of the GNU General Public -License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions -of the GNU General Public License can be used, that proxy's public -statement of acceptance of a version permanently authorizes you to -choose that version for the Program. - -Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - -#### 15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT -WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND -PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR -CORRECTION. - -#### 16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR -CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES -ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT -NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR -LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM -TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER -PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -#### 17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - -END OF TERMS AND CONDITIONS - -### How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these -terms. - -To do so, attach the following notices to the program. It is safest to -attach them to the start of each source file to most effectively state -the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper -mail. - -If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands \`show w' and \`show c' should show the -appropriate parts of the General Public License. Of course, your -program's commands might be different; for a GUI interface, you would -use an "about box". - -You should also get your employer (if you work as a programmer) or -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. For more information on this, and how to apply and follow -the GNU GPL, see . - -The GNU General Public License does not permit incorporating your -program into proprietary programs. If your program is a subroutine -library, you may consider it more useful to permit linking proprietary -applications with the library. If this is what you want to do, use the -GNU Lesser General Public License instead of this License. But first, -please read . \ No newline at end of file +1.1. “Contributor†+ + means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. +1.2. “Contributor Version†+ + means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. +1.3. “Contribution†+ + means Covered Software of a particular Contributor. +1.4. “Covered Software†+ + means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. +1.5. “Incompatible With Secondary Licenses†+ + means + + that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or + + that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. + +1.6. “Executable Form†+ + means any form of the work other than Source Code Form. +1.7. “Larger Work†+ + means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. +1.8. “License†+ + means this document. +1.9. “Licensable†+ + means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. +1.10. “Modifications†+ + means any of the following: + + any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or + + any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims†of a Contributor + + means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. +1.12. “Secondary License†+ + means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. +1.13. “Source Code Form†+ + means the form of the work preferred for making modifications. +1.14. “You†(or “Yourâ€) + + means an individual or a legal entity exercising rights under this License. For legal entities, “You†includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control†means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants and Conditions +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + + under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and + + under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: + + for any code that a Contributor has removed from Covered Software; or + + for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or + + under Patent Claims infringed by Covered Software in the absence of its Contributions. + +This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). +2.5. Representation + +Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. +2.6. Fair Use + +This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. +3. Responsibilities +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + + such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and + + You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). +3.4. Notices + +You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. +4. Inability to Comply Due to Statute or Regulation + +If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. +5. Termination + +5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. +6. Disclaimer of Warranty + +Covered Software is provided under this License on an “as is†basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. +7. Limitation of Liability + +Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. +8. Litigation + +Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. +9. Miscellaneous + +This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. +10. Versions of the License +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. +10.3. Modified Versions + +If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + +If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. +Exhibit B - “Incompatible With Secondary Licenses†Notice + + This Source Code Form is “Incompatible With Secondary Licensesâ€, as defined by the Mozilla Public License, v. 2.0. diff --git a/INSTALL.md b/INSTALL.md deleted file mode 100644 index 3f848b99cd..0000000000 --- a/INSTALL.md +++ /dev/null @@ -1,5 +0,0 @@ -For build instruction see [doc/build/0-INSTALL.md](docs/build/0-INSTALL.md) - -For better readability see [readthedocs documentation](readthedocs-antares) - -[readthedocs-antares]: https://antares-doc.readthedocs.io/ \ No newline at end of file diff --git a/NEWS.md b/NEWS.md index f24a4c7442..9d36d912f2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,4 +1,4 @@ Antares Changelog ================= -Please refer to [docs/CHANGELOG.md](docs/CHANGELOG.md) +Please refer to [docs/developer-guide/CHANGELOG.md](docs/developer-guide/CHANGELOG.md) diff --git a/README.md b/README.md index dea3006bc4..df15f52b86 100644 --- a/README.md +++ b/README.md @@ -1,85 +1,84 @@ # Antares Simulator -[![Status][ubuntu_precompiled_svg]][ubuntu_precompiled_link] [![Status][windows_precompiled_svg]][windows_precompiled_link] [![Status][centos_precompiled_svg]][centos_precompiled_link] [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=AntaresSimulatorTeam_Antares_Simulator&metric=alert_status)](https://sonarcloud.io/dashboard?id=AntaresSimulatorTeam_Antares_Simulator) - -[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) - - - -Antares Simulator is an open source power system simulator meant to be -used by anybody placing value in quantifying the adequacy or the -economic performance of interconnected power systems, at short or -remote time horizons: - -Transmission system Operators, Power Producers, Regulators, Academics, -Consultants, NGO and all others actors concerned by energy policy issues +[![Status][ubuntu_ci_svg]][ubuntu_ci_link] +[![Status][windows_ci_svg]][windows_ci_link] +[![Status][centos_ci_svg]][centos_ci_link] +[![Status][oraclelinux_ci_svg]][oraclelinux_ci_link] +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=AntaresSimulatorTeam_Antares_Simulator&metric=alert_status)](https://sonarcloud.io/dashboard?id=AntaresSimulatorTeam_Antares_Simulator) +[![License: MPL v2](https://img.shields.io/badge/License-MPLv2-blue.svg)](https://www.mozilla.org/en-US/MPL/2.0/) +[![ReadTheDocs](https://readthedocs.org/projects/antares-simulator/badge/?version=stable)](https://antares-simulator.readthedocs.io/en/stable/?badge=stable) + +![C++](https://img.shields.io/badge/c++-%2300599C.svg?style=for-the-badge&logo=c%2B%2B&logoColor=white) + +Antares Simulator is an open-source power system simulator. +It is meant to be used by anybody placing value in quantifying the adequacy, or the +economic performance, of interconnected power systems, at short or +remote time horizons: + +Transmission system operators, power producers, regulators, academics, +consultants, NGOs and all others actors concerned by energy policy issues are welcome to use the software. -The Antares Simulator project was initiated by RTE (French Electricity -Transmission system Operator) in 2007. It was developed from the start -as a cross-platform application (Windows, GNU/Linux ,Unix). - -Until 2018 it was distributed under the terms of a proprietary license. +The Antares Simulator project was initiated by RTE (French Electricity +Transmission system Operator) in 2007. It has been developed since the beginning +as a cross-platform application (Windows, GNU/Linux, Unix). -In May 2018 RTE decided to release the project under the GPLv3 license. +Until 2018, it had been distributed under the terms of a proprietary license. -[linux_system_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Linux%20CI%20(system%20libs)/badge.svg +In May 2018, RTE decided to release the project under the GPLv3 license. -[linux_system_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Linux%20CI%20(system%20libs)" - -[windows_vcpkg_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG)/badge.svg - -[windows_vcpkg_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG)" - -[centos7_system_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(system%20libs)/badge.svg - -[centos7_system_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(system%20libs)" +In January 2024, RTE, as the exclusive copyright owner, decided to switch from the GPLv3 to the MPLv2 license, +starting with the 9.0 version of Antares Simulator. +The GUI is deprecated in favor of [Antares Web](https://antares-web.readthedocs.io). # Links: -- Antares web site : https://antares-simulator.org -- RTE web site : http://www.rte-france.com/ -- Doxygen code documentation : https://antaressimulatorteam.github.io/Antares_Simulator/ - +- Antares website: https://antares-simulator.org +- RTE web site : http://www.rte-france.com/ +- Doxygen code documentation: https://antaressimulatorteam.github.io/Antares_Simulator/doxygen +- Antares Web: https://antares-web.readthedocs.io # Installation This software suite has been tested under: -* Ubuntu 20.04 [![Status][ubuntu_precompiled_svg]][ubuntu_precompiled_link] -* Microsoft Windows with Visual Studio 2019 (64-bit) [![Status][windows_precompiled_svg]][windows_precompiled_link] -* Centos7 [![Status][centos_precompiled_svg]][centos_precompiled_link] +* Ubuntu 20.04 [![Status][ubuntu_ci_svg]][ubuntu_ci_link] +* Microsoft Windows with Visual Studio 2022 (64-bit) [![Status][windows_ci_svg]][windows_ci_link] +* Centos7 [![Status][centos_ci_svg]][centos_ci_link] +* Oracle Linux [![Status][oraclelinux_ci_svg]][oraclelinux_ci_link] Antares Simulator is built using CMake. -For installation instructions, please visit [INSTALL.md](INSTALL.md) +For installation instructions, please visit the [documentation website](https://antares-simulator.readthedocs.io/) +or [its sources](docs/developer-guide/0-Introduction.md). # Source Code Content * [AUTHORS](AUTHORS.txt) - Antares Simulator authors * [CERTIFICATE](CERTIFICATE.txt) - A standard DCO that has to be signed by every contributor -* [CONTRIBUTING](CONTRIBUTING.txt) - How to submit patches and discuss about code evolutions -* [COPYING](COPYING.txt) - The GPL v3 license. -* [INSTALL](INSTALL.md) - Installation and building instructions. +* [CONTRIBUTING](CONTRIBUTING.md) - How to submit patches and discuss code evolutions +* [COPYING](COPYING.txt) - The MPL v2 license. * [NEWS](NEWS.md) - Important modifications between the releases. * [README](README.md) - This file. -* [ROADMAP](ROADMAP.txt) - Main orientations for further developements +* [ROADMAP](ROADMAP.txt) - Main orientations for further developments * [THANKS](THANKS.txt) - Attribution notices for external libraries and contributors. -* [resources/](resources) - Free sample data sets. +* [resources/](resources) - Free sample data sets. * [src/analyzer/](src/analyzer) - source code for the statistical analysis of historical time-series. -* [src/cmake/](src/cmake) - files for initializing a solution ready for compilation. -* [src/distrib/](src/distrib) - system redistributable libraries Win(x64,x86),unix. +* [src/cmake/](src/cmake) - files for initializing a solution ready for compilation. +* [src/distrib/](src/distrib) - system redistributable libraries Win(x64,x86),unix. * [src/ext/](src/ext) - third party libraries used by Antares_Simulator: libYuni, Sirius_Solver. * [src/libs/](src/libs) - miscellaneous Antares_Simulator libraries. * [src/solver/](src/solver) - simulation and optimization part. -* [src/tools/](src/tools) - miscellaneous tools for dataset management. -* [src/ui/](src/ui) - Graphic user interface. +* [src/tools/](src/tools) - miscellaneous tools for dataset management. +* [src/ui/](src/ui) - Graphic user interface. +[ubuntu_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(push%20and/or%20release)/badge.svg +[ubuntu_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(push%20and/or%20release)" -[ubuntu_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(pre-compiled)/badge.svg -[ubuntu_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(pre-compiled)" +[windows_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg +[windows_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" -[windows_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg -[windows_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" +[centos_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(push%20and/or%20release)/badge.svg +[centos_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(push%20and/or%20release)" -[centos_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(pre-compiled)/badge.svg -[centos_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(pre-compiled)" +[oraclelinux_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Oracle%208%20CI%20(push%20and/or%20release)/badge.svg +[oraclelinux_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Oracle%208%20CI%20(push%20and/or%20release)" diff --git a/antares-deps-version.json b/antares-deps-version.json deleted file mode 100644 index ced7f5add0..0000000000 --- a/antares-deps-version.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "antares_deps_version": "2.0.2b" -} diff --git a/docs/Architecture/API_usage_example-Nominal_example_of_Simulator_API_usage.svg b/docs/Architecture/API_usage_example-Nominal_example_of_Simulator_API_usage.svg new file mode 100644 index 0000000000..61648e8af7 --- /dev/null +++ b/docs/Architecture/API_usage_example-Nominal_example_of_Simulator_API_usage.svg @@ -0,0 +1 @@ +Nominal example of Simulator API usageClientClientSimulatorAPISimulatorAPISimulationResultSimulationResultPerformSimulation(/path/to/study, 4 /*Force parallelization*/ )Simulator perfor the simulation on the designated studySimulationResultGetHebdoProblems()HebdoProblemsGetSimulationOutputDir()path to simulation file resultsDoStuff(HebdoProblems, simulation_path) \ No newline at end of file diff --git a/docs/Architecture/API_usage_example.puml b/docs/Architecture/API_usage_example.puml new file mode 100644 index 0000000000..6887c4ed5c --- /dev/null +++ b/docs/Architecture/API_usage_example.puml @@ -0,0 +1,20 @@ +@startuml +'https://plantuml.com/sequence-diagram + +title Nominal example of Simulator API usage + +Actor Client +Boundary SimulatorAPI + +Client -> SimulatorAPI: PerformSimulation(/path/to/study, 4 /*Force parallelization*/ ) +activate SimulatorAPI +rnote over SimulatorAPI: Antares-Simulator performs the simulation on the designated study +SimulatorAPI --> Client: SimulationResult +deactivate SimulatorAPI +Client -> SimulationResult: GetHebdoProblems() +SimulationResult --> Client: HebdoProblems +Client -> SimulationResult: GetSimulationOutputDir() +SimulationResult --> Client: path to simulation file results +Client -> Client: DoStuff(HebdoProblems, simulation_path) + +@enduml \ No newline at end of file diff --git a/docs/Architecture_Decision_Records/Expose_cpp_API.md b/docs/Architecture_Decision_Records/Expose_cpp_API.md new file mode 100644 index 0000000000..fcc11c8a93 --- /dev/null +++ b/docs/Architecture_Decision_Records/Expose_cpp_API.md @@ -0,0 +1,22 @@ +# Expose public C++ API + +## Status: Accepted [2024/02/26] + +## Context + +Several clients, such as Xpansion, express a preference for utilizing a library over a command-line interface (CLI) tool. Exposing a library necessitates the exposure of a public API. + +This API can be presented in either pure C or C++. It's worth noting that a C API can always serve as a facade atop a C++ API. + +In the case of a C++ API, concerns regarding ABI compatibility are alleviated, as the Simulator library is provided in a static form. Consequently, when a client upgrades, they would simply need to recompile and relink with the new version of the library. + +## Decision + +Expose C++ public API. + +## Consequences + +* This allow clients to bind to library directly and not use CLI client +* Allow data transmission between client and library without resorting to files +* Allow describing a pure C API in the future if the need comes +* Need to maintain API/ABI versioning and communicate changes/breaking changes diff --git a/docs/Architecture_Decision_Records/separate_install_exe_api.md b/docs/Architecture_Decision_Records/separate_install_exe_api.md new file mode 100644 index 0000000000..3a9662ec1d --- /dev/null +++ b/docs/Architecture_Decision_Records/separate_install_exe_api.md @@ -0,0 +1,25 @@ +# Expose public C++ API + +## Status: Rejected [2024/04/11] + +## Context + +Originally, there exists a single install target designated to deploy the diverse Antares executables, predominantly packaged within the release assets. However, there's a rationale behind avoiding the creation of a unified package containing both executables and libraries, given that they cater to distinct user demographics. This mirrors the flexibility offered by package managers such as apt, where users can opt to install binary packages and separate development (devel) packages according to their requirements. + +## Decision + +Split installation into two targets + +Produce different assets/packages for each install targets. + + +## Consequences + +* Mutltiplication of assets +* Two install targets to manage +* Users of executable not "polluted" by libraries + +## Reason for rejection + +The decision was rejected because it was deemed unnecessary to split the installation targets. It adds +some difficulties for few benefits at the moment \ No newline at end of file diff --git a/docs/Architecture_Decision_Records/use_interface_in_cmake.md b/docs/Architecture_Decision_Records/use_interface_in_cmake.md new file mode 100644 index 0000000000..dd6ad55ef8 --- /dev/null +++ b/docs/Architecture_Decision_Records/use_interface_in_cmake.md @@ -0,0 +1,18 @@ +# Use $ in CMakeLists + +## Status: accepted + +## Context +Using BUILD_INTERFACE is required to allow build system to find include at the right place during compilation on a local +machine while still maintaining the possibility to resolve include path once installed. + +INSTALL_INTERFACE can be used when different path is required between build and installation + +## Decision + +Accepted + +## Consequences + +Use BUILD_INTERFACE in CMakeLists +E.g : Add a public include as $ diff --git a/docs/Doxyfile b/docs/Doxyfile index 24c257cd98..ba758079b7 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -54,7 +54,7 @@ PROJECT_NUMBER = # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. -PROJECT_BRIEF = +PROJECT_BRIEF = Power System Simulator # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 @@ -943,7 +943,7 @@ WARN_LOGFILE = # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. -INPUT = src/ +INPUT = README.md src/ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses @@ -1158,7 +1158,7 @@ FILTER_SOURCE_PATTERNS = # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. -USE_MDFILE_AS_MAINPAGE = +USE_MDFILE_AS_MAINPAGE = README.md # The Fortran standard specifies that for fixed formatted Fortran code all # characters from position 72 are to be considered as comment. A common @@ -1357,7 +1357,7 @@ HTML_FILE_EXTENSION = .html # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_HEADER = +HTML_HEADER = doxygen-awesome-css/doxygen-custom/header.html # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard @@ -1398,7 +1398,10 @@ HTML_STYLESHEET = # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = doxygen-awesome-css/doxygen-awesome.css \ - doxygen-awesome-css/doxygen-awesome-sidebar-only.css + doxygen-awesome-css/doxygen-custom/custom.css \ + doxygen-awesome-css/doxygen-awesome-sidebar-only.css \ + doxygen-awesome-css/doxygen-awesome-sidebar-only-darkmode-toggle.css \ + doxygen-awesome-css/doxygen-custom/custom-alternative.css # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note @@ -1408,7 +1411,12 @@ HTML_EXTRA_STYLESHEET = doxygen-awesome-css/doxygen-awesome.css \ # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_FILES = +HTML_EXTRA_FILES = doxygen-awesome-css/doxygen-awesome-darkmode-toggle.js \ + doxygen-awesome-css/doxygen-awesome-fragment-copy-button.js \ + doxygen-awesome-css/doxygen-awesome-paragraph-link.js \ + doxygen-awesome-css/doxygen-custom/toggle-alternative-theme.js \ + doxygen-awesome-css/doxygen-awesome-interactive-toc.js \ + doxygen-awesome-css/doxygen-awesome-tabs.js # The HTML_COLORSTYLE tag can be used to specify if the generated HTML output # should be rendered with a dark or light theme. @@ -1432,7 +1440,7 @@ HTML_COLORSTYLE = LIGHT # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_COLORSTYLE_HUE = 220 +HTML_COLORSTYLE_HUE = 209 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use gray-scales only. A @@ -1440,7 +1448,7 @@ HTML_COLORSTYLE_HUE = 220 # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_COLORSTYLE_SAT = 100 +HTML_COLORSTYLE_SAT = 255 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 @@ -1451,7 +1459,7 @@ HTML_COLORSTYLE_SAT = 100 # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_COLORSTYLE_GAMMA = 80 +HTML_COLORSTYLE_GAMMA = 113 # If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML # documentation will contain a main index with vertical navigation menus that @@ -1758,7 +1766,7 @@ ENUM_VALUES_PER_LINE = 4 # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. -TREEVIEW_WIDTH = 250 +TREEVIEW_WIDTH = 335 # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. @@ -1809,7 +1817,7 @@ FORMULA_MACROFILE = # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -USE_MATHJAX = NO +USE_MATHJAX = YES # With MATHJAX_VERSION it is possible to specify the MathJax version to be used. # Note that the different versions of MathJax have different requirements with @@ -1851,7 +1859,7 @@ MATHJAX_FORMAT = HTML-CSS # - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3 # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_RELPATH = +MATHJAX_RELPATH = https://cdn.jsdelivr.net/npm/mathjax@2 # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example @@ -1969,7 +1977,7 @@ EXTRA_SEARCH_MAPPINGS = # If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. # The default value is: YES. -GENERATE_LATEX = YES +GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..49c350d844 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,114 @@ +# Antares_Simulator documentation sources + +This directory contains the source files for building the *Antares Simulator* [documentation website](https://antares-simulator.readthedocs.io/), +the PDF user guides that are published in every [release](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases), +as well as the [Doxygen documentation](https://antaressimulatorteam.github.io/Antares_Simulator/doxygen/). + +Please help us keep this documentation alive: +- If you find that something is missing, outdated, or some mistake, report it in a [new issue](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/new) + or, better yet, open a [pull request](https://github.com/AntaresSimulatorTeam/Antares_Simulator/compare)! +- If you add a new feature, change a parameter, change something in the technical workflow, etc., update these + sources in the same pull request. Pull requests that do not update the documentation when needed will not be approved. + +## Contents of this directory + +As noted above, these sources serve two purposes: +1. Building the website +2. Building the PDF user guide +3. Building the Doxygen documentation + +While most of the source code is common, some code is specific. + +### Building the website +The website is hosted on [readthedocs](https://readthedocs.org/). The build workflow requires a configuration file which +is currently at the root of the project: [readthedocs.yml](../readthedocs.yml). This platform presents many advantages, +thanks to its workflow of automatic branch/tag building & publication: +- Multiple versions are activated: you can browse different versions of the documentation for different releases of *Antares Simulator* +- Pull requests are built automatically and the built status is reported in the PR's checks (`docs/readthedocs.org:antares-simulator`). + You can preview the built website inside this check (just click on `Details`), thus making it easier for reviewers to review changes of the docs. + +HTML content of the website is built automatically from source files written in [Markdown](https://fr.wikipedia.org/wiki/Markdown), +using [mkdocs](https://www.mkdocs.org/). +The mkdocs configuration file is [mkdocs.yml](../mkdocs.yml), at the root of the project. +It contains all customization options for the website (for example, the theme used is [mkdocs-material](https://squidfunk.github.io/mkdocs-material/)). +Here is the most common cases when you'll need to tweak this file: +- When you add a new page (written in Markdown), it is invisible by default. In order to make it visible, you have to + add it to the navigation list of the website in mkdocs.yml (`nav` section). +- If you want to customize the theme's behaviour, you will probably have to change the mkdocs.yml file (refer to the + used theme's documentation first) +- If you want to customize mkdoc's behaviour, add plugins, css, etc., you need to change this file (refer to the + [mkdocs doc](https://www.mkdocs.org/user-guide/) first) + +Sometimes, the possibilities offered by mkdocs & the used theme can be limiting. Mkdocs offers the possibility to use +custom html & css code. Currently, two methods are used: +- Custom CSS: the [extra.css](stylesheets/extra.css) files contains custom CSS classes (read more about this [here](https://squidfunk.github.io/mkdocs-material/customization/#additional-css)). + Feel free to add classes to it if you find it necessary. +- HTML overrides: the [overrides](overrides) directory contains HTML files that override objects inherited from mkdocs + or its theme (read more about this [here](https://squidfunk.github.io/mkdocs-material/customization/#extending-the-theme)). + You can use this method when other, lighter methods (i.e. tweaking mkdocs.yml & CSS styles) are not enough. + +When modifying the website content, you can easily preview the result on your PC by navigating to the root of the +project and running: +```bash +mkdocs serve +``` +Then click on the produced link (most likely `http://127.0.0.1:8000/`) to open the website in your browser. +As long as this process is running, updating any doc file automatically regenerates the website and refreshed the browser. + +### Building the PDF user guide +In every *Antares Simulator* [release](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases), +the user guide is printed to a PDF file and published in the assets. This document can be downloaded by users who +want to install *Antares Simulator* and be able to consult its documentation off-line. + +In practice, the PDF is generated automatically from Markdown files under [reference-guide](./user-guide) by +[Sphinx](https://www.sphinx-doc.org/) (using LaTeX). The script for this generation is in [pdf-doc-generation-with-sphinx/create_pdf_doc.sh](./pdf-doc-generation-with-sphinx/create_pdf_doc.sh); +it is automatically run by a GitHub [action](../.github/workflows/build-userguide.yml) during every release, and for +each pull request (in order to verify that the PDF builds). + +While the source material used for the PDF user guide are the same as the ones used for the mkdocs website (i.e. +Markdown files under `reference-guide`), some extra source files are needed: +- As for all Sphinx projects, this one needs a configuration file: [conf.py](./pdf-doc-generation-with-sphinx/source/conf.py). + This file allows you to customize the Sphinx build, in the same way mkdoks.yml allows you to customize mkdocs build. +- Sphinx navigation is built iteratively, using "index" files that refer to each other. The top-most index file is + [pdf-doc-generation-with-sphinx/source/index.rst](./pdf-doc-generation-with-sphinx/source/index.rst). It points to + [reference-guide/00-index.md](user-guide/00-index.md), which in turns points to other pages or indexes, + defining the whole navigation tree of the documentation. **This [reference-guide/00-index.md](user-guide/00-index.md) + file should be updated** in the same way mkdocs.yml is, in order to keep the navigation tree of the PDF document + synchronized with the navigation tree of the mkdocs website. + +When modifying the user guide content, you can easily preview the resulting PDF on your PC by navigating to the +root of the project and running: +```bash +cd docs/pdf-doc-generation-with-sphinx +bash create_pdf_doc.sh reference-guide.pdf +``` +Sphinx will create a `reference-guide.pdf` file in `docs/pdf-doc-generation-with-sphinx`. + +### Doxygen +[//]: # (TODO) +We strive to enrich code documentation as it evolves. The doxygen doc is generated automatically each time the develop +branch is updated. It is hosted [here](https://antaressimulatorteam.github.io/Antares_Simulator/doxygen), and can also +be generated locally with the follow command at the root of the project: + +**doxygen-executable** docs/Doxyfile + +If you'd like the same rendering as the one published checkout [doxygen-awesome-css](https://github.com/jothepro/doxygen-awesome-css) +and do this step before: +```bash +git clone https://github.com/jothepro/doxygen-awesome-css.git +cd doxygen-awesome-css +git checkout v2.2.1 +git apply ../docs/antares-simulator-doxygen.patch +``` + +## Extra considerations + +Like mentioned above, the same source material is used to automatically generate three different formats (mkdocs website, +PDF, doxygen website). When writing pages that have to be published in more than one format, please make sure the +syntax you are using is compatible with all the target formats. +Here is a **non-exhaustive** list of points to watch out for: +- When you add a page, make sure you add it to all target supports. For instance, adding a page to the mkdocs website + requires creating a `nav` entry in the [mkdocs.yml](../mkdocs.yml) file, while adding it to the Sphinx PDF requires + adding an extra entry to an existing index.md file, and, sometimes, creating an extra index.md file (to add a section). +- Do not use non-standard characters (such as emojis) in the user guide, as they cannot be rendered by LaTeX + in PDF. diff --git a/docs/antares-simulator-doxygen.patch b/docs/antares-simulator-doxygen.patch new file mode 100644 index 0000000000..01a24657d1 --- /dev/null +++ b/docs/antares-simulator-doxygen.patch @@ -0,0 +1,52 @@ +From 7219365be1db9b4bd55ffa6a2cea5b56c5029e7e Mon Sep 17 00:00:00 2001 +From: Abdoulbari ZAKIR +Date: Wed, 15 Nov 2023 14:35:52 +0100 +Subject: [PATCH] patch for xpansion + +Signed-off-by: Abdoulbari ZAKIR +--- + doxygen-custom/header.html | 18 +++++++++--------- + 1 file changed, 9 insertions(+), 9 deletions(-) + +diff --git a/doxygen-custom/header.html b/doxygen-custom/header.html +index 7f37e6f..35ab907 100644 +--- a/doxygen-custom/header.html ++++ b/doxygen-custom/header.html +@@ -7,16 +7,16 @@ + + + +- +- +- +- ++ ++ ++ ++ + + + +- +- +- ++ ++ ++ + + + $projectname: $title +@@ -46,8 +46,8 @@ $extrastylesheet + + + +- +- ++ ++ + + +-- +2.37.3.windows.1 + diff --git a/docs/build/0-INSTALL.md b/docs/build/0-INSTALL.md deleted file mode 100644 index 2be78c7552..0000000000 --- a/docs/build/0-INSTALL.md +++ /dev/null @@ -1,20 +0,0 @@ -# Introduction - -*ANTARES* is developed mainly in **C++** - -This software suite has been tested under: - -* Ubuntu 20.04 [![Status][ubuntu_precompiled_svg]][ubuntu_precompiled_link] -* Microsoft Windows with Visual Studio 2019 (64-bit) [![Status][windows_precompiled_svg]][windows_precompiled_link] -* Centos 7 [![Status][centos_precompiled_svg]][centos_precompiled_link] - -*ANTARES* is built using CMake. - -## Build and installation details - -- [Development requirements](1-Development-requirements.md) -- [Dependencies](2-Dependencies-install.md) -- [Build](3-Build.md) -- [Tests](4-Tests.md) -- [Installer creation](5-Installer-creation.md) -- [Developer advice](6-dev-advice.md) diff --git a/docs/build/1-Development-requirements.md b/docs/build/1-Development-requirements.md deleted file mode 100644 index 891cbe9cc4..0000000000 --- a/docs/build/1-Development-requirements.md +++ /dev/null @@ -1,104 +0,0 @@ -# Development requirements - -## [C++ version](#c++-version) -The compilation of *antares-xpansion* requires C++17 support. - -=== "Windows" - - Compilation is tested on MSVC 2019 - -=== "Centos" - - By default, GCC version of Centos7 is 4.8.5. - - Some external repositories must be enabled - - === "Centos 7 (EPEL)" - ``` - sudo yum install epel-release - sudo yum install centos-release-scl - ``` - - === "Centos 8 (PowerTools)" - ``` - sudo yum install dnf-plugins-core - sudo yum config-manager --set-enabled PowerTools - ``` - - You can then use a more recent version of GCC by enabling `devtoolset-9` : - ``` - sudo yum install devtoolset-9 - ``` - - Before compiling *antares-xpansion* we must launch a new shell with `scl` tool : - ``` - scl enable devtoolset-9 bash - ``` -=== "Ubuntu" - - ``` - sudo apt install build-essential - ``` -## [CMake version](#cmake-version) -CMake 3.x must be used. - -=== "Windows" - - You can download latest Windows version directly from [CMake website](https://cmake.org/download/). -=== "Centos" - - ``` - sudo yum install epel-release - sudo yum install cmake3 - ``` -=== "Ubuntu" - - ``` - sudo apt install cmake - ``` - -## [Python version](#python-version) -Python 3.x is used for end-to-end test. - -=== "Windows" - - You can download latest Windows version directly from [Python website](https://www.python.org/downloads/windows/). -=== "Centos" - - ``` - sudo yum install python3 python3-pip - ``` -=== "Ubuntu" - - ``` - sudo apt-get install python3 python3-pip - ``` - -Required python modules can be installed with : -``` -pip install -r requirements-tests.txt -``` - -## [Git version](#git-version) -Git version must be above 2.15 for external dependencies build because `--ignore-whitespace` is not used by default and we have an issue with OR-Tools compilation of ZLib and application of patch on Windows (see https://github.com/google/or-tools/issues/1193). - -=== "Windows" - - You can download latest Windows version directly from [Git website](https://gitforwindows.org/). -=== "Centos" - - ``` - sudo yum install rh-git227-git - sudo yum install git - ``` - - Sometimes we need a 2.x version of git. To enable git 2.27 : - ``` - source /opt/rh/rh-git227/enable - ``` - -=== "Ubuntu" - - ``` - sudo apt-get install git - ``` diff --git a/docs/build/2-Dependencies-install.md b/docs/build/2-Dependencies-install.md deleted file mode 100644 index 067402dfa7..0000000000 --- a/docs/build/2-Dependencies-install.md +++ /dev/null @@ -1,92 +0,0 @@ -# Dependencies install - -*ANTARES* depends on severals mandatory libraries. - -- [Sirius Solver](https://github.com/AntaresSimulatorTeam/sirius-solver/tree/Antares_VCPKG) (fork from [RTE](https://github.com/rte-france/sirius-solver/tree/Antares_VCPKG)) -- [OR-Tools](https://github.com/rte-france.com/or-tools) (fork from [Google](https://github.com/google/or-tools)) -- [wxWidgets](https://github.com/wxWidgets/wxWidgets) - (Only for the complete Antares Simulator solution with GUI) -- Boost librairies : test (Only for unit tests) - -This section describes the install procedures for the third-party Open source libraries used by *ANTARES*. -The install procedure can be done - -- by compiling the sources after cloning the official git repository -- by using a package manager - -## Install with package manager - -=== "Windows (VCPKG)" - - For Windows we will use [vcpkg](https://github.com/microsoft/vcpkg) to download and compile the libraries. vcpkg is available as a submodule in *ANTARES*. - - You must install the corresponding [vcpkg-triplet](https://vcpkg.readthedocs.io/en/latest/users/integration/#triplet-selection) depending on Antares version and libraries load: - - - ``x64-windows`` : 64 bits version with dynamic libraries load - - ``x86-windows`` : 32 bits version with dynamic libraries load - - ``x64-windows-static`` : 64 bits version with static libraries load - - ``x86-windows-static`` : 32 bits version with static libraries load - - The vcpkg-triplet used will be named [vcpg-triplet] later in this document. - - - Init submodule and install vcpkg - - ``` - git submodule update --init vcpkg - cd vcpkg - .\bootstrap-vcpkg.bat - ``` - - Note : - > all vcpkg command further described must be run from vcpkg folder. This folder will be named [vcpkg_root] later in this document. - - - - Install dependencies - ``` - cd vcpkg - vcpkg install wxwidgets boost-test --triplet [vcpg-triplet] - ``` -=== "Centos (yum)" - - ``` - sudo yum install git redhat-lsb-core gcc gcc-c++ make wget centos-release-scl scl-utils rpm-build - sudo yum install cmake3 devtoolset-9 - sudo yum install libuuid-devel unzip wxGTK3-devel boost-test boost-devel - ``` -=== "Ubuntu (apt-get)" - - ``` - sudo apt-get install uuid-dev libwxgtk3.0-gtk3-dev - sudo apt-get install libboost-test-dev - ``` - -## Automatic libraries compilation from git -[Antares dependencies compilation repository](https://github.com/AntaresSimulatorTeam/antares-deps) is used as a git submodule for automatic libraries compilation from git. - -Apart from OR-Tools, all dependencies can be built at configure time using the option `-DBUILD_ALL=ON` (`OFF` by default). For a list of available option see [Antares dependencies compilation repository](https://github.com/AntaresSimulatorTeam/antares-deps). - -You can set `-DBUILD_ORTOOLS=ON` to download & build OR-Tools. It is also possible to use a precompiled archive, see below. - -### Pre-compiled OR-Tools : release+static only -You can [download](https://github.com/rte-france/or-tools/releases) a precompiled OR-Tools archive that contains headers & static libraries. - -Please note that dynamic linking with OR-Tools is only supported in Linux. - -Decompress the archive, and provide its path as a `CMAKE_PREFIX_PATH`. If you use XPRESS, you may need also to specify `XPRESS_ROOT`. - -### Defining dependency install directory -When using multiple directories for antares development with multiple branches it can be useful to have a common dependency install directory. - -Dependency install directory can be specified with `DEPS_INSTALL_DIR`. By default install directory is `/../rte-antares-deps-` - -Note : -> `DEPS_INSTALL_DIR` is added to `CMAKE_PREFIX_PATH` - -### Pre-compiled libraries download : release version only -You can download pre-compiled antares-deps archive from [Antares dependencies compilation repository][antares-deps-url]. Only release versions are available. - -Note: -> For windows, you must you use a MSVC version compatible with MSVC version used in GitHub Action. - -[antares-deps-url]: https://github.com/AntaresSimulatorTeam/antares-deps/releases/tag/v2.0.2 - diff --git a/docs/build/3-Build.md b/docs/build/3-Build.md deleted file mode 100644 index a918b63d6b..0000000000 --- a/docs/build/3-Build.md +++ /dev/null @@ -1,69 +0,0 @@ -# Build -Before build, make sure that dependencies are installed (see [here](2-Dependencies-install.md) for more informations) - -## Environnement settings -On Centos enable `devtoolset-9` and `rh-git227`: -``` -scl enable devtoolset-9 bash -source /opt/rh/rh-git227/enable -``` -## Update git submodule -``` -git submodule update --init src/antares-deps -``` -## Configure build with CMake -=== "Windows" - Note : - > cpack NSIS installer creation need an 'out of source build'. The build directory must be outside `[antares_src]` directory - - ``` - cmake -B _build -S [antares_src] -DVCPKG_ROOT=[vcpkg_root] -DVCPKG_TARGET_TRIPLET=[vcpkg-triplet] -DCMAKE_BUILD_TYPE=release - ``` -=== "Centos" - - ``` - cmake3 -B _build -S [antares_src] -DCMAKE_BUILD_TYPE=release - ``` -=== "Ubuntu" - - ``` - cmake -B _build -S [antares_src] -DCMAKE_BUILD_TYPE=release - ``` - -Here is a list of available CMake configure option : - -|Option | Description | -|:-------|-------| -|`CMAKE_BUILD_TYPE` | Define build type. Available values are `release` and `debug` (case insensitive) | -|`BUILD_UI`|Enable or disable Antares Simulator UI compilation (default `ON`)| -|`BUILD_ALL`|Enable build of ALL external libraries (default `OFF`)| -|`DEPS_INSTALL_DIR`|Define dependencies libraries install directory| -|`USE_PRECOMPILED_EXT`| This option must be set if you use wxWidget as precompiled external library (default `OFF`)| -|`BUILD_TESTING`| Enable test build (default `OFF`)| -|`BUILD_ORTOOLS`| Enable build for OR-Tools and its dependencies (requires an Internet connecton)| - -Additionnal options for windows - -|Option |Description | -|:-------|-------| -|`VCPKG_ROOT`|Define vcpkg directory | -|`VCPKG_TARGET_TRIPLET`|Define [vcpkg-triplet] | - -## Build -=== "Windows" - - ``` - cmake --build _build --config release -j8 - ``` -=== "Centos" - - ``` - cmake3 --build _build --config release -j8 - ``` -=== "Ubuntu" - - ``` - cmake --build _build --config release -j8 - ``` -Note : -> Compilation can be done on several processor with ```-j``` option. diff --git a/docs/build/4-Tests-dev.md b/docs/build/4-Tests-dev.md deleted file mode 100644 index 5bed51c145..0000000000 --- a/docs/build/4-Tests-dev.md +++ /dev/null @@ -1,68 +0,0 @@ -# Tests (developer) -This document aims at describing the workflow used for the ~200 non-regression studies that are executed before every release. The goal of these tests is to avoid any unexpected change in the results, thus ensuring compatibility of the new versions with the old ones. - -Note: -> This is a work-in-progress - -## Repositories -There are two repositories : - -- [Antares_Simulator_Tests_NR](https://github.com/AntaresSimulatorTeam/Antares_Simulator_Tests_NR) contains the study batches. These batches are published in releases and do not contain any result. -- [SimTest](https://github.com/AntaresSimulatorTeam/SimTest) contains the study batches as well as some reference results. - -## Antares_Simulator_Tests_NR -This repository publishes releases. Each release contains the following files : - -- `study-batches.txt`, a newline-separated list of study batches. A study batch is a group of Antares studies in the same directory. Note that some studies may also be placed in a sub-directory. -- Archives containing the study batches. - -Here is an excerpt from the latest `study-batches.txt` -``` -short-tests -long-tests-1 -long-tests-2 -long-tests-3 -``` - -Here is a list of the corresponding archives: - -- `short-tests.zip` -- `long-tests-1.zip` -- `long-tests-2.zip` -- `long-tests-3.zip` - -These archives can be found at the following URL: `https://github.com/AntaresSimulatorTeam/Antares_Simulator_Tests_NR/releases/download//` - -In each study, there is a config.json file containing the necessary information for running tests. - -## SimTest -This is the source of releases. Each release contains the following files: -- `study-batches.txt`. It is merely a copy of `study-batches.txt` from Antares_Simulator_Tests_NR. -- For each study batch listed above, two archives containing results for Ubuntu and Windows. - -As above, config.json are packaged in the archives: one per study. - -Here is a list of archives corresponding to the batches above: - -- `short-tests-windows-latest.zip` -- `long-tests-1-windows-latest.zip` -- `long-tests-2-windows-latest.zip` -- `long-tests-3-windows-latest.zip` -- `short-tests-ubuntu-latest.zip` -- `long-tests-1-ubuntu-latest.zip` -- `long-tests-2-ubuntu-latest.zip` -- `long-tests-3-ubuntu-latest.zip` - -In the future, CentOS 7 should be included as well. - -## Configuration files -TODO - -## Workflow -The workflow is the following: - -1. Create a release in Antares_Simulator_Tests_NR (only if new studies are introduced). Tag it `X`. -2. Create a release in SimTest (only if a new feature is introduced) from Antares_Simulator_Tests_NR, tag `X` and Antares_Simulator, tag `Y`. -3. Use the release in SimTest to compare results of tag `Z` in Antares_Simulator. In this step, `pytest` is used as well as the `config.json` configuration files to test new results against the reference results. - -Note that steps 1. and 2. are rarely used, therefore there is no need to automate them. Step 3. however is to be run for every Antares_Simulator release, as such it should be automated. diff --git a/docs/build/4-Tests-user.md b/docs/build/4-Tests-user.md deleted file mode 100644 index 8e6fb73b95..0000000000 --- a/docs/build/4-Tests-user.md +++ /dev/null @@ -1,38 +0,0 @@ -# Tests (user) - -Tests compilation can be enabled at configure time using the option `-DBUILD_TESTING=ON` (`OFF` by default). It is required only for unit-tests and end-to-end tests. - -After build, tests can be run with ``ctest`` : - -``` -cd _build -ctest -C Release --output-on-failure -``` - -All tests are associated to a label and multiple labels can be defined. You can choose which tests will be executed at ctest run. - -This is the list of the available labels : - -| Label | Description | -|:-------|-----| -| `units` | Units tests | -| `end-to-end` | End to end tests with antares study creation | -| `json` | Run examples configured with a .json file (see below) | - -Note : -> Use `ctest -N` to see all available tests - -Note : -> In this case the regex is on name (`-R`) so only short-examples are executed. -For more information on `ctest` call see [documentation](https://cmake.org/cmake/help/latest/manual/ctest.1.html) - -# Running JSON tests -To run JSON tests, a [study batch](https://github.com/AntaresSimulatorTeam/SimTest/releases) is first required. - -```bash -cd ${Antares_Simulator_ROOT}/src/tests/resources/batches -wget https://github.com/AntaresSimulatorTeam/SimTest/releases/download/v8.3.2/valid-defaillance-ubuntu-20.04.zip -unzip valid-defaillance-ubuntu-20.04.zip -cd ${Antares_Simulator_ROOT}/build -ctest -C Release --output-on-failure -R json -``` diff --git a/docs/build/5-Installer-creation.md b/docs/build/5-Installer-creation.md deleted file mode 100644 index 2d888ff768..0000000000 --- a/docs/build/5-Installer-creation.md +++ /dev/null @@ -1,53 +0,0 @@ -# Installer creation -CPack can be used to create the installer after the build phase : - -=== "Windows" - ``` - cd _build - cpack -GNSIS - ``` - Currently missing in NSIS installer : - - External libraries sources - -=== "Centos" - - ### RHEL .rpm (Experimental) - ``` - cd _build - cpack3 -G RPM . - ``` - Note : - > `rpm-build` must be installed for RPM creation : `sudo yum install rpm-build` - - ### Linux .tar.gz - ``` - cd _build - cpack3 -G TGZ - ``` - - ### Required system libraries - There are still some system libraries that must be installed if you want to use *ANTARES*: - - ``` - sudo yum install epel-release - sudo yum install wxGTK3 - ``` - -=== "Ubuntu" - - ### Ubuntu .deb (Experimental) - ``` - cd _build - cpack -G DEB . - ``` - ### Linux .tar.gz - ``` - cd _build - cpack -G TGZ - ``` - - ### Required system libraries - There are still some system libraries that must be installed if you want to use *ANTARES*: - ``` - sudo apt-get install libwxgtk3.0-gtk3-0v5 - ``` \ No newline at end of file diff --git a/docs/build/6-dev-advice.md b/docs/build/6-dev-advice.md deleted file mode 100644 index 7b23e718e4..0000000000 --- a/docs/build/6-dev-advice.md +++ /dev/null @@ -1,39 +0,0 @@ -# Developer advice - -## Ignore submodules to make git operations faster -Antares_Simulator is quite a large project, with a few large submodules. In file .git/config, you can add this line to all [submodule] sections - -``` -ignore = all -``` - -This way git won't waste time computing diff on these when checking out, diffing commits, etc. git operations should be a lot faster. Keep in mind that your submodules won't be updated. - -## Disable the UI build to make builds faster -The UI takes up a good chunk of compilation time. It is enabled by default, byt you can disable it by providing CMake with this option at configure time - -``` -cmake -S src [...] -DBUILD_UI=OFF -``` - -## Use Ninja to speed up target generation by CMake -At configure time, you may specify Ninja for generation instead of traditional Make. This will speed up the update step after you made small changes to the code. - -``` -cmake -S src [...] -G Ninja -``` - -Note that you may need to install Ninja first (package `ninja-build` on Ubuntu). - -## Adding the solver build path to your PATH -If you use `antares-x.y-solver` often, you may find it convenient to add it's location to your PATH. In your .bashrc, add (with slight variations) - -``` -export PATH="$PATH:path/to/Antares_Simulator/build/solver -``` - -Then you can open a terminal and execute antares-x.y-solver by just typing - -``` -antares-x.y-solver -``` diff --git a/docs/build/continuous-integration.md b/docs/build/continuous-integration.md deleted file mode 100644 index b826084dec..0000000000 --- a/docs/build/continuous-integration.md +++ /dev/null @@ -1,68 +0,0 @@ -# Continuous Integration -*ANTARES* compilation is fully tested on GitHub CI. - -Here is a description of workflow with their associated status : - -| OS | .yml | Description | Status | -|:-------|--------|--------|------| -| Ubuntu |`ubuntu-system.yml`|Compilation with system libraries (apt-get) and pre-compiled not system libraries use| [![Status][ubuntu_precompiled_svg]][ubuntu_precompiled_link] | -| Ubuntu |`ubuntu-system-deps-build.yml`|Compilation with system libraries (apt-get) and not system libraries compilation| [![Status][ubuntu_deps_build_svg]][ubuntu_deps_build_link] | -| Ubuntu |`ubuntu-release.yml`|Compilation with system libraries (apt-get) and not system libraries compilation for release creation| [![Status][ubuntu_release_svg]][ubuntu_release_link] -| Windows |`windows-vcpkg.yml`|Compilation with VCPKG use and pre-compiled not system libraries use| [![Status][windows_precompiled_svg]][windows_precompiled_link] | -| Windows |`windows-pre-compiled-only.yml`|Compilation without VCPKG and with pre-compiled libraries use| [![Status][windows_precompiled_only_svg]][windows_precompiled_only_link] | -| Windows |`windows-vcpkg.yml`|Compilation with VCPKG use and pre-compiled not system libraries use for release creation| [![Status][windows_release_svg]][windows_release_link] | -| Centos7 | `centos7-system.yml`|Compilation with system librairies (`yum`) and pre-compiled not system libraries use| [![Status][centos_precompiled_svg]][centos_precompiled_link] | -| Centos7 |`centos7-system-deps-build.yml`| Compilation with system librairies (`yum`) and not system libraries compilation| [![Status][centos_deps_build_svg]][centos_deps_build_link] | -| Centos7 | `centos7-system.yml`|Compilation with system librairies (`yum`) and pre-compiled not system libraries use for release creation| [![Status][centos_release_svg]][centos_release_link] | - -## Additionnals workflow - - | .yml | Description | Status | -|:-------|--------|------| -| `sonarcloud.yml`|Compilation with specifics options for sonarcloud analysis.| [![Status][sonarcloud_svg]][sonarcloud_link] | -| `build-userguide.yml`|User guide generation| [![Status][userguide_svg]][userguide_link] | -| `branchNameValidation.yml`|Check branch name for CI workflow run|| - - -## Created Github actions - - - | Name | Description | -|:-------|--------| -| `generate-user-guide-pdf`|Generate User Guide pdf using Sphinx (not supported on windows)| -| `download-extract-precompiled-libraries-zip`|Download and extract .zip precompiled libraries from antares-deps repository| -| `download-extract-precompiled-libraries-tgz`|Download and extract .tgz precompiled libraries from antares-deps repository| - - -[ubuntu_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(pre-compiled)/badge.svg -[ubuntu_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(pre-compiled)" - -[ubuntu_release_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(Release)/badge.svg -[ubuntu_release_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(Release)" - -[ubuntu_deps_build_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(deps.%20compilation)/badge.svg -[ubuntu_deps_build_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(deps.%20compilation)" - -[windows_precompiled_only_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(pre-compiled%20only)/badge.svg -[windows_precompiled_only_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(pre-compiled%20only)" - -[windows_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg -[windows_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" - -[windows_release_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(Release)/badge.svg -[windows_release_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(Release)" - -[centos_deps_build_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(deps.%20compilation)/badge.svg -[centos_deps_build_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(deps.%20compilation)" - -[centos_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(pre-compiled)/badge.svg -[centos_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(pre-compiled)" - -[centos_release_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(Release)/badge.svg -[centos_release_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(Release)" - -[sonarcloud_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/SonarCloud/badge.svg -[sonarcloud_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"SonarCloud" - -[userguide_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Build%20Userguide%20pdf/badge.svg -[userguide_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Build%20Userguide%20pdf" diff --git a/docs/build/ortools-integration.md b/docs/build/ortools-integration.md deleted file mode 100644 index 6598f15c0c..0000000000 --- a/docs/build/ortools-integration.md +++ /dev/null @@ -1,56 +0,0 @@ -# Ortools integration - -## Ortools available solvers -There is currently no ortools API to get a list of available solver. - -We will be using name and enum defined in `linear_solver/linear_solver.cc` - -### Linear optimisation -| Ortools solver name| Enum| Licence |Website| -|:-------|-------|-----|------| -| `clp`| CLP_LINEAR_PROGRAMMING|Open source|https://github.com/coin-or/Clp| -| `glpk_lp`| GLPK_LINEAR_PROGRAMMING|Open source|https://www.gnu.org/software/glpk/| -| `glop`| GLOP_LINEAR_PROGRAMMING|Open source|https://developers.google.com/optimization/lp/glop| -| `gurobi_lp`| GUROBI_LINEAR_PROGRAMMING|Commercial|https://www.gurobi.com/| -| `NOT_DEFINED`| CPLEX_LINEAR_PROGRAMMING|Commercial|https://www.ibm.com/fr-fr/analytics/cplex-optimizer| -| `xpress_lp`| XPRESS_LINEAR_PROGRAMMING|Commercial|https://www.fico.com/en/products/fico-xpress-solver| -| `NOT_DEFINED`| SIRIUS_LINEAR_PROGRAMMING|Open source| - -### Mixed real integer optimisation -| Ortools solver name| Enum | Licence |Website| -|:-------|-------|-----|------| -| `scip`| SCIP_MIXED_INTEGER_PROGRAMMING|Special license ZIB (research purposes as a member of a non-commercial or academic institution)|https://www.scipopt.org/| -| `glpk_mip`| GLPK_MIXED_INTEGER_PROGRAMMING|Open sourcer|https://www.gnu.org/software/glpk/| -| `cbc`| CBC_MIXED_INTEGER_PROGRAMMING|Open source|https://github.com/coin-or/Cbc| -| `gurobi_mip`| GUROBI_MIXED_INTEGER_PROGRAMMING|Commercial|https://www.gurobi.com/| -| `NOT_DEFINED`| CPLEX_MIXED_INTEGER_PROGRAMMING|Commercial|https://www.ibm.com/fr-fr/analytics/cplex-optimizer| -| `xpress_mip`| XPRESS_MIXED_INTEGER_PROGRAMMING|Commercial|https://www.fico.com/en/products/fico-xpress-solver| -| `NOT_DEFINED`| SIRIUS_MIXED_INTEGER_PROGRAMMING|Open source|| - -### Constraint optimisation -| Ortools solver name| Enum | Licence | Optimisation type |Website| -|:-------|-------|-----|------|------| -| `bop`| BOP_INTEGER_PROGRAMMING|Open source|Boolean|| -| `sat`| SAT_INTEGER_PROGRAMMING|Open source|Boolean integer|| - -## Solver available for antares-solver -We need 2 types of solver : -* Linear -* Mixed real integer - -Here are the solver used depending on antares-solver command line option ortools-solver: - -|ortools-solver|Linear solver|Mixed real integer| -|:-------|-----|--------| -|`sirius` (default)|SIRIUS_LINEAR_PROGRAMMING|SIRIUS_MIXED_INTEGER_PROGRAMMING| -|`coin`|CLP_LINEAR_PROGRAMMING|CBC_MIXED_INTEGER_PROGRAMMING| - -5 more solvers will be added when ortools is updated : - -|ortools-solver|Linear solver|Mixed real integer|Waiting for| -|:-------|-----|--------|--------| -|`xpress`|XPRESS_LINEAR_PROGRAMMING|XPRESS_MIXED_INTEGER_PROGRAMMING| Update ortools building process for XPRESS support| -|`glop-scip`|GLOP_LINEAR_PROGRAMMING|SCIP_MIXED_INTEGER_PROGRAMMING|Merging of 7.8 ortools version in rte ortools fork| -|`cplex`|CPLEX_LINEAR_PROGRAMMING|CPLEX_MIXED_INTEGER_PROGRAMMING| Update ortools building process for CPLEX support| -|`gurobi`|GUROBI_LINEAR_PROGRAMMING|GUROBI_MIXED_INTEGER_PROGRAMMING| Update ortools building process for gurobi support| -|`glpk`|GLPK_LINEAR_PROGRAMMING|GLPK_MIXED_INTEGER_PROGRAMMING| Update ortools building process for glpk support| \ No newline at end of file diff --git a/docs/developer-guide/0-Overview.md b/docs/developer-guide/0-Overview.md new file mode 100644 index 0000000000..139f23d552 --- /dev/null +++ b/docs/developer-guide/0-Overview.md @@ -0,0 +1,39 @@ +--- +hide: + - toc +--- + +# Overview + +*ANTARES* is developed mainly in **C++** + +This software suite has been tested under: + +* Ubuntu 20.04 [![Status][ubuntu_ci_svg]][ubuntu_ci_link] +* Microsoft Windows with Visual Studio 2019 (64-bit) [![Status][windows_ci_svg]][windows_ci_link] +* Centos 7 [![Status][centos_ci_svg]][centos_ci_link] +* Oracle Linux [![Status][oraclelinux_ci_svg]][oraclelinux_ci_link] + +Antares Simulator is built using CMake. + +## Build and installation details + +- [Development requirements](1-Development-requirements.md) +- [Dependencies](2-Dependencies-install.md) +- [Build](3-Build.md) +- [User tests](4-Tests-user.md) +- [Developer tests](4-Tests-dev.md) +- [Installer creation](5-Installer-creation.md) + + +[ubuntu_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(push%20and/or%20release)/badge.svg +[ubuntu_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(push%20and/or%20release)" + +[windows_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg +[windows_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" + +[centos_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(push%20and/or%20release)/badge.svg +[centos_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(push%20and/or%20release)" + +[oraclelinux_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Oracle%208%20CI%20(push%20and/or%20release)/badge.svg +[oraclelinux_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Oracle%208%20CI%20(push%20and/or%20release)" diff --git a/docs/developer-guide/1-Development-requirements.md b/docs/developer-guide/1-Development-requirements.md new file mode 100644 index 0000000000..02c0896f33 --- /dev/null +++ b/docs/developer-guide/1-Development-requirements.md @@ -0,0 +1,117 @@ +# Development requirements + +## C++ +-------------------- +The compilation of *Antares Simulator* requires C++17 support. + +=== "Windows" + + Compilation is tested on MSVC 2019 + +=== "Centos" + + By default, GCC version on Centos is old. + Some external repositories must be enabled depending on your version of the OS: + + #### Centos 7 + You must enable the EPEL repository: + ``` + sudo yum install epel-release + sudo yum install git redhat-lsb-core make wget centos-release-scl scl-utils rpm-build + sudo yum install devtoolset-10-gcc* + + scl enable devtoolset-10 bash + source /opt/rh/rh-git227/enable + ``` + + #### Centos 8 + You must enable PowerTools, then install a more recent version of GCC by installing and enabling `devtoolset-9`: + ``` + sudo yum install dnf-plugins-core + sudo yum config-manager --set-enabled PowerTools + sudo yum install devtoolset-10 + scl enable devtoolset-10 bash + ``` + +=== "Ubuntu/Debian" + + #### Ubuntu 20.04 or 22.04 / Debian 11 + You need to install G++ 10: + ``` + sudo apt install g++-10 + ``` + + #### Ubuntu 23.04 / Debian 12 + The installation requires the following build and test dependencies: + ``` + sudo apt install git unzip build-essentials + ``` + +## CMake version +-------------------- +CMake 3.x must be used. + +=== "Windows" + + You can download latest Windows version directly from [CMake website](https://cmake.org/download/). +=== "Centos" + + ``` + sudo yum install epel-release + sudo yum install cmake3 + ``` +=== "Ubuntu/Debian" + + ``` + sudo apt install cmake + ``` +## Python version +-------------------- +Python 3.x is used for end-to-end test. + +=== "Windows" + + You can download latest Windows version directly from [Python website](https://www.python.org/downloads/windows/). + +=== "Centos" + + ``` + sudo yum install python3 python3-pip + ``` + +=== "Ubuntu/Debian" + + ``` + sudo apt install python3 python3-pip + ``` + +Required python modules can be installed with: +``` +pip install -r requirements-tests.txt +``` + +## Git version +-------------------- +Git version must be above 2.15 for external dependencies build because `--ignore-whitespace` is not used by default and we have an issue with OR-Tools compilation of ZLib and application of patch on Windows (see https://github.com/google/or-tools/issues/1193). + +=== "Windows" + + You can download latest Windows version directly from [Git website](https://gitforwindows.org/). + +=== "Centos" + + ``` + sudo yum install rh-git227-git + sudo yum install git + ``` + + Sometimes we need a 2.x version of git. To enable git 2.27: + ``` + source /opt/rh/rh-git227/enable + ``` + +=== "Ubuntu/Debian" + + ``` + sudo apt install git + ``` diff --git a/docs/developer-guide/2-Dependencies-install.md b/docs/developer-guide/2-Dependencies-install.md new file mode 100644 index 0000000000..1177228e6a --- /dev/null +++ b/docs/developer-guide/2-Dependencies-install.md @@ -0,0 +1,70 @@ +--- +toc_depth: 2 +--- + +# Dependencies install + +*Antares Simulator* depends on some mandatory libraries. + +- [Sirius Solver](https://github.com/AntaresSimulatorTeam/sirius-solver/tree/Antares_VCPKG) (fork from [RTE](https://github.com/rte-france/sirius-solver/tree/Antares_VCPKG)) +- [OR-Tools](https://github.com/rte-france.com/or-tools) (fork from [Google](https://github.com/google/or-tools)) +- [wxWidgets](https://github.com/wxWidgets/wxWidgets) + (Only for the complete Antares Simulator solution with GUI) +- [minizip](https://github.com/zlib-ng/minizip-ng) library, with its dependency zlib +- [Boost](https://www.boost.org/) libraries: header libraries and boost-test library +- [libuuid](https://linux.die.net/man/3/libuuid) on Linux systems + +We favor using [vcpkg](https://github.com/microsoft/vcpkg) for building and installing most of those dependencies, +see [build instructions](3-Build.md) which explain how it integrates with CMake build. +However, we still have a few exceptions that must be installed in a different way, see next sections. + +Although not encouraged, it's still possible to install those dependencies yourself and add +their installation path to your `CMAKE_PREFIX_PATH`. + +## OR-Tools + +OR-Tools may be installed in one of 2 ways: + +1. **As a pre-compiled dependency** + + You can [download](https://github.com/rte-france/or-tools/releases) a precompiled OR-Tools archive that contains headers & static libraries. + + Please note that dynamic linking with OR-Tools is only supported in Linux. + + Decompress the archive, and provide its path as a `CMAKE_PREFIX_PATH`. + +2. **As part of the build** + + You may enable the `BUILD_ORTOOLS` configuration option to build it from source during Antares build, + as documented in [build instructions](3-Build.md). + + The drawback of this second approach is that OR-Tools may need to be built again when you + run again a cmake configure step, therefore it's not advised for developers. + + +## Linux: libuuid and wxWidgets + +On Linux systems, libuuid development packages need to be installed with your +OS package manager. +You will also need to install wxWidgets if you want to build the GUI. + +=== "Centos" + + ``` + sudo yum install libuuid-devel + sudo yum install wxGTK3-devel + ``` + +=== "Ubuntu 20.04 or 22.04 / Debian 11" + + ``` + sudo apt install uuid-dev + sudo apt install libwxgtk3.0-gtk3-dev + ``` + +=== "Ubuntu 23.04 / Debian 12" + + ``` + sudo apt install uuid-dev + sudo apt install libwxgtk3.2-dev + ``` diff --git a/docs/developer-guide/3-Build.md b/docs/developer-guide/3-Build.md new file mode 100644 index 0000000000..860c9f47cb --- /dev/null +++ b/docs/developer-guide/3-Build.md @@ -0,0 +1,123 @@ +# Build + +Before building, make sure that dependencies are [installed](2-Dependencies-install.md). + +## Install VCPKG + +Although you may install third party dependencies yourself, the preferred way is +to rely on [vcpkg](https://github.com/microsoft/vcpkg) and its CMake integration +to build and install most of them. + +The first step will be to install VCPKG using its bootstrap script: + +=== "Windows" + + ``` + git submodule update --init vcpkg + cd vcpkg + .\bootstrap-vcpkg.bat + ``` + +=== "Linux" + + ``` + git submodule update --init vcpkg + cd vcpkg + ./bootstrap-vcpkg.sh + ``` + +## Configure build with CMake + +The preferred way of building the project is to use a pre-compiled version of OR-Tools and to install +other dependencies using vcpkg. To achieve this, you will need to define VCPKG-related variables, +and add your OR-tools install path to `CMAKE_PREFIX_PATH`: + + +=== "Windows" + + ``` + cmake -B _build -S src -DCMAKE_TOOLCHAIN_FILE=../vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-windows-antares \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_PREFIX_PATH= + ``` + + > **Note:** cpack NSIS installer creation needs an 'out-of-source build'. The build directory must be outside `src` directory + + +=== "Linux" + + ``` + cmake -B _build -S src -DCMAKE_TOOLCHAIN_FILE=../vcpkg/scripts/buildsystems/vcpkg.cmake \ + -DVCPKG_TARGET_TRIPLET=x64-linux-antares \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_PREFIX_PATH= + ``` + +Here is a list of mandatory or optional CMake configuration options: + +| Option | Mandatory | Description | Expected value | Default value | +|:-----------------------|--------------|----------------------------------------------------------------------------------|---------------------------------------------|-----------------------------------------------------------| +| `CMAKE_C_COMPILER` | OS-dependent | Select C compiler | `gcc-10` | | +| `CMAKE_CXX_COMPILER` | OS-dependent | Select C++ compiler | `g++-10` | | +| `CMAKE_BUILD_TYPE` | **yes** | Define build type | `Release` / `Debug` / `RelWithDebInfo` | | +| `BUILD_UI` | no | Enable or disable Antares Simulator UI[^1] compilation | `ON` / `OFF` | `ON` | +| `BUILD_TESTING` | no | Enable build for unit tests | `ON` / `OFF` | `OFF` | +| `BUILD_ORTOOLS` | no | Enable build for OR-Tools and its dependencies (requires an Internet connection) | `ON` / `OFF` | `OFF` | +| `CMAKE_TOOLCHAIN_FILE` | no | Path to VCPKG toolchain file, allows to integrate VCPKG with cmake build | `../vcpkg/scripts/buildsystems/vcpkg.cmake` | | +| `VCPKG_TARGET_TRIPLET` | no | Define VCPKG triplet (build type for dependencies etc.) | `x64-windows-antares` / `x64-linux-antares` | | + +> 💡 **Disable the UI build to make builds faster** +> The UI takes up a good chunk of compilation time. It is enabled by default, but you can disable it by turning off `BUILD_UI` + +> 💡 **Use Ninja to speed up target generation by CMake** +> At configure time, you may specify Ninja for generation instead of traditional Make. This will speed up the update +> step after you make small changes to the code. +> ``` +> cmake -S src [...] -G Ninja +> ``` +> Note that you may need to install Ninja first (package `ninja-build` on Ubuntu). + +## Build +=== "Windows" + + ``` + cmake --build _build --config Release -j8 + ``` +=== "CentOS" + + ``` + cmake3 --build _build -j8 + ``` +=== "Ubuntu/Debian" + + ``` + cmake --build _build -j8 + ``` + +> 💡 Compilation can be done on several processors with `-j` option. + + +The final GUI file can be executed at `_build/ui/simulator/antares-X.Y-ui-simulator` + +## Developer tips + +### Use a compiler cache +In order to avoid unnecessary rebuilds, for example when you switch branches, you may use a compiler cache +such as ccache. Using it under Linux systems is pretty easy with CMake, you only need to specify it +as the compiler launcher at configure time: +``` +cmake ... -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache ... +``` + +### Ignore submodules to make git operations faster +Antares_Simulator is quite a large project, with a few large submodules. In file .git/config, you can add this line to all [submodule] sections +``` +ignore = all +``` +This way git won't waste time computing diff on these when checking out, diffing commits, etc. git operations should be a lot faster. +Keep in mind that your submodules won't be updated. + + + +[^1]: GUI support has been dropped in favor of [Antares Web](https://antares-web.readthedocs.io) \ No newline at end of file diff --git a/docs/developer-guide/4-Tests-dev.md b/docs/developer-guide/4-Tests-dev.md new file mode 100644 index 0000000000..f7db7e353f --- /dev/null +++ b/docs/developer-guide/4-Tests-dev.md @@ -0,0 +1,87 @@ +# Tests (developer) +This document describes the workflow used for the non-regression studies that are executed before every release. +The goal of these tests is to avoid any unexpected change in the results, thus ensuring compatibility of the new +versions with the old ones. + +*Antares Simulator*'s non-regression tests are divided in two repositories: +- [Antares_Simulator_Tests_NR](https://github.com/AntaresSimulatorTeam/Antares_Simulator_Tests_NR) contains the study batches (inputs). These batches are published in releases and do not contain any result. +- [SimTest](https://github.com/AntaresSimulatorTeam/SimTest) contains the study batches as well as reference results for some of the studies. + +## Antares_Simulator_Tests_NR +This repository publishes releases. Each release contains the following files: + +- `study-batches.txt`, a newline-separated list of study batches. A study batch is a group of Antares studies in the + same directory. Note that some studies may also be placed in a subdirectory. +- Archives containing the study batches. + +Here is an example of one version of `study-batches.txt`: +``` +short-tests +long-tests-1 +long-tests-2 +long-tests-3 +``` + +And here is the list of the corresponding archives: +- `short-tests.zip` +- `long-tests-1.zip` +- `long-tests-2.zip` +- `long-tests-3.zip` + +These archives can be found at the following URL: +`https://github.com/AntaresSimulatorTeam/Antares_Simulator_Tests_NR/releases/download//` + +In each study, there is a `check-config.json` file containing the necessary information for running tests. + +## SimTest +This is the source of releases. Each release contains the following files: +- `study-batches.txt`. It is merely a copy of `study-batches.txt` from Antares_Simulator_Tests_NR. +- For each study batch listed above, and for each target OS, an archive containing study results. + +As above, `check-config.json` are packaged in the archives: one per study. + +Here is a list of archives corresponding to the batches above (in this example, target OS are `windows-latest` and `ubuntu-latest`): + +- `short-tests-windows-latest.zip` +- `long-tests-1-windows-latest.zip` +- `long-tests-2-windows-latest.zip` +- `long-tests-3-windows-latest.zip` +- `short-tests-ubuntu-latest.zip` +- `long-tests-1-ubuntu-latest.zip` +- `long-tests-2-ubuntu-latest.zip` +- `long-tests-3-ubuntu-latest.zip` + +In the future, CentOS 7 should be included as well. + +## Configuration files +Every study contains a `check-config.json` file that configures the test. Here is its content. + +### Contents +[//]: # (TODO) +_**This section is under construction**_ + +#### name +The name of the test. Not really important, and currently not used. + +#### checks +The list of checks that the test should conduct on the results. +Contains one `output_compare` and one `integrity_compare` json objects. + +##### output-compare + +##### integrity-compare + +### Full example +```json + +``` + +## Workflow +The workflow is the following: + +1. Create a release in Antares_Simulator_Tests_NR (only if new studies are introduced). Tag it `X`. +2. Create a release in SimTest (only if a new feature is introduced, ie some results have changed) from Antares_Simulator_Tests_NR, tag `X` and Antares_Simulator, tag `Y`. +3. Use the release in SimTest to compare results of tag `Z` in Antares_Simulator. In this step, `pytest` is used as well as the `check-config.json` configuration files to test new results against the reference results. + +Note that steps 1 and 2 are rarely used, therefore there is no need to automate them. +Step 3, however, is to be run for every Antares_Simulator release, and so it [is automated in the 'run_tests' workflow](continuous-integration.md). diff --git a/docs/developer-guide/4-Tests-user.md b/docs/developer-guide/4-Tests-user.md new file mode 100644 index 0000000000..f2b8b25902 --- /dev/null +++ b/docs/developer-guide/4-Tests-user.md @@ -0,0 +1,31 @@ +--- +hide: + - toc +--- + +# Tests (user) + +Tests compilation can be enabled at configure time using the option `-DBUILD_TESTING=ON` (`OFF` by default). It is required only for unit-tests and end-to-end tests. + +After build, tests can be run with ``ctest`` : + +``` +cd _build +ctest -C Release --output-on-failure +``` + +All tests are associated to a label and multiple labels can be defined. You can choose which tests will be executed at ctest run. +Use `ctest -N` to see all available tests + +> For more information on `ctest` call, see [the cmake documentation](https://cmake.org/cmake/help/latest/manual/ctest.1.html) + +## Running JSON tests +To run JSON tests, a [study batch](https://github.com/AntaresSimulatorTeam/SimTest/releases) is first required. + +```bash +cd ${Antares_Simulator_ROOT}/src/tests/resources/batches +wget https://github.com/AntaresSimulatorTeam/SimTest/releases/download/v8.3.2/valid-defaillance-ubuntu-20.04.zip +unzip valid-defaillance-ubuntu-20.04.zip +cd ${Antares_Simulator_ROOT}/build +ctest -C Release --output-on-failure -R json +``` diff --git a/docs/developer-guide/5-Installer-creation.md b/docs/developer-guide/5-Installer-creation.md new file mode 100644 index 0000000000..459dac39f8 --- /dev/null +++ b/docs/developer-guide/5-Installer-creation.md @@ -0,0 +1,57 @@ +--- +hide: + - toc +--- + +# Installer creation +CPack can be used to create the installer after the build phase: + +=== "Windows" + ``` + cd _build + cpack -GNSIS + ``` + Currently missing in NSIS installer: + - External libraries sources + +=== "Centos" + + ### RHEL .rpm (Experimental) + ``` + cd _build + cpack3 -G RPM . + ``` + Note : + > `rpm-build` must be installed for RPM creation: `sudo yum install rpm-build` + + ### Linux .tar.gz + ``` + cd _build + cpack3 -G TGZ + ``` + + ### Required system libraries + There are still some system libraries that must be installed if you want to use *Antares Simulator*: + ``` + sudo yum install epel-release + sudo yum install wxGTK3 + ``` + +=== "Ubuntu/Debian" + + ### Ubuntu .deb (experimental) + ``` + cd _build + cpack -G DEB . + ``` + ### Linux .tar.gz + ``` + cd _build + cpack -G TGZ + ``` + + ### Required system libraries + There are still some system libraries that must be installed if you want to use *Antares Simulator*: + ``` + sudo apt install libwxgtk3.0-gtk3-0v5 + ``` diff --git a/docs/CHANGELOG.md b/docs/developer-guide/CHANGELOG.md similarity index 79% rename from docs/CHANGELOG.md rename to docs/developer-guide/CHANGELOG.md index fa88e14d54..d6606547da 100644 --- a/docs/CHANGELOG.md +++ b/docs/developer-guide/CHANGELOG.md @@ -1,45 +1,299 @@ -Antares Changelog -================= - -8.7.0 (08/2023) +--- +toc_depth: 2 +--- + +# Antares Changelog +## Branch 9.1.x + +### 9.1.0 (06/2024) +#### New features +* Scenarized & hourly values for hydro pumping and hydro generation. Previously this data was not scenarized and daily. +* STS groups are now "dynamic" : group names are no longer fixed by code, user is free to define these groups. +* Add optimization options from command line in OR-Tools / XPRESS (#1837) + +#### Improvements +* Rationalize consistency checks on the number of columns (#2073) +* Documentation reorganization and improvement (#2024) (#2023) (#2022) +* Add doc for thermal heuristic (#2048) + +#### Bugfixes +* Change the formula used in thermal clusters profits (#2097) [ANT-1719] +* Bug on GUI: double-click on study.antares doesn't work anymore (#2047) [ANT-1634] +* Fix build error related to Boost Test < 1.67 on OL8 (#2094) + +#### For developers +* Update format-code.sh (#2027) +* Update clang-format options and apply them (#2067) +* FileTreeStudyLoader [ANT-1213] (#2058) +* Yaml parser and Antlr4 integration (#1985) +* Fix oracle 8 compilation related to boost test linking (#2101) +* Fix enum deprecation warning for FileLevel (#2104) +* Improve new release workflow (#2088), make "target branch" field mandatory (#2095) +* Exclude src/ui from sonarQ analysis (#2087) +* Graphviz presets (#2065) +* Unit tests for parameters and generaldata.ini, remove limit on number of MC years (#2041) +* Move Run X Mode in dedicated files (#2054) +* Fix duplicate build for series/series.cpp (#2046) +* Improve dependency requirements (#2009) +* Time Series generation refactor (#2045) +* Create & forward declare BasisStatus struct, reduce build time (#2044) + +#### Code quality +* Simplify code for timer (#2032) +* Refactor Application (#2056) +* Remove some Yuni Strings in solver (#2061) +* Cleanup link variables includes (#2030) +* Remove Study::Ptr variant for RetrieveListFromStudy and cbuilder (#2051) (#2052) +* Add more explicit example on how to set solver parameters from command line (#2100) +* Fix a few warnings emitted by clang-19 (#2099) +* Remove Fixture Test Suite, use fixture test case (#2055) +* Use std::atomic instead of std::mutex (#2082) +* Use std::clamp for sc-builder's hydro levels (#2074) + +#### Removed +* Remove study cleaner tool (#2059) +* Remove export target (#2053) +* Remove unique_ptr passed by ref (#2086) +* Remove dependency of Antares::logs to antares-core (#2083) +* Remove unnecessary ".inc.hxx" files (#2031) +* Remove deps-build Actions (#2043) +* Remove unused logs.hxx (#2026) + +## Branch 9.0.x + +### 9.0.0 +#### License +* Use licence MPL 2.0 instead of GPL3_WITH_RTE-Exceptions (#1812) + +#### Improvements +* Include overflow variable in HydroPower constraint (#1903) +* Add total time logging at the end of the simulation (#1908) +* Add STS level constraint to suspect list for infeasible problem analysis (#1891) + +#### For developers +* Use precompiled OR-Tools for Oracle Linux 8 CI (#1893) +* Change version behavior to allow more flexibility (#1898) + +#### Code quality +* Use std::shared_ptr instead of indices for active binding constraints in results (#1887) +* Fix a few compilation warnings (#1880) +* Scratchpad numspace (#1749) + +#### Tests +* Fix invalid index causing segfault in `test-study` test (#1902) + +## Branch 8.8.x (end of support 12/2025) + +### 8.8.5 (05/2024) +#### Bugfix +- [UI] Fix opening a study from the file browser +- Fix crash occurring when duplicate thermal clusters are present in a study (same name) +- Fix formula for "PROFIT BY PLANT" + +### 8.8.4 (03/2024) +#### Bugfix +* Adequacy patch CSR - fix DTG MRG (#1982) +* Fix ts numbers for no gen clusters (#1969) +* Remove unitcount limit for time series generation (#1960) + +### 8.8.3 (02/2024) +#### Bugfix +* Fix an issue where depending on the platform the output archive could contain several entries of the same area and interco files + +### 8.8.2 +#### Bugfix +* Fix segfault caused by uninitialized `cluster.series.timeseriesNumbers` (#1876). This bug was introduced in v8.8.1 by #1752 +* Bump OR-Tools from 9.5 to 9.8 (fix crash with XPRESS) (#1873) + +### 8.8.1 (01/2024) +/!\ This version has known bugs, please use 8.8.2 instead. + +#### Bugfix +* Simplify TS numbers drawings, fix bug related to refresh & local thermal generation (#1752) + +#### Improvements +* Take into account breaking change in OR-Tools's API, enable SCIP & GLPK solvers, bump OR-Tools (#1825). This should improve performances with FICO XPRESS +* Fail if OR-Tools solver is not found (#1851) +* Normalize simulation mode Expansion, fix logs (#1771) +* Add possibility to release without running any tests (#1852) + +#### Code quality +* Use `std::unordered_map` for tmpDataByArea_ (hydro ventilation) (#1855) +* Remove `mutable` keyword from `PROBLEME_HEBDO` (#1846) +* Remove `Study::gotFatalError`, throw exceptions instead (#1806) +* Renewable containers (#1809) +* Use modern style `for` loops, avoid int cast (#1847) +* Remove `YUNI_STATIC_ASSERT` (#1863) + +#### Testing +* Add tests on short-term storage/thermal cluster/renewable cluster removal (#1841) + +#### Doc +* Add precision about `enabled` field in ST storage (#1850) +* Use dedicated URL path for Doxygen, instead of root (#1865) +* Fix HTML generation for readthedocs (#1867) +* Add dark mode switch for Doxygen online documentation (#1792) + +### 8.8.0 (12/2023) -------------------- -## New Features + +#### New features +* New "cash-flow" variable for ST storage (#1633) +* Experimental optimization with discrete variables (MILP unit-commitment mode #670) +* Add `enabled` property for ST storage objects, fix bug related to saving ST objects (#1807) +* Solver logs can be enabled either by the command-line option (--solver-logs) or in the generaldata.ini + +#### Improvements +* Add shortcut -s for names MPS problems in CLI options (#1613) +* Use 50% as a default value for ST-storage property initiallevel (#1632) +* Add warning logs for non-existent output variable (#1638) +* Add area name in error message for rare error (#1695) +* Fix wrong year number in logs upon failed year (#1672) +* Always check mingen against maxPower, regardless of reservoirManagement (#1656) +* New log msg when solver not found in or-tools (#1687) + +#### For developers +* Fix annoying error log about correlation matrices in tests (#1573) + +#### Bugfixes (reported by users) +* Fix output variable PROFIT for thermal clusters (#1767) +* Bug on renewable cluster (wrong group) (#1631) + +#### Bugfixes (reported internally) +* Fix oracle-linux8 binaries missing compression feature (#1741) +* Named MPS - fix duplicated "ranged" binding constraints (#1569) +* Fix save for short term storage objects (#1807) +* Prevent segfault during simulation, check bounds of scenario builder (#1567) +* Fix number of links in deprecated output file digest.txt (#1646) +* Fix unfeasible problem analyzer (#1527) +* [Windows only] Increase file size limit when reading file (#1674) +* Fix segfault encountered when importing logs (#1702) +* Fixes swallowed exceptions in computation thread (#1685) +* Fix writer causing a segfault with OR-Tools (#1584) + +#### Documentation +* Create Doxygen documentation (#1650) +* Update README.md (#1654) +* Add advice for developers (#1639) +* Document the usage of XPRESS (#1596) + +#### GUI +* Fix regression on cluster renaming, add unit tests (#1699) + +#### Dependencies +* Use minizip-ng 4.0.1 (from 3.0.7) (#1696) +* Bump vcpkg to latest tag (2023.07.21) (#1532) +* Remove dead code yuni-docmake (#1544) +* Remove fixed-size ints from Yuni (#1622, #1629) + +#### Code cleaning / quality +* Architecture Decision Record for Study breakdown (#1600) +* Remove dependency to UI, use RAII to handle resources (#1678) +* De-templatize `HydroManagement::prepareNetDemand` (#1679) +* Use `std::unique_ptr::operator->` rather than `std::unique_ptr::get` (#1676) +* Renamed `timeSeries` into `timeSeriesEnum` (#1675) +* Remove RenouvelableParPalier from global variable (#1659) +* Remove code duplication in src/libs/antares/study/parameters.cpp (#1667) +* Remove manual alloc and update code standards in hydro/daily2 (#1651) +* Remove `StudyRuntimeInfos::parameters` (#1665) +* Introduce & use DataSeriesCommon::getAvailablePowerYearly (#1660) +* Add getValue for thermal clusters, remove `State::timeSeriesIndex` (#1644) +* Move `resultWriter` out of class `Study` (#1649) +* Remove malloc in src/solver/hydro/ (#1626) +* Refactor constraint building (#1607) +* Remove most uses of `IResultWriter::Ptr`, use ref instead (#1642) +* Refactor hydro pmin checks (#1381) +* Clean up parameters.cpp (#1623) +* Remove unused `BindingConstraintsRepository::eachActive` (#1625) +* Provide reference to `Benchmarking::IDurationCollector`, not raw pointer (#1621) +* Use `int32_t` and `uint32_t` in `PROBLEME_HEBDO` (#1577, #1543) +* Reduce use of study in helper functions (#1610) +* Move thermal noises to class Simulation (#1594) +* Upgrade src/solver/hydro to C++ (#1581) +* Remove duplicate header (#1595) +* Remove unused variable (#1585) +* Remove dynamic alloc of PROBLEME_HEBDO (#1554) +* Remove memory usage (#1578) +* Use reference instead of raw pointers (#1579) +* Re-order initialization to avoid compilation warnings (#1599) +* Remove some global variables (#1545) +* Remove `goto` in `OPT_AppelDuSimplexe` (#1533) +* Remove useless Area's data member : `enabled` (#1556) +* Clarify string -> enum conversion for thermal cluster groups (#1553) +* Remove unmanaged dynamic allocation for `ProblemeAResoudre` (#1549) +* Remove `shared_ptr` for `OptPeriodStringGenerator` (#1528) +* Final removal of study singleton from the solver (#1536) +* Remove use of current study singleton in emergency exit (#1519) +* Remove unused function `getFilenameWithExtension` (#1537) +* Remove tmpnam from tests (#1506) + +#### Build +* ACR CMake (#1551) +* Add "Antares::action" CMake library, build only if BUILD_UI=ON (#1637) +* Fix conflicting library name (#1590) +* Cleanup date dependency (#1565) +* CMake Memory and Sys (#1558) +* Split benchmarking (#1582) +* Remove liblib* CMake targets (#1609) +* Split study in CMakefile (#1583) +* CMake usage improvements (#1548) +* Fix build for Oracle Linux 8 (#1542) + +#### Misc +* Schedule deps compile instead of develop merge (#1530) + +## Branch 8.7.x + +### 8.7.3 (02/2024) +#### Bugfix +* Use OR-Tools v9.8-rte1.0 (performance improvements with OR-Tools + XPRESS) + +### 8.7.2 (11/2023) +#### Bugfix +* Named MPS - fix duplicated "ranged" binding constraints (#1569) + +### 8.7.1 (11/2023) +#### Bugfix +* Fix output variable PROFIT for thermal clusters (#1767) + +### 8.7.0 (08/2023) +#### New Features * Binding constraint RHS scenarization (#1219) * Implement --mps-export command-line option (#1404) * Name constraints & variables in MPS files using --named-mps-problems command-lin e option (#1294) * Thermal price definition (contributed by RTE-i, #1272) -## Improvements +#### Improvements * Write full command-line instead of solver location in logs (#1518) -## Packages +#### Packages * Give Oracle Linux 8 assets a proper name instead of "unknown" (#1438) * Don't build tools (study-updater, etc.) by default (#1442) -## Bugfixes +#### Bugfixes * Fix error when writing files over 80Mb into a zip (#1488) * Fix memory leaks (#1468) * Fix segfault, add !skipped to enabled constraints (#1441) * Backport [v8.4.3](#v843-082023) changes -## GUI +#### GUI * Thermal price definition (RTEi's -> CR20) - UI (#1485) -## Docs +#### Docs * Fix possible values for ST storage (#1455) -## Tests +#### Tests * Add named MPS tests (#1408) * Enforce better unit test isolation (#1486) * Add tests for Windows CI when job is scheduled (#1483) * Tests for CR20: thermal price definition (#1364), improvements (#1422) -## For developers +#### For developers * Remove platform-specific headers (#1523) * Remove one `goto` instruction in OPT (#1522) * Remove study singleton in application signal handlers (#1513) * Remove barely-used `ThermalCluster::productionCost` temporary (#1517) -* Bindings constraints scenario : handling last remarks (#1466) +* Bindings constraints scenario : handling last remarks (#1466) * Replace remaining vector of pointers by plain vector (#1505) * Split ts numbers data classes in different files (#1398) * Remove more usage of study singleton (#1509) @@ -63,37 +317,60 @@ Antares Changelog * Named MPS: factorize variable & constraint namers (#1409) * Array, logs jit and correlation in makefile (#1410) --------------------- -# v8.6.2 (08/2023) -## Bugfixes +## Branch 8.6.x (end of support 06/2025) +### 8.6.7 (05/2024) +#### Bugfixes +* Fix formula use in output var Profit by plant [ANT-1719] (https://github.com/AntaresSimulatorTeam/Antares_Simulator/pull/2097) + +### 8.6.6 (03/2024) +#### Bugfixes +* Adequacy patch CSR - fix DTG MRG (#1982) +* Fix ts numbers for no gen clusters (#1969) +* Remove unitcount limit for time series generation (#1960) + +### 8.6.5 (02/2024) +#### Bugfix +* Use OR-Tools v9.8-rte1.0 (performance improvements with OR-Tools + XPRESS) + +### 8.6.4 (11/2023) +#### Bugfixes +* Fix Oracle Linux minizip build + actually run zip unit tests (#1744) +* Fix output variable PROFIT for thermal clusters (#1767) + +### 8.6.3 (10/2023) +#### Bugfixes +* Increase file size limit from 80Mo to 80Go when reading file. Fix issue on Windows + +### 8.6.2 (08/2023) +#### Bugfixes * Backport [v8.4.3](#v843-082023) changes -8.6.1 (06/2023) +### 8.6.1 (06/2023) -------------------- -## Bugfixes +#### Bugfixes * Fix major bug related to short-term storage & MRG. PRICE (#1377) -8.6.0 (06/2023) +### 8.6.0 (06/2023) -------------------- -## New features +#### New features * Short-term storage (#1163). * Add pollutant emissions (#1184, #1222) * Minimal generation for hydraulic (#1273, RTE/RTE-i/Redstork) * Make LMR optional for adequacy patch (#1247) -## Improvements +#### Improvements * Use ISO8601 for date format in the logs (#1303) * Publish installers for Oracle Linux 8 (#1341) * Remove doc from UI/package, publish it as a separate PDF (#1233) * Tune XPRESS resolution (#1158), this should improve performance for OR-Tools+XPRESS * Performance metrics (produce a JSON file) (#1306) -## Bugfixes +#### Bugfixes * Fix a bug in adequacy study mode (#1314) * Fix memory errors detected by valgrind (#1302) * Fix empty ROR & STORAGE in output using the TS-Generator (#1293) -## Code quality +#### Code quality * Simplify if/else (#1309) * Max number of columns in an output file (#1159) * Fix a few compilation warnings (int -> uint) (#1301) @@ -106,67 +383,70 @@ Antares Changelog * INI files load encapsulation (#1057) * Remove group{Min,Max}Count, annuityInvestment in thermal clusters (#1350) -## For developers +#### For developers * Bumped OR-Tools 9.2 -> 9.5. CMake 3.18+ is required for build if building OR-Tools, and XPRESS 9.0 for execution (previously 8.13). +## Branch 8.5.x +### 8.5.1 (08/2023) -------------------- -# v8.5.1 (08/2023) - +#### Changes * Backport [v8.4.3](#v843-082023) changes -# v8.5.0 (02/2022) - -## New features +### 8.5.0 (02/2022) +-------------------- +#### New features * Curtailment Sharing Rule for Adequacy Patch #1062, including a scaling coefficient in hurdle costs #1155. This feature was contributed by RTE-i with support from RTE, ELIA and APG. -## Bugfix +#### Bugfix * Hydraulic patch #697 * Fix link path error in Kirchhoff constraint builder #1157 -## For developers +#### For developers * Fix build on Ubuntu 22.04 #1160 * Cleaning #1142, 1146, #1149 -## Examples & documentation +#### Examples & documentation * Update docs to include CSR #1156 * Fix examples studies (invalid v8.3.0 -> v8.5.0) #1136 +## Branch 8.4.x -# v8.4.3 (08/2023) +### 8.4.3 (08/2023) +-------------------- -## Features +#### Features * Increase file size limit from 80Mo to 80Go when reading file. -## Bugfix +#### Bugfix * Fix "unhandled error" with big studies in zip mode. MPS files were too big and hit file size hard limit -v8.4.2 (01/2022) +### 8.4.2 (01/2022) -------------------- -## Improvements +#### Improvements * Generate a solver-only asset for every release #976, #1080 * Use MPS writer from solvers, instead of copy-pasted functions #1023 -## GUI +#### GUI * Allow more than 100 thermal clusters #1011 * Remove status bar count. The sum was sometimes wrong #1029 * Remove unused "District marginal prices" button from Advanced Parameters #1067 -## Bugfix +#### Bugfix * Fix overwritten MPS files when optimization/simplex-range=day #1041 * Restore warm start for OR-Tools+XPRESS #1079 * Fix output overwrite when using zip output by adding a -2, -3, etc. suffix #1044 * Fix crash when generaldata.ini is empty, using default values #892 -## Testing +#### Testing * Introduce missing MPS comparison tests #1035 -## For developers +#### For developers * Fix empty CMAKE_BUILD_TYPE #1028 * Fix memory leaks #669 -## Code cleaning +#### Code cleaning * Clean up Yuni #1055 * Remove default implementation for hourEnd (see variable.hxx) #1020 * Remove free functions for areas' mem allocation #922 @@ -179,21 +459,21 @@ v8.4.2 (01/2022) * Pass optimization number as an argument #1040 -## New Contributors +#### New Contributors * @JasonMarechal25 made their first contribution in #1055 **Full Changelog**: https://github.com/AntaresSimulatorTeam/Antares_Simulator/compare/v8.4.1...v8.4.2 -v8.4.1 (12/2022) +### 8.4.1 (12/2022) -------------------- -### Bugfix +#### Bugfix * Fix formula for profit calculation #1022 -v8.4.0 (12/2022) +### 8.4.0 (12/2022) -------------------- -### Features +#### Features * Add option & command-line argument to write results into a single zip archive #794 * Add option to set link capacity to null/infinity for physical links only #792 * Speed up simulations by extracting simplex basis in XPRESS/OR-Tools #957 @@ -201,10 +481,10 @@ v8.4.0 (12/2022) * Do not export BC MARG PRICE variable by default by #928 * Enable MPS write with OR-Tools+Sirius -### GUI +#### GUI * Make sure that RC/beta are displayed in version numbers #739 -### Bugfix +#### Bugfix * Remove error message printed on -h/--help in antares-solver #895 * Use average for BC MARG PRICE (daily & weekly) #940 * Fix crash when exporting MPS with OR-Tools #923 @@ -216,7 +496,7 @@ v8.4.0 (12/2022) * Make logs more expressive when checking link values by @flomnes in #1005 * Add condition to avoid null pointer by @payetvin in #989 -### For developers +#### For developers * Case insensitive option for build type by @payetvin in #986 * [DEV] Refactored ortools_utils by @payetvin in #978 * [CI] Integrate ortools v9.2-rte2.0 by @payetvin in #1007 @@ -230,35 +510,36 @@ v8.4.0 (12/2022) * Remove antares-solver swap variant & librairies, reduce build duration #906 -### Documentation +#### Documentation * [DOC] OR-Tools build #880 * Document how to run JSON tests #902 * Document option --list-solvers #770 -## New Contributors +#### New Contributors * @kathvargasr made their first contribution in #967 **Full Changelog**: https://github.com/AntaresSimulatorTeam/Antares_Simulator/compare/v8.3.2..v8.4.0 -v8.3.3 (12/2022) +## Older branches +### 8.3.3 (12/2022) -------------------- -### Bugfix +#### Bugfix - Round renewable production (#985) -v8.3.2 (09/2022) +### 8.3.2 (09/2022) -------------------- -### Output aggregation change +#### Output aggregation change - Daily, weekly, monthtly & annual values for link variable "MARG. COST" (EUR/MWh) was previously obtained by a sum. It now computed by average (#881). -### New features +#### New features - Add new BC marginal price output variable (#801) - Add Antares logo in solver logs (#861) - Add XPRESS-compatible assets for Ubuntu. Windows coming soon. -### GUI +#### GUI - In the "Links" panel, replace "Flat" view by "By area" view (#755) -### Bug fixes +#### Bug fixes - Fix segfault when more than 9 renewable clusters are present in an area (#869) - Fix segfault related to the digest occurring when many thermal clusters are present (#852) - Statistics: use std::mutex / std::atomic<> to prevent concurrent writes (#838) @@ -266,7 +547,7 @@ v8.3.2 (09/2022) - Fix warning in hydro.ini loading function (#883) - MPS for the 1st optimization were erased by the one related to the 2nd optimization. Fixed (#863). -### For developers +#### For developers - Simplify day ahead reserve condition (#777) - Remove unused "shedding strategy" (#788) - Refactor Layers by adding a LayerData class (#866) @@ -277,28 +558,28 @@ v8.3.2 (09/2022) - Simplify Parameters::fixRefreshIntervals, clean headers (#832) - Simplify tuneSolverSpecificOptions (#829) -### Documentation +#### Documentation - Input and output format due to addition of BC marginal prices (#836) - Fix e-mail address and website (#834) -v8.3.1 (08/2022) +### 8.3.1 (08/2022) -------------------- -### New features +#### New features - Add execution-info.ini output file, containing execution durations and study info #740 #803 #816 - OR-Tools: set solver-specific options for XPRESS #796 -### Bug fixes +#### Bug fixes - Fix missing renewable columns in districts (sets of areas) #802 -### GUI +#### GUI - Fix wrong number of cores in the "Run a simulation" window #793 -### For developers +#### For developers - Bump C++11 to C++17 -v8.3.0 (07/2022) +### 8.3.0 (07/2022) -------------------- -### New features +#### New features - Adequacy patch - share the unsupplied energy according to the "local matching rule". This feature was contributed by RTE-i with support from RTE, ELIA and APG #657 - Add output variable "profit by cluster". This variable represents the difference between proportional costs and marginal costs in the area. It provides a partial answer to the question "what is the economic profit associated to a thermal cluster ?", excluding non-proportional (€/h) and startup costs (€/startup). #686 - Allow +/- infinity in binding constraint RHS, allowing the user to enable BCs only for some timesteps #631(*) @@ -308,7 +589,7 @@ v8.3.0 (07/2022) (*) May not work with the Sirius solver. Consider using other solvers through OR-Tools -### Bug fixes +#### Bug fixes - Fix segfault occuring when inter/intramodal correlation is enabled and TS width are inconsistent #694 - Fix logging of performed MC years when running jobs in parallel #680 - Fix a crash occuring in studies where an area contains 100+ thermal clusters (#753) @@ -317,38 +598,38 @@ v8.3.0 (07/2022) - UI For property update for adq-patch mode, allow batch edit (#747) - UI - Fix GUI freeze when using multiple map layers (#721) -### For developers +#### For developers - Display the git commit-id in the logs for debugging & diagnosis purposes #698 - Code cleaning in hydro heuristic #671 - Use antares-deps 2.0.2, which now excludes OR-Tools #684 - Fetch OR-Tools directly, allowing more flexibility on the flavor (XPRESS/Sirius/etc.) #684 - Code cleaning #663 #665 #666 #687 #725 #667 #668 #730 -### Misc. improvements +#### Misc. improvements - Generate 2 assets in CentOS 7 : one that includes XPRESS, one that does not #689 - Upgrade examples 8.1 -> 8.3 (#733) -v8.2.3 (11/2022) +### 8.2.3 (11/2022) -------------------- -### Bug fixes +#### Bug fixes - Round renewable production (#985) -v8.2.2 (04/2022) +### 8.2.2 (04/2022) -------------------- -### Bug fixes +#### Bug fixes - Fix solver crash on parsing command-line parameters #624 -### GUI +#### GUI - Fix crash occuring when switching to the links panel #658 -v8.2.1 (03/2022) +### 8.2.1 (03/2022) -------------------- -### Bug fixes +#### Bug fixes - Fix scenario builder data loss when renaming area #610 - Write 1 in the ts-numbers when series.width == 1 #609 - Add noise to the cost vector in the allocation problems to enforce uniqueness #622 - Linux only : fix segfault occurring when an INI file does not exist #606 -### GUI +#### GUI - Place "Dataset > Resize columns to..." in first position #607 - Allow that all NTC be 0 in one direction #595 - Fix occasional crash when opening the links panel #594 @@ -356,115 +637,115 @@ v8.2.1 (03/2022) - Linux only : fix impossibility to save a study #600 - Developer version only : fix assertion errors in the GUI #584 -v8.2.0 (03/2022) +### 8.2.0 (03/2022) -------------------- -### New features +#### New features - Multiple timeseries for link capacities (NTC). It is now possible to establish different scenarios for the capacity of a link. Users can now take partial or total outages for links into account #520 - Infeasible problem analyzer. When the underlying problem has no solution, list the most suspicious constraints in a report. This should help users identify faulty binding constraints #431 - Add a hydro-debug switch that allows the printing of some useful debug data in heuristic mode #254 -### GUI +#### GUI - Add a "view results" button in the dialog that appears when a simulation has been completed #511 - Help menu : add an "online documentation" item #509 - Improve UI for new thermal parameter "tsGenBehavior" #534 - Improve cell styles when loop-flow is enabled for a link #571 -### Bug fixes +#### Bug fixes - Prevent an area from having a link to itself #531 - Fix crash when the study folder does not exist #521 - Fix crash when failing to load a study #502 -### For developers +#### For developers - Remove calls to exit() #505. Provide consistent return values for antares-solver by fixing a segfault related to the log object #522 - Remove calls to setjmp, goto's big brother #527 - Large refactor of antares-solver's main function, hoping to make error management easier to understand #521 - Use std::shared_ptr instead of Yuni::SmartPtr in most cases #529 - Simplify and clean some parts of the code #537, #538, #540 -v8.1.1 (01/2022) +### 8.1.1 (01/2022) -------------------- -### Bug fixes +#### Bug fixes - Fix segfault occurring randomly when thermal clusters are disabled (#472) - Fix hydro level discontinuities (#491). Very rarely, hydro reservoirs would inexplicably be filled from 0% to 100% in 1h, this violating the modelling constraints. - Execution times when the Sirius solver is used in conjunction with OR-Tools are now similar as with Sirius alone. This is a result of [this fix](https://github.com/AntaresSimulatorTeam/or-tools/pull/1), related to "hot-start". -### GUI +#### GUI - Speed up scrolling (#395) - Warn the user about disabled renewable clusters only when relevant (#386) -### Packages +#### Packages Include antares-analyzer into .zip and .tar.gz archives (#470). This is especially useful if you use the portable version of Antares. -### For developers +#### For developers In the CI workflow, CentOS 7 now uses devtoolset-9 (previously 7), with in particular gcc 9. This allows for C++17 features to be used without hassle. -v8.1.0 (09/2021) +### 8.1.0 (09/2021) -------------------- -### New features +#### New features - Allow up to 9 RES groups (off-shore wind, on-shore wind, rooftop solar, PV solar, etc.) as opposed to wind and solar previously. This allows the user to distinguish between more renewable energy sources. When creating a new study, renewable generation modelling is set to "clusters" by default. This change does not affect opening an existing study. Note that TS generation is not available for these new RES groups. - Add 3 thermal groups, named other, other 2, other 3 and other 4. -### Bug fixes +#### Bug fixes - When a binding constraint is marked as skipped in the GUI, disable it in the solver #366 -### GUI +#### GUI - Keep selection on thermal/renewable cluster when its group changes #360 - Dialogs "Thematic trimming" and "User playlist" are now resizable -### For developers +#### For developers - Add non-regression tests on each release - Fix vcpkg on Github Actions - Add build cache for Github Actions to speed up the build (Linux only) -v8.0.3 (05/2021) +### 8.0.3 (05/2021) -------------------- -### Bug fixes +#### Bug fixes - Fix calculation of average for variable "congestion probability" - Fix NODU when unit number is not an integer i.e has decimals - GUI: allow decimal nominal capacity for thermal clusters - GUI: Linux: use xdg-open to open pdf files instead of gnome-open -### For developers +#### For developers - Remove code related to licence management - Remove openssl and libcurl dependencies - Remove dead code -v8.0.2 (04/2021) +### 8.0.2 (04/2021) -------------------- -### Bug fixes +#### Bug fixes - Fix GUI freeze when area color is changed but user don't validate new color - Correction of MC year weight use for PSP and MISC NDG -v8.0.1 (03/2021) +### 8.0.1 (03/2021) -------------------- -### Features +#### Features - Add "Continue Offline" button at startup if antares metric server is unreachable -### Bug fixes +#### Bug fixes - Error with hydro start when using scenario playlist and stochastic TS refresh span - Files needed for antares-xpansion not exported when using scenario playlist with first year disabled - Correction of crash if user define a stochastic TS refresh span of 0 : minimum value is now 0 - Correction of MC years playlist weight write when sum of weight was equal to number oy years (no MC years playlist export in .ini) -### For developers +#### For developers - Add a GitHub action to check if branch name will launch CI - Add shared dll in windows .zip archive -v8.0.0 (03/2021) +### 8.0.0 (03/2021) -------------------- -### Features +#### Features - OR-Tools integration : - add command line option in antares-solver to define OR-Tools use and OR-Tools solver (option --use-ortools and --ortools-solver='solver') @@ -498,7 +779,7 @@ v8.0.0 (03/2021) After simulation, the MC year have a contribution to averages or standard deviations in synthesis results depending on the weight it was given. -### Bug fixes +#### Bug fixes - Selecting an area and then, from the inspector, trying to select a thermal cluster or a link of this area in the dependencies section causes a crash. The inspector's cluster/link selection was removed. @@ -509,7 +790,7 @@ v8.0.0 (03/2021) triggered. If the disabled cluster is given a number for many MC years in the active rule, a single summary warning should be raised, not a warning per year. -### For developers +#### For developers - External dependencies : - use of new repository [antares-deps](https://github.com/AntaresSimulatorTeam/antares-deps) for external dependencies compilation @@ -536,10 +817,10 @@ v8.0.0 (03/2021) - Adding pytest scripts to check reference output values - Add pytest scripts related to unfeasible problems -v7.2.0 (06/2020) +### 7.2.0 (06/2020) -------------------- -### Features +#### Features - Simulation dashboard: A new "Geographic Trimming" option is now available in the "Configure" menu. This option makes @@ -583,7 +864,7 @@ v7.2.0 (06/2020) - Usage metrics: added reference key for this version -### Bug fixes +#### Bug fixes - GUI of the "Thematic trimming" option: Window size is naturally readjusted to improve readability by upgrading wxwidgets (3.1.3 and above). @@ -592,10 +873,10 @@ v7.2.0 (06/2020) command line syntax have been introduced and now make it possible to launch a sequence of simulations to run in parallel -v7.1.0 (12/2019) +### 7.1.0 (12/2019) -------------------- -### Features +#### Features - Simulation Dashboard: A new option "Thematic Trimming" is available in the "Output Profile" Section. This option @@ -625,7 +906,7 @@ v7.1.0 (12/2019) - Usage metrics: added reference key for this version -### Bug fixes +#### Bug fixes - Output file "mc-all/grid/digest.txt": replaced "NaN" values by zeroes, where appropriate @@ -651,10 +932,10 @@ v7.1.0 (12/2019) any data for given Areas or Links, avoid creation of empty folders named after said Areas or Links -v7.0.1 (04/2019) +### 7.0.1 (04/2019) -------------------- -### Features +#### Features - Time-series analysis: in "detrended mode", extended perimeter to raw data including periods with no meaningful signal @@ -662,10 +943,10 @@ v7.0.1 (04/2019) - Hydro-storage modelling: added ability to optimize pumping along with generation in mode "use heuristic target without leeway" -v7.0.0 (12/2018) +### 7.0.0 (12/2018) -------------------- -### Features +#### Features - GPL release: updated companion files (README,...) - GPL release: updated project Icons @@ -679,24 +960,24 @@ v7.0.0 (12/2018) - Documentation: updated optimization problem formulation - Documentation: updated examples library -v7.0.0-rc (12/2018) +### 7.0.0-rc (12/2018) -------------------- -### Features +#### Features - Improved code for linux compilation with gcc 7 -### Bugs +#### Bugs - Fixed various issues in GUI - Fixed RHS of constraints generated by the KCG when min and max values of PST settings are strictly equal and constraints are generated for the whole year -v6.5.1 (11/2018) +### 6.5.1 (11/2018) ---------------- -### Bugs +#### Bugs - Fixed index in hydro heuristic engine - Hydro GUI: added scrollbars for correct display on laptops @@ -704,10 +985,10 @@ v6.5.1 (11/2018) - Kirchhoff's constraint generator: fixed several GUI issues - Districts GUI: improved syntax control -v6.5.0 (11/2018) +### 6.5.0 (11/2018) ---------------- -### Features +#### Features - Implementation of Kirchhoff's laws (DC approximation), modeling of phase-shifters and representation of passive @@ -785,7 +1066,7 @@ v6.5.0 (11/2018) - Example library: upgraded to 6.5 (without extension) -### Bug fixes +#### Bug fixes - Time-series generation: the storage (Input folder) of time-series generated for thermal clusters either in the @@ -802,10 +1083,10 @@ v6.5.0 (11/2018) value (changed to 2 decimal accuracy) -v6.1.3 (06/2018) +### 6.1.3 (06/2018) ---------------- -### Features +#### Features - Output: added a new file at the root of simulation results, displaying a short summary of the overall system economic @@ -819,7 +1100,7 @@ v6.1.3 (06/2018) - Expansion mode: presolve stage replaced by hot start -### Bug fixes +#### Bug fixes - Simulation: In the "accurate" Unit Commitment mode, the optimization preference "thermal Clusters Min Up/Down Time" @@ -833,27 +1114,27 @@ v6.1.3 (06/2018) - Example library : upgraded to 6.1 and extended -v6.1.2 (11/2017) +### 6.1.2 (11/2017) ---------------- -### Features +#### Features - Solver, Simplexe package: Improvement of the Scaling stage (Matrix, right hand side, costs) -v6.1.1 (11/2017) +### 6.1.1 (11/2017) ---------------- -### Features +#### Features - Solver: Light changes in Presolve stage -v6.1.0 (09/2017) +### 6.1.0 (09/2017) ---------------- -### Features +#### Features - GUI and simulation: "binding constraints" objects may now involve not only flows on interconnections but also power generated from @@ -862,10 +1143,10 @@ v6.1.0 (09/2017) associated with arbitrary offsets (time-lags expressed in hours). -v6.0.6 (07/2017) +### 6.0.6 (07/2017) ---------------- -### Features +#### Features - GUI: Binding constraint parameters tables (weights and offsets) are trimmed line-wise so as to fit exactly with the content of the selected working map @@ -875,10 +1156,10 @@ v6.0.6 (07/2017) -v6.0.5 (07/2017) +### 6.0.5 (07/2017) ---------------- -### Bug fixes +#### Bug fixes - Solver: Pruning of redundant messages in simulations launched from command line @@ -890,10 +1171,10 @@ v6.0.5 (07/2017) cleaning datasets (detected as of 6.0.0) -v6.0.4 (06/2017) +### 6.0.4 (06/2017) ---------------- -### Bug fixes +#### Bug fixes - GUI: The "variable per variable" view of the output files allows to display the power generated by each thermal cluster @@ -902,15 +1183,15 @@ v6.0.4 (06/2017) unsupplied energy allowances -v6.0.3 (06/2017) +### 6.0.3 (06/2017) ---------------- -### Features +#### Features - GUI: The number of system maps that could be stored in a given study was limited to 19. This number is now unbounded. -### Bug fixes +#### Bug fixes - GUI: The list of thermal clusters displayed for a given Area in the current map was sometimes wrongly initialized (Area considered @@ -923,16 +1204,16 @@ v6.0.3 (06/2017) circumstances -v6.0.2 (06/2017) +### 6.0.2 (06/2017) ---------------- -### Features +#### Features - Optimization : To help discriminate between equivalent economic solutions, random noises on hydro hourly prices are more regularly spread out (absolute values) in the interval (5 e-4 ,1 e-3)Euros/MWh -### Bug fixes +#### Bug fixes - Simulation : The identification of the Monte-Carlo year numbers in which the smallest/greatest values of random variables are @@ -940,10 +1221,10 @@ v6.0.2 (06/2017) two years ore more. -v6.0.1 (05/2017) +### 6.0.1 (05/2017) ---------------- -### Features +#### Features - Thermal Time-series generation: Data regarding all thermal clusters are generated and stored in the same way, regardless of their activity @@ -968,10 +1249,10 @@ v6.0.1 (05/2017) listed above -v6.0.0 (04/2017) +### 6.0.0 (04/2017) ---------------- -### Features +#### Features - GUI: A new interface makes it possible to define several views (maps) of the Power System modelled in an Antares study. These maps are meant to give @@ -1005,10 +1286,10 @@ v6.0.0 (04/2017) copy to backup folders, registering of studies and archives in catalogues. -v5.0.9-SE (04/2017) +### 5.0.9-SE (04/2017) ---------------- -### Bug fixes +#### Bug fixes - Random noises on thermal clusters costs now include the zero-cost "must-run" clusters (as a consequence, noises assumptions do not vary @@ -1018,26 +1299,26 @@ v5.0.9-SE (04/2017) minimum number of committed thermal units (+1 or -1 deviation, "accurate" mode only) -v5.0.7-SE (04/2017) +### 5.0.7-SE (04/2017) ---------------- -### Features +#### Features - License control : management of SSL certificates encrypted through SHA-256 algorithm -v5.0.7 (12/2016) +### 5.0.7 (12/2016) ---------------- -### Bug fixes +#### Bug fixes - Fixing a packaging error -v5.0.6 (12/2016) +### 5.0.6 (12/2016) ---------------- -### Bug fixes +#### Bug fixes - Results processing: For full "must-run" thermal clusters, the NODU variable could be wrongly assessed in the "accurate" unit commitment simulation mode @@ -1047,7 +1328,7 @@ v5.0.6 (12/2016) the deleted object were kept alive in the scenario builder context) -### Features +#### Features - Unsupplied energy control: if the actual economic optimization requires it, load shedding is now allowed to occur in areas where the available thermal generation @@ -1065,10 +1346,10 @@ v5.0.6 (12/2016) -v5.0.5 (08/2016) +### 5.0.5 (08/2016) ---------------- -### Bug fixes +#### Bug fixes - No-Load Heat costs and Start-up costs: in the "fast" unit commitment options, the result was slightly below the actual optimal possible cost for some @@ -1080,7 +1361,7 @@ v5.0.5 (08/2016) can work properly again (feature inhibited in previous 5.0.x versions) -### Features +#### Features - License control throughout the internet: all combinations of UTF8 characters can now be used within proxy ids and passwords @@ -1090,14 +1371,14 @@ v5.0.5 (08/2016) is locally expressed as a constraint of the optimization problem (LOLE=0) -v5.0.4 (05/2016) +### 5.0.4 (05/2016) ---------------- -### Bug fixes +#### Bug fixes - Errors occured on loading the "min gen modulation" time-series of thermal clusters -### Features +#### Features - Better estimate of the number of thermal units dispatched in "fast" unit commitment mode - Nodal Marginal Prices and Marginal yield on interconnections are now available in @@ -1106,33 +1387,33 @@ v5.0.4 (05/2016) negative values can be used for all classes of constraints (hourly, daily, weekly) -v5.0.3 (05/2016) +### 5.0.3 (05/2016) ---------------- -### Bug fixes +#### Bug fixes - Crashes occured when the "full must-run status" parameter was set on "true" for thermal clusters -v5.0.2 (04/2016) +### 5.0.2 (04/2016) ---------------- -### Bug fixes +#### Bug fixes - Removed debug information that should not be displayed in release mode -### Features +#### Features - The optimization criterion used to assess the hydro energies to generate throughout each month incorporates heavier penalization terms for the 12 deviations from the theoretical monthly targets (formerly, only the largest deviation was penalized). -v5.0.1 (04/2016) +### 5.0.1 (04/2016) ---------------- -### Bug fixes +#### Bug fixes - Adequacy mode: fixed a memory allocation bug that forced the post-simulation output files processing to be interrupted @@ -1141,10 +1422,10 @@ v5.0.1 (04/2016) performances in some cases. This problem is now solved. -v5.0.0 (03/2016) +### 5.0.0 (03/2016) ---------------- -### Bug fixes +#### Bug fixes - GUI, system map: copy /paste of binding constraints could alter the activity status or the names of the duplicated binding constraints in some instances @@ -1173,7 +1454,7 @@ v5.0.0 (03/2016) - Output, File comparison functions: "Max" operator has been added -### Features +#### Features - Optimization: introduction of a new unit-commitment mode based on a MILP approach slower but more accurate than the former one. An option lets the user choose which mode should be used (fast/accurate) @@ -1208,10 +1489,10 @@ v5.0.0 (03/2016) -v4.5.4 (03/2015) +### 4.5.4 (03/2015) ---------------- -### Bug fixes +#### Bug fixes - License checking: internet proxys for which no login and/or password have been defined can now be used @@ -1219,10 +1500,10 @@ v4.5.4 (03/2015) - Upgrade to 4.5 format of datasets edited in 4.4 format or lower, in which the "scenario builder" feature was activated: the conversion to 4.5 format could fail sometimes. -v4.5.3 (02/2015) +### 4.5.3 (02/2015) ---------------- -### Features +#### Features - Start-up and fixed thermal costs: the interpretation of the unit-commitment strategy (starting-up and shutting-down times of each thermal unit) includes the explicit @@ -1236,7 +1517,7 @@ v4.5.3 (02/2015) - Control of license validity through the internet (setting up of a dedicated server) -### Bug fixes +#### Bug fixes - Scenario builder: indices not subject to random draws could be mixed up in areas including both "must-run" units and "regular" units (bug circumscribed to the thermal @@ -1245,18 +1526,18 @@ v4.5.3 (02/2015) - Spillage management, when numerous binding constraints are active: an excessive leeway could be observed regarding the level of hydro power allowed to be curtailed -v4.5.2 (06/2014) +### 4.5.2 (06/2014) ---------------- -### Bug fixes +#### Bug fixes - In the previous version, the average values of interconnection-related variables were multiplied by two and this error was propagated to the standard deviation of the same variables -v4.5.1 (06/2014) +### 4.5.1 (06/2014) ---------------- -### Features +#### Features - Start-up and fixed thermal costs: the contribution of each thermal cluster to the operating cost is now explicitly displayed in the results (field : "non proportional cost") @@ -1264,10 +1545,7 @@ v4.5.1 (06/2014) - Load time-series : negative values are now authorized - - - -### Bug fixes +#### Bug fixes - Creation of a thermal cluster : the default value of the NPOMAX parameter is set to 100 @@ -1278,10 +1556,10 @@ v4.5.1 (06/2014) - Copy/paste of nodes : the field "spread on unsupplied energy cost" was not pasted -v4.5.0 (04/2014) +### 4.5.0 (04/2014) ---------------- -### Features +#### Features - Simplex solver: acceleration regarding the control of the admissibility of the solution in the dual stages. This brings a significant improvement of the calculation time for @@ -1292,7 +1570,7 @@ v4.5.0 (04/2014) non-zero system costs ( max = 5 10^4 Euros/MWh ; min = 5 10^-3 Euros/MWh) -### Bug fixes +#### Bug fixes - Hydro Time-series generation : the GUI did not react properly when forbidden values (negative) were seized for energy expectation and/or standard deviation @@ -1302,10 +1580,10 @@ v4.5.0 (04/2014) within a week was not fully optimized -v4.4.1 (05/2013) +### 4.4.1 (05/2013) ---------------- -### Bug fixes +#### Bug fixes - Creation of a new binding constraint: the operation needed to be confirmed twice (double click on "create button") and the study had to be "saved as" and reloaded before @@ -1318,10 +1596,10 @@ v4.4.1 (05/2013) -v4.4.0 (04/2013) +### 4.4.0 (04/2013) ---------------- -### Features +#### Features - Antares licenses can be either static or floating. Floating tokens are managed and distributed by the Flexnet product, version 11.9. @@ -1352,32 +1630,32 @@ v4.4.0 (04/2013) is levelled on the other days of the month with a flatter pattern. -### Bug fixes +#### Bug fixes - On creation of a new link, the transmission capacity status parameter is set to `Use transmission capacities` instead of `Set to null`. -v4.3.7 (02/2013) +### 4.3.7 (02/2013) ---------------- -### Features +#### Features - Performance improvements for graphical display of large tables -### Bug fixes +#### Bug fixes - The binding constraint data might not be written properly in some cases when the constraint was renamed. -V4.3.6 (12/2012) +### 4.3.6 (12/2012) ---------------- -### Bug fixes +#### Bug fixes - Windows only: fixed potential crash which could happen when exiting a simulation in adequacy mode with import of generated time-series @@ -1386,10 +1664,10 @@ V4.3.6 (12/2012) consideration user- and folder-related quotas -V4.3.5 (10/2012) +### 4.3.5 (10/2012) ---------------- -### Features +#### Features - The calendar field "year" is now available in the simulation main screen (allows not only simulations from JAN to DEC but also from OCT to SEP, etc.) @@ -1407,7 +1685,7 @@ V4.3.5 (10/2012) the ultimate choice may differ from that of the previous version -### Bug fixes +#### Bug fixes - Reference numbers of the time-series used in the course of a simulation: When the simulation is based on a user-defined scenario (building mode: custom) @@ -1425,17 +1703,17 @@ V4.3.5 (10/2012) -V4.2.6 (07/2012) +### 4.2.6 (07/2012) ---------------- -### Features +#### Features - The field "MAX MRG" (last of the nodal results) is now available in the output files - The Monte-Carlo synthesis edition can be skipped when year-by-year results are asked for -### Bug fixes +#### Bug fixes - Binding constraints: in the filter available for the weight matrix, removal of redundant options @@ -1457,10 +1735,10 @@ V4.2.6 (07/2012) -v4.1.0 (06/2012) +### 4.1.0 (06/2012) ---------------- -### Features +#### Features - Hydro storage energy management : each nodal policy of use can be tuned so as to accommodate simultaneously the net load of several nodes @@ -1478,10 +1756,10 @@ v4.1.0 (06/2012) -v3.8.0 (12/2011) +### 3.8.0 (12/2011) ---------------- -### Features +#### Features - The simulation mode `Adequacy` is renamed `Draft`. @@ -1500,10 +1778,10 @@ v3.8.0 (12/2011) -V3.7.4 (08/2011) +### 3.7.4 (08/2011) ---------------- -### Features +#### Features - New version of the dual simplex engine (speed is about twice that of 3.6 version) @@ -1528,10 +1806,10 @@ V3.7.4 (08/2011) -V3.6.4 (04/2011) +### 3.6.4 (04/2011) ---------------- -### Features +#### Features - The "scenario builder" is now available. With this builder it is possible to define precisely the simulation context (for any given year, random numbers drawn for each @@ -1542,10 +1820,10 @@ V3.6.4 (04/2011) -V3.5.3 (03/2011) +### 3.5.3 (03/2011) ---------------- -### Features +#### Features - Addition of the fuel category "lignite" to the regular options available for the description of thermal plants. @@ -1561,10 +1839,10 @@ V3.5.3 (03/2011) -V3.4.4 (02/2011) +### 3.4.4 (02/2011) ---------------- -### Features +#### Features - The names of nodes, thermal clusters and binding constraints can be extended to 128 characters. Authorized characters are : `a-z, A-Z,0-9,-,_, space` @@ -1572,10 +1850,10 @@ V3.4.4 (02/2011) -v3.4.3 (10/2010) +### 3.4.3 (10/2010) ---------------- -### Features +#### Features - Two calculations modes are now available (in the "run" window): @@ -1604,10 +1882,10 @@ v3.4.3 (10/2010) -v3.3.2 (07/2010) +### 3.3.2 (07/2010) ---------------- -### Features +#### Features - Improvement of the wind power time-series generator (faster calculations) @@ -1631,10 +1909,10 @@ v3.3.2 (07/2010) -v3.1.0 (01/2010) +### 3.1.0 (01/2010) ---------------- -### Features +#### Features - Breakdown of monthly hydro storage energy credits in daily credits: The pilot curve is now the net load (i.e. load - all must-run generation) @@ -1648,7 +1926,7 @@ v3.1.0 (01/2010) -From V1 to V2 (all versions) +### From V1 to V2 (all versions) ---------------------------- - Refer to project development archives (TRAC thread) diff --git a/docs/developer-guide/continuous-integration.md b/docs/developer-guide/continuous-integration.md new file mode 100644 index 0000000000..6414c531a6 --- /dev/null +++ b/docs/developer-guide/continuous-integration.md @@ -0,0 +1,54 @@ +# Continuous Integration +*ANTARES SIMULATOR*'s compilation is fully tested on GitHub CI. + +Here is a description of workflows with their associated status. + +## Build & release workflows + +| OS | .yml | Description | Status | +|:-----------------|-----------------------|-----------------------------------------------------------------------------------------|------------------------------------------------------| +| Ubuntu | `ubuntu.yml` | Builds Antares Simulator | [![Status][ubuntu_ci_svg]][ubuntu_ci_link] | +| Windows | `windows-vcpkg.yml` | Builds Antares Simulator | [![Status][windows_ci_svg]][windows_ci_link] | +| Centos7 | `centos7.yml` | Builds Antares Simulator | [![Status][centos_ci_svg]][centos_ci_link] | +| OracleLinux8 | `oracle8.yml` | Builds Antares Simulator | [![Status][oraclelinux_ci_svg]][oraclelinux_ci_link] | +| - | `build-userguide.yml` | Generates PDF user guide from material in `docs/user-guide` (uses Sphinx) | [![Status][userguide_svg]][userguide_link] | +| All of the above | `new_release.yml` | When a release is created, runs the aforementioned workflows and publishes their assets | [![Status][new_release_svg]][new_release_link] | + +## Additional workflows + +| .yml | Description | Status | +|:--------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------|----------------------------------------------| +| `sonarcloud.yml` | Compilation with specific options for sonarcloud analysis | [![Status][sonarcloud_svg]][sonarcloud_link] | +| `branchNameValidation.yml` | This workflow verifies that new branches respect Antares Simulator Team's naming conventions[^1] | | +| `docker.yml` | Builds and pushes ["centos7-basic-requirements" docker image](https://hub.docker.com/r/antaresrte/rte-antares) | | +| `doxygen.yml` | Builds & publishes the [doxygen](https://antaressimulatorteam.github.io/Antares_Simulator/doxygen/) documentation | | +| `download-extract-precompiled-libraries-tgz/action.yml` | Download and extract .tgz precompiled libraries from antares-deps repository | | +| `download-extract-precompiled-libraries-zip/action.yml` | Download and extract .zip precompiled libraries from antares-deps repository | | +| `install-cmake-328/action.yml` | Installs cmake 3.28 using devtoolset 10 | | +| `run-tests/action.yml` | Runs tests on the simulator using reference study batches [here](https://github.com/AntaresSimulatorTeam/SimTest) | | + +[^1]: all branch names must start with `feature/`, `features/`, `fix/`, `release/`, `doc/`, `issue-`, or `dependabot/`; otherwise the workflows are not run + +[ubuntu_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(push%20and/or%20release)/badge.svg +[ubuntu_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(push%20and/or%20release)" + +[windows_ci_only_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(pre-compiled%20only)/badge.svg +[windows_ci_only_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(pre-compiled%20only)" + +[windows_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg +[windows_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" + +[centos_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(push%20and/or%20release)/badge.svg +[centos_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(push%20and/or%20release)" + +[oraclelinux_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Oracle%208%20CI%20(push%20and/or%20release)/badge.svg +[oraclelinux_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Oracle%208%20CI%20(push%20and/or%20release)" + +[sonarcloud_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/SonarCloud/badge.svg +[sonarcloud_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"SonarCloud" + +[userguide_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Build%20Userguide%20pdf/badge.svg +[userguide_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Build%20Userguide%20pdf" + +[new_release_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Create%20new%20release/badge.svg +[new_release_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Create%20new%20release" diff --git a/docs/developer-guide/ortools-integration.md b/docs/developer-guide/ortools-integration.md new file mode 100644 index 0000000000..4c0b4b8d8d --- /dev/null +++ b/docs/developer-guide/ortools-integration.md @@ -0,0 +1,71 @@ +# OR-Tools integration + +[OR-Tools](https://developers.google.com/optimization) is an open-source software suite for optimization developed by Google. +It is compatible with most of existing open-source & commercial solvers. +*Antares Simulator* uses OR-Tools as an interface, in order to ensure its own compatibility with multiple solvers. + +## Available solvers + +These are the solver names and enum, defined in the [OR-Tools API](https://github.com/google/or-tools/blob/stable/ortools/linear_solver/linear_solver.cc). + +### Linear optimization + +| OR-Tools solver name | Enum | Usage | Website | +|:---------------------|---------------------------|-------------|--------------------------------------------------------------------------------------------------------------------| +| `clp` | CLP_LINEAR_PROGRAMMING | Free-to-use | [https://github.com/coin-or/Clp](https://github.com/coin-or/Clp) | +| `glpk_lp` | GLPK_LINEAR_PROGRAMMING | Free-to-use | [https://www.gnu.org/software/glpk](https://www.gnu.org/software/glpk) | +| `glop` | GLOP_LINEAR_PROGRAMMING | Free-to-use | [https://developers.google.com/optimization/lp/glop](https://developers.google.com/optimization/lp/glop) | +| `highs_lp` | HIGHS_LINEAR_PROGRAMMING | Free-to-use | [https://highs.dev](https://highs.dev) | +| `pdlp` | PDLP_LINEAR_PROGRAMMING | Free-to-use | [https://developers.google.com/optimization/lp/pdlp_math](https://developers.google.com/optimization/lp/pdlp_math) | +| `sirius_lp` [^1] | SIRIUS_LINEAR_PROGRAMMING | Free-to-use | [https://github.com/rte-france/sirius-solver](https://github.com/rte-france/sirius-solver) | +| `gurobi_lp` | GUROBI_LINEAR_PROGRAMMING | Commercial | [https://www.gurobi.com](https://www.gurobi.com) | +| `cplex_lp` | CPLEX_LINEAR_PROGRAMMING | Commercial | [https://www.ibm.com/fr-fr/analytics/cplex-optimizer](https://www.ibm.com/fr-fr/analytics/cplex-optimizer) | +| `xpress_lp` | XPRESS_LINEAR_PROGRAMMING | Commercial | [https://www.fico.com/en/products/fico-xpress-solver](https://www.fico.com/en/products/fico-xpress-solver) | + +[^1]: SIRIUS solver is only supported in [RTE's builds](https://github.com/rte-france/or-tools-rte/releases) of OR-Tools. + +### Mixed real integer optimization + +| OR-Tools solver name | Enum | Usage | Website | +|:---------------------|----------------------------------|-------------|------------------------------------------------------------------------------------------------------------| +| `scip` | SCIP_MIXED_INTEGER_PROGRAMMING | Free-to-use | [https://www.scipopt.org](https://www.scipopt.org) | +| `glpk` | GLPK_MIXED_INTEGER_PROGRAMMING | Free-to-use | [https://www.gnu.org/software/glpk](https://www.gnu.org/software/glpk) | +| `cbc` | CBC_MIXED_INTEGER_PROGRAMMING | Free-to-use | [https://github.com/coin-or/Cbc](https://github.com/coin-or/Cbc) | +| `highs` | HIGHS_MIXED_INTEGER_PROGRAMMING | Free-to-use | [https://highs.dev](https://highs.dev) | +| `gurobi` | GUROBI_MIXED_INTEGER_PROGRAMMING | Commercial | [https://www.gurobi.com](https://www.gurobi.com) | +| `cplex` | CPLEX_MIXED_INTEGER_PROGRAMMING | Commercial | [https://www.ibm.com/fr-fr/analytics/cplex-optimizer](https://www.ibm.com/fr-fr/analytics/cplex-optimizer) | +| `xpress` | XPRESS_MIXED_INTEGER_PROGRAMMING | Commercial | [https://www.fico.com/en/products/fico-xpress-solver](https://www.fico.com/en/products/fico-xpress-solver) | + +### Constraint optimization + +| OR-Tools solver name | Enum | Usage | Optimization type | +|:---------------------|------------------------------------|-------------|-------------------| +| `bop` | BOP_INTEGER_PROGRAMMING | Free-to-use | Boolean | +| `sat` | SAT_INTEGER_PROGRAMMING | Free-to-use | Boolean integer | +| `knapsack` | KNAPSACK_MIXED_INTEGER_PROGRAMMING | Free-to-use | | + +## Integration in Antares Simulator + +*Antares Simulator* needs 2 types of solvers: + +* A linear solver +* A mixed real integer solver + +While the OR-Tools interface allows using multiple solvers, Antares restricts this usage. +The *Antares Simulator* user can select the solvers using the `ortools-solver` command-line option. Here are the allowed +values: + +| `ortools-solver` | Linear solver | Mixed real integer solver | +|:-------------------|--------------------------------|----------------------------------| +| `sirius` (default) | SIRIUS_LINEAR_PROGRAMMING | SIRIUS_MIXED_INTEGER_PROGRAMMING | +| `coin` | CLP_LINEAR_PROGRAMMING | CBC_MIXED_INTEGER_PROGRAMMING | +| `xpress` | XPRESS_LINEAR_PROGRAMMING | XPRESS_MIXED_INTEGER_PROGRAMMING | +| `glpk` | GLPK_LINEAR_PROGRAMMING | GLPK_MIXED_INTEGER_PROGRAMMING | +| `scip` | SCIP_MIXED_INTEGER_PROGRAMMING | SCIP_MIXED_INTEGER_PROGRAMMING | + +The following commercial solvers are not yet supported by *Antares Simulator*, because of unmet pre-requisites: + +| `ortools-solver` | Linear solver | Mixed real integer | Waiting for | +|:-----------------|---------------------------|----------------------------------|-----------------------------------------------------| +| `cplex` | CPLEX_LINEAR_PROGRAMMING | CPLEX_MIXED_INTEGER_PROGRAMMING | Update OR-Tools building process for CPLEX support | +| `gurobi` | GUROBI_LINEAR_PROGRAMMING | GUROBI_MIXED_INTEGER_PROGRAMMING | Update OR-Tools building process for GUROBI support | diff --git a/docs/index.md b/docs/index.md index be2a04c3a6..19cce2d41e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,40 +1,63 @@ -[![Status][ubuntu_precompiled_svg]][ubuntu_precompiled_link] [![Status][windows_precompiled_svg]][windows_precompiled_link] [![Status][centos_precompiled_svg]][centos_precompiled_link] [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=AntaresSimulatorTeam_Antares_Simulator&metric=alert_status)](https://sonarcloud.io/dashboard?id=AntaresSimulatorTeam_Antares_Simulator) +--- +hide: + - toc +--- -[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) + + +![antares logo](assets/antares.png){ .add-padding-and-white-bg } -![C++](https://img.shields.io/badge/c++-%2300599C.svg?style=for-the-badge&logo=c%2B%2B&logoColor=white) -![antares logo](assets/antares.png) +[![Status][ubuntu_ci_svg]][ubuntu_ci_link] +[![Status][windows_ci_svg]][windows_ci_link] +[![Status][centos_ci_svg]][centos_ci_link] +[![Status][oraclelinux_ci_svg]][oraclelinux_ci_link] +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=AntaresSimulatorTeam_Antares_Simulator&metric=alert_status)](https://sonarcloud.io/dashboard?id=AntaresSimulatorTeam_Antares_Simulator) +[![License: MPL v2](https://img.shields.io/badge/License-MPLv2-blue.svg)](https://www.mozilla.org/en-US/MPL/2.0/) +![C++](https://img.shields.io/badge/c++-%2300599C.svg?style=for-the-badge&logo=c%2B%2B&logoColor=white) -Antares Simulator is an open source power system simulator meant to be -used by anybody placing value in quantifying the adequacy or the -economic performance of interconnected power systems, at short or +Antares Simulator is an open-source power system simulator. +It is meant to be used by anybody placing value in quantifying the adequacy, or the +economic performance, of interconnected power systems, at short or remote time horizons: -Transmission system Operators, Power Producers, Regulators, Academics, -Consultants, NGO and all others actors concerned by energy policy issues +Transmission system operators, power producers, regulators, academics, +consultants, NGOs and all others actors concerned by energy policy issues are welcome to use the software. The Antares Simulator project was initiated by RTE (French Electricity -Transmission system Operator) in 2007. It was developed from the start -as a cross-platform application (Windows, GNU/Linux ,Unix). +Transmission system Operator) in 2007. It has been developed since the beginning +as a cross-platform application (Windows, GNU/Linux, Unix). + +Until 2018, it had been distributed under the terms of a proprietary license. + +In May 2018, RTE decided to release the project under the GPLv3 license. -Until 2018 it was distributed under the terms of a proprietary license. +In January 2024, RTE, as the exclusive copyright owner, decided to switch from the GPLv3 to the MPLv2 license, +starting with the 9.0 version of Antares Simulator. -In May 2018 RTE decided to release the project under the GPLv3 license. +The GUI is deprecated in favor of [Antares Web](https://antares-web.readthedocs.io). -# Links: +### Links +- Antares ecosystem: [https://antares-doc.readthedocs.io](https://antares-doc.readthedocs.io) +- Antares website: [https://antares-simulator.org](https://antares-simulator.org) +- RTE website: [http://www.rte-france.com/](http://www.rte-france.com/) -- Antares web site : https://antares-simulator.org -- RTE web site : http://www.rte-france.com/ +[ubuntu_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(push%20and/or%20release)/badge.svg +[ubuntu_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(push%20and/or%20release)" -[ubuntu_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Ubuntu%20CI%20(pre-compiled)/badge.svg -[ubuntu_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Ubuntu%20CI%20(pre-compiled)" +[windows_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg +[windows_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" -[windows_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Windows%20CI%20(VCPKG%20and%20pre-compiled)/badge.svg -[windows_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Windows%20CI%20(VCPKG%20and%20pre-compiled)" +[centos_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(push%20and/or%20release)/badge.svg +[centos_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(push%20and/or%20release)" -[centos_precompiled_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Centos7%20CI%20(pre-compiled)/badge.svg -[centos_precompiled_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Centos7%20CI%20(pre-compiled)" +[oraclelinux_ci_svg]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/workflows/Oracle%208%20CI%20(push%20and/or%20release)/badge.svg +[oraclelinux_ci_link]: https://github.com/AntaresSimulatorTeam/Antares_Simulator/actions?query=workflow%3A"Oracle%208%20CI%20(push%20and/or%20release)" diff --git a/docs/javascripts/mathjax.js b/docs/javascripts/mathjax.js new file mode 100644 index 0000000000..8b0e1a87ea --- /dev/null +++ b/docs/javascripts/mathjax.js @@ -0,0 +1,6 @@ +MathJax = { + tex: { + inlineMath: [['$', '$'], ['\\(', '\\)']], + }, +}; + diff --git a/docs/overrides/partials/toc-item.html b/docs/overrides/partials/toc-item.html new file mode 100644 index 0000000000..d348052f1f --- /dev/null +++ b/docs/overrides/partials/toc-item.html @@ -0,0 +1,26 @@ + + + +
  • + + + {{ toc_item.title }} + + + + + {% if toc_item.children %} + + {% endif %} +
  • diff --git a/docs/pdf-doc-generation-with-sphinx/create_pdf_doc.sh b/docs/pdf-doc-generation-with-sphinx/create_pdf_doc.sh index 49ad7a10e1..a3f8a51f10 100644 --- a/docs/pdf-doc-generation-with-sphinx/create_pdf_doc.sh +++ b/docs/pdf-doc-generation-with-sphinx/create_pdf_doc.sh @@ -1,11 +1,11 @@ #!/bin/bash # copy reference guide md files and assets -cp -r ../reference-guide source/ +cp -r ../user-guide source/ cp -r ../assets/ source/ # change style for inline latex math \\( -> $ and \\) -> $ -find source/reference-guide/ -type f -name "*.md" -exec sed -i 's=\\\\)=$=g ; s=\\\\(=$=g' {} \; +find source/user-guide/ -type f -name "*.md" -exec sed -i 's=\\\\)=$=g ; s=\\\\(=$=g' {} \; # actually make the pdf sphinx-build -M latexpdf source build mv build/latex/antaressimulatoruserguide.pdf "./${1}" # clean -rm -rf source/reference-guide source/assets build +rm -rf source/user-guide source/assets build diff --git a/docs/pdf-doc-generation-with-sphinx/source/conf.py b/docs/pdf-doc-generation-with-sphinx/source/conf.py index b3ea4429cc..9226aefac1 100644 --- a/docs/pdf-doc-generation-with-sphinx/source/conf.py +++ b/docs/pdf-doc-generation-with-sphinx/source/conf.py @@ -18,8 +18,8 @@ # -- Project information ----------------------------------------------------- project = 'Antares Simulator User Guide' -release = 'v8.6' -copyright = '2023, RTE' +release = 'v9.1' +copyright = '2024, RTE' author = 'RTE' diff --git a/docs/pdf-doc-generation-with-sphinx/source/index.rst b/docs/pdf-doc-generation-with-sphinx/source/index.rst index cbe461bc64..f9409643d7 100644 --- a/docs/pdf-doc-generation-with-sphinx/source/index.rst +++ b/docs/pdf-doc-generation-with-sphinx/source/index.rst @@ -5,4 +5,4 @@ Welcome to Antares Simulator User Guide'! :maxdepth: 2 :caption: Contents - reference-guide/* + user-guide/00-index.md diff --git a/docs/reference-guide/01-introduction.md b/docs/reference-guide/01-introduction.md deleted file mode 100644 index 160ee6694f..0000000000 --- a/docs/reference-guide/01-introduction.md +++ /dev/null @@ -1,99 +0,0 @@ -# Introduction - -This document describes all the main features of the **Antares\_Simulator** package, version 8.6. - -It gives useful general information regarding the way data are handled and processed, -as well as how the Graphic User Interface (GUI) works. To keep this documentation -as compact as possible, many redundant details (how to mouse-select, etc.) are omitted. - -Real-life use of the software involves a learning curve process that cannot be supported by a -simple reference guide. In order to be able to address this basic issue, two kinds of resources may be used: - -- The examples' library, which is meant as a self-teaching way to learn how to use the software. -It is enhanced in parallel to the development of new features. -The content of this library may depend on the type of installation package it comes from -(general public or members of the users' club). - -- The [https://antares-simulator.org](https://antares-simulator.org/) website - -If you notice an issue in the documentation, please report it on [github.com](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/new/choose). - -# General content of Antares\_Simulator sessions - -A typical **Antares\_Simulator** [^1] session involves different steps that are usually run in sequence, -either automatically or with some degree of man-in-the-loop control, depending on the kind of study to perform. - -These steps most often involve: - -1. GUI session dedicated to the initialization or to the updating of various input data sections -(time-series of many kinds, grid topology, generating fleet description, etc.) - -2. GUI session dedicated to the definition of simulation contexts -(definition of the number and consistency of the "Monte-Carlo years" to simulate) - -3. Simulation session producing actual numeric scenarios following the directives defined in (2) - -4. Optimization session aiming at solving all the optimization problems associated with -each of the scenarios produced in (3) - -5. GUI session dedicated to the exploitation of the detailed results yielded by (4) - -The scope of this document is to give a detailed description of the software involved in -step (1) to (5) mostly based on a functional approach, leaving thereby aside a significant -part of the mathematical content involved in several of these steps. -[^2] The following picture gives a functional view of all that is involved in steps (1) to (5). - -![Antares_Process](Antares_Process.png) - -The number and the size of the individual problems to solve (typically, a least-cost hydro-thermal power schedule and -unit commitment, with an hourly resolution and throughout a week, over a large interconnected system) make -optimization sessions often computer-intensive. - -Depending on user-defined results accuracy requirements, various practical options allow to simplify either -the formulation of the problems or their resolution. - -In terms of power studies, the different fields of application Antares has been designed for are the following: - -- **Generation adequacy problems:** -- **Transmission project profitability:** - -The common rationale of the modeling used in all of these studies is, whenever it is possible, -to decompose the general issue (representation of the system behavior throughout many years, -with a time step of one hour) into a series of standardized smaller problems. - -In Antares, the "elementary" optimization problem resulting from this approach is that of the minimization of -the overall system operation cost over a week, taking into account all proportional and -non-proportional generation costs, as well as transmission charges and "external" costs such as -that of the unsupplied energy (generation shortage) or, conversely, that of the spilled energy (generation excess). -In this light, carrying out generation adequacy studies or transmission projects studies means formulating and -solving a series of a great many week-long operation problems (one for each week of each Monte-Carlo year), -assumed to be independent to some extent (note that, however, issues such as the management of hydro resources –or -possibly other kinds of energy storage facilities– may bring a significant coupling between the successive problems, -which needs to be addressed properly). - -### Generation adequacy problems -Adequacy problems aim to study the need for new generating plants to keep the security of -supply above a given critical threshold. - -What is most important in these studies is to survey a great number of scenarios that represent well enough -the random factors that may affect the balance between load and generation. Economic parameters do not play -as much a critical role as they do in the other kinds of studies since the stakes are mainly to know if and -when supply security is likely to be jeopardized (detailed costs incurred in more ordinary conditions are of -comparatively lower importance). In these studies, the default Antares option to use is the "Adequacy" -simulation mode. - -### Transmission project profitability -Transmission project profitability studies the savings brought by a specific reinforcement of the grid, -in terms of decrease of the overall system generation cost (using an assumption of fair and perfect market) and/or -improvement of the security of supply (reduction of the loss-of-load expectation). - -In these studies, economic parameters and the physical modeling of the dynamic constraints bearing on -the generating units are of paramount importance. Though a thorough survey of many "Monte-Carlo years" -is still required, the number of scenarios to simulate is not as large as in generation adequacy studies. -In these studies, the default Antares option to use is the "Economy" simulation mode. - - - -[^1]: For simplicity's sake, the _**Antares\_Simulator**_ 8.6 application will as of now be simply denoted "Antares". - -[^2]: A detailed expression of the basic mathematical problem solved in the red box of the following figure can be found in the document "Optimization problems formulation". diff --git a/docs/reference-guide/02-data_organization.md b/docs/reference-guide/02-data_organization.md deleted file mode 100644 index b5be3e71e9..0000000000 --- a/docs/reference-guide/02-data_organization.md +++ /dev/null @@ -1,69 +0,0 @@ -# Data organization - -In Antares, all input and output data regarding a given study are located within a folder named after the study -and which should preferably be stored within a dedicated library of studies -(for instance: `C/.../A_name_for_an_Antares_lib/Study-number-one`). - -The software has been designed so that all input data may be handled (initialized, updated, deleted) through -the simulator's GUI. Likewise, all results in the output data can be displayed and analyzed within the simulator: -its standard GUI is actually meant to be able to provide, on a stand-alone basis, all the features required to access -input and output in a user-friendly way. - -In addition to that, the Antares simulator may come [^3] with or without functional extensions that provide additional -ways to handle input and output data. - -These extensions take the form of companion applications whose documentation is independent of that of the main simulator. -For information regarding these tools (*Antares Data Organizer*, *AntaresViz* R packages, …) please refer to -the specific relevant documents. - -Besides, a point of notice is that most of Antares files belong to either ".txt" or ".csv" type: -as an alternative to the standard GUI, they can therefore be viewed and updated by many applications -(Windows Notepad, Excel, etc.). However, this is not recommended since handling data this way may result in fatal -data corruption (e.g. as a consequence of accidental insertion of special characters). - -Direct access to input or output data files should therefore be reserved to experienced users. - -The input data contained in the study folder describe the whole state of development of the interconnected power system -(namely: grid, load and generating plants of every kind) for a given future year. - -As already stated, all of these data may be reviewed, updated, deleted through the GUI, whose commands and windows -are described in Sections 3 and 4. - -Once the input data is ready for calculation purposes, an Antares session may start and involve any or all of -the following steps: historical time-series analysis, stochastic times-series generation, -(full) adequacy simulation and economic simulation. - -The results of the session are stored within the output section of the study folder. -The results obtained in the different sessions are stored side by side and tagged. -The identification tag has two components: a user-defined session name and the time at which the session was launched. - -Particular cases are: - -1. The outputs of the Antares time-series analyzer are not printed in the general output files but kept within -the input files structure (the reason being that they are input data for the Antares time - series generators). -The associated data may nonetheless be accessed to be reviewed, updated and deleted at any time through the GUI. - -2. Some specific input data may be located outside the study folder: this is the case for the historical times-series -to be processed by the time-series analyzer, which may be stored either within the "user" subfolder of the -study or anywhere else (for instance, on a remote "historical data" or "Meteorological data" server). - -3. The study folder contains a specific subfolder named "user", whose status is particular: Antares is not allowed -to delete any files within it (yet files may be updated on the user's requirement). As a consequence, -the "user" subfolder is unaffected by the "clean study" command (see [Commands](03-commands.md)). -This subfolder is therefore a -"private" user space, where all kinds of information can be stored without any kind of interference with Antares. -Note that on using the "save as" command (described further below), the choice is given to make or not a copy of -this subfolder. - -4. The times-series analyzer requires the use of a temporary directory in which intermediate files are created -in the course of the analysis and deleted in the end, unless the user wishes to keep them for further examination. -Its location is user-defined and should usually be the "user" subfolder if files are to be kept, otherwise any -proper temporary space such as `C..../Temp`. - -5. The outputs of the Antares Kirchhoff's constraints generator are not printed in the general output files -but kept within the input files structure, the reason being that they are input data for the proper Antares simulation. -The associated data (so-called binding constraints bearing in their name the prefix "@UTO-") may nonetheless -be accessed to be reviewed, updated and deleted at any time through the GUI. - - -[^3]: Many various graphic extensions (under the form of programs written in the R language) are available at: [https://cran.r-project.org/web/packages/antaresViz/index.html](https://cran.r-project.org/web/packages/antaresViz/index.html) diff --git a/docs/reference-guide/03-commands.md b/docs/reference-guide/03-commands.md deleted file mode 100644 index f5fb8cc779..0000000000 --- a/docs/reference-guide/03-commands.md +++ /dev/null @@ -1,292 +0,0 @@ -# Commands - -The Antares GUI gives access to a general menu of commands whose name and meanings are described hereafter. - -## File - -- **New** Create a new empty study to be defined entirely from scratch (network topology, interconnections -ratings, thermal power plants list, fuel costs, hydro inflows stats, wind speed stats, load profiles ,etc.) - -- **Open** Load in memory data located in a specified Antares study folder. Once loaded, these data may be reviewed, -updated, deleted, and simulations may be performed. If "open" is performed while a study was already opened, the former study will be automatically closed. - -- **Quick Open** Same action as open, with a direct access to the recently opened studies - -- **Save** Save the current state of the study, if necessary by replacing original files by updated ones. -After using this command the original study is no longer available, though some original files may be kept until -the "clean" command is used (see "clean" command ) - -- **Save as** Save the current state of the study under a different name and / or location. -Using this command does not affect the original study. When "saving as", the user may choose whether -he/she prefers to save input and output data or only input data. Note that Antares does not perform "autosave": -Therefore, the actions performed on the input data during an Antares session (adding an interconnection, -removing a plant, etc.) will have no effect until either "save" or "save as" have been used - -- **Export Map** Save a picture of the current map as a PNG, JPEG or SVG file. Default background color and -storage location can be changed - -- **Open in Windows Explorer** Open the folder containing the study in a standard Windows Explorer window - -- **Clean** Remove all junk files that may remain in the study folder if the Antares session has involved lots -of sequences such as "create area – add plant –save –rename area – save - rename plant ..." -(Antares performs only low level auto-clean for the sake of GUI's efficiency) - -- **Close** Close the study folder. If no "save" or "save as" commands have been performed, -all the modifications made on the input data during the Antares session will be ignored - -- **Quit** Exit from Antares - -## Edit - -- **Copy** Prepare a copy of elements selected on the current system map. -The command is available only if the current active tab (whose name appears at the top line of the subcommand menu) -is actually that of the System maps. - -- **Paste** Paste elements previously prepared for copy. The command is available only if the current -active tab (whose name appears at the top line of the subcommand menu) is actually that of the System maps. -Note that copy/paste may be performed either within the same map or between two different maps, attached to -the same study or to different studies. To achieve that, launch one instance of Antares to open the "origin" study, -select elements on the map and perform copy, launch another instance of Antares to open the destination study, -perform paste. Copied elements are stored in an Antares clipboard that remains available for subsequent (multiple) -paste as long as the system map is used as active window. - -- **Paste Special** Same as Paste, with a comprehensive set of parameterized actions (skip, merge, update, import) -that can be defined for each data cluster copied in the clipboard. This gives a high level of flexibility for -carrying out complex copy/paste actions. - -- **Reverse** The elements currently selected on the system map are no longer selected and are replaced by -those not selected beforehand. - -- **Unselect All** Unselect all elements currently selected on the system map. - -- **Select All** Select all elements on the system map. - -## Input - -- **Name of the study** Give a reference name to the study. The default name is identical to that of -the study's folder but the user may modify it. The default name of a new study is "no title" - -- **Author(s)** Set the study's author(s) name. Default value is "memory" - -The other "input" subcommands here below are used to move from one active window to another. -Note that the availability of the __Wind__, __Solar__, and __Renewable__ subcommands depend on the advanced -parameter *"Renewable Generation modeling"* described in [miscellaneous](08-miscellaneous.md). - -- **System Maps** -- **Simulation** -- **User's Notes** -- **Load** -- **Solar** -- **Wind** -- **Renewable** -- **Hydro** -- **Thermal** -- **Misc. Gen.** -- **Reserves/DSM** -- **Links** -- **Binding constraints** -- **Economic opt.** - -## Output - -**\\** - -For each simulation run for which results have been generated, open a GUI for displaying results. -Results may be viewed by multiple selections made on a number of parameters. Note that, since all simulations do -not include all kinds of results (depending on user's choices), some parameters are not always visible. -Parameters stand as follows: - -- Antares area (node) -- Antares interconnection (link) -- Class of Monte-Carlo results : - - Monte-Carlo synthesis (throughout all years simulated) - - Year-by-Year (detailed results for one specific year) -- Category of Monte-Carlo results : - - General values (operating cost, generation breakdown, ...) - - Thermal plants (detailed thermal generation breakdown) - - Renewable generation (per cluster) - - Record years (for each Antares variable, identification of the Monte-Carlo year for which lowest and highest values were encountered) - -- Span of Monte-Carlo results : - - _Hourly_ - - _Daily_ - - _Weekly_ - - _Monthly_ - - _Annual_ - -The interface provides a user-friendly way for the comparison of results between multiple simulations -(e.g. "before" and "after" commissioning of a new plant or interconnection): - -- Use "new tab" button and choose a first set of simulation results -- Use again "new tab" and choose a second set of simulation results - -The results window will be automatically split so as to show the two series of results in parallel. -To the right of the "new tab" button, a symbolic (icon) button gives further means to compare results on a -split window (average, differences, minimum, maximum and sum). - -Besides, when the simulation results contain the "year-by-year" class, it is possible to carry out an -extraction query on any given specific variable (e.g. "monthly amounts of CO2 tons emitted") throughout -all available years of simulation. - -The results of such queries are automatically stored within the output file structures, so as to -be available at very short notice if they have to be examined later in another session (extractions may require -a significant computer time when there are many Monte-Carlo years to process). - -- **Open in Windows Explorer** This command displays the list of available simulation results and allows -browsing through the output files structure. The content of these files may be reviewed by tools such as Excel. -File structures are detailed in [Output Files](05-output_files.md). - -## Run - -- **Monte Carlo Simulation** Runs either an economy simulation or an adequacy simulation -depending on the values of the parameters set in the "simulation" active window (see [Simulation window](04-active_windows.md#simulation)). -If hardware resources and simulation settings allow it, simulations benefit from full multi-threading -(see [System requirements](09-system_requirements.md)) - -- **Time-series Generators** Runs any or all of the Antares stochastic time-series generators, -depending on the values of the parameters set in the "simulation" active window (see [Simulation window](04-active_windows.md#simulation)), and -each cluster's "Generate TS" parameter (see [Thermal window](04-active_windows.md#thermal)) - -- **Time-series Analyzer** Runs the Antares historical time-series analyzer. -The parameters of this module are defined by a specific active window, available only on launching the analyzer -(see [Time-series analysis and generation](06-time_series_analysis_and_generation.md)) - -- **Kirchhoff's Constraints Generator** Runs the Antares Kirchhoff's Constraints Generator. -The parameters of this module are defined by a specific active window, available only on launching the KCG -(see [Kirchhoff Constraints Generator](07-kirchhoffs_constraint_generator.md)) - -## Configure - -- **Thematic Trimming** Opens a window in which a choice can be made regarding the individual output status of -the variables defined in [Output Files](05-output_files.md). Each computed variable can either be stored as part of -the Output data to produce at the end of the simulation, or trimmed from it. In the latter case, the variable is regularly computed but the printing stage is skipped. Thematic Trimming does not reduce computation time but can bring some benefits on total runtime (smaller files to write). Thematic Trimming can save large amounts of storage space in simulations where only a handful of variables are of interest. - -- **Geographic Trimming** Opens an auxiliary window that allows multiple selection of the results to store at -the end of a simulation: Choice of areas, interconnections, temporal aggregations (hourly, daily, etc.). -Note that in addition to this feature, alternative access to the function is available -(see [Active windows](04-active_windows.md), "output profile"). Geographic Trimming does not reduce actual computation -time but can bring some benefits on total runtime (fewer files to write). Geographic Trimming can save large -amounts of storage space in simulations where only a few Areas and Links are of interest. - -- **Regional Districts** Allows selecting a set of areas to bundle them together in a "district". -These are used in the course of simulations to aggregate results over several areas. -They can be given almost any name (a "@" prefix is automatically added by Antares). -Bypassing the GUI is possible (see [Miscellaneous](08-miscellaneous.md)). - -- **MC Scenario builder** For each Monte-Carlo year of the simulation defined in the "Simulation" window, -this command allows to state, for each kind of time-series, whether it should be randomly drawn from -the available set (be it ready-made or Antares-generated) _**OR**_ should take a user-defined value -(in the former case, the default "rand" value should be kept; in the latter, the value should be the reference number of the time-series to use). Multiple simulation profiles can be defined and archived. The default active profile gives the "rand" status for all time-series in all areas (full probabilistic simulation). - - Regarding Hydro time-series, the scenario builder gives, in addition to the assignment of a specific number to use for the inflows time-series, the ability to define the initial reservoir level to use for each MC year. - -- **MC Scenario playlist** For each Monte-Carlo year of the simulation defined in the "Simulation" active window, -this command allows to state whether a MC year prepared for the simulation should be actually simulated or not. -This feature allows, for instance, to refine a previous simulation by excluding a small number of "raw" MC years -whose detailed analysis may have shown that they were not physically realistic. A different typical use consists -in replaying only a small number of years of specific interest (for instance, years in the course of which Min or Max -values of a given variable were encountered in a previous simulation). - - In addition, each MC year i=1, …, N can be given a relative “weight†\\(W_i\\) in the simulation (default value: 1). The expectation and standard deviation of all random variables will then be computed as if the scenarios simulated were sampled from a probability density function in which MC year i is given the probability - - $$\frac{W_{i}}{\sum_{j=1,...,N}{W_{j}}}$$ - -- **Optimization preferences** Defines a set of options related to the optimization core used in the simulations. -The set of preferences is study-specific; it can be changed at any time and saved along with study data. -Options refer to objects (binding constraints, etc.) that are presented in subsequent sections of this document. -The values set in this menu overlay the local parameters but do not change their value: for instance, if the LOCAL -parameter "set to infinite" is activated for some interconnections, and if the GLOBAL preference regarding transmission -capacities is "set to null", the simulation will be carried out as if there were no longer any grid BUT the local -values will remain untouched. If the preference is afterwards set to "local values", the interconnections will be -given back their regular capacities (infinite for those being set on "set to infinite"). - - - _Binding constraints (include / ignore)_ - - _Hurdle costs (include / ignore)_ - - _Transmission capacities (local values / set to null / set to infinite)_ - - _Min Up/down time of thermal plants (include / ignore)_ - - _Day-ahead reserve (include / ignore)_ - - _Primary reserve (include / ignore)_ - - _Strategic reserve (include / ignore)_ - - _Spinning reserve (include / ignore)_ - - _Export mps (false/true)_ - - _Simplex optimization range [^4] (day / week)_ - - _Unfeasible problems behavior (Error Dry/ Error Verbose/ Warning Dry/ Warning Verbose_ - -- **Adequacy Patch** Auxiliary window [Options] Defines a set of options related to the adequacy patch. -The set of preferences is study-specific; it can be changed at any time and saved along with study data. -Auxiliary window [Areas] Opens a window in which a choice can be made regarding the individual area adequacy patch mode. - -- _Enable Adequacy patch (false / true)_ -- _NTC from physical areas outside to physical areas inside adequacy patch (set to null / local values)_ -- _NTC between physical areas outside adequacy patch (set to null / local values)_ -- _Price taking order (DENS / Load)_ -- _Include hurdle cost in CSR optimization (false / true)_ -- _Check CSR cost function value prior and after CSR (false / true)_ -- _Thresholds:_ - - _Initiate curtailment sharing rule_ - - _Display local maching rule violations_ - - _Relax CSR variable boundaries_ - -- **Advanced parameters** Advanced Parameters allow to adjust the simulation behavior regarding issues -that are more numerical than physical. The set of parameters is study-specific and can be updated at any time. - - - Seeds for random number generation - - Time-series draws (MC scenario builder) - - Wind time-series generation - - Solar time-series generation - - Hydro time - series generation - - Load time - series generation - - Thermal time-series generation - - Noise on thermal plants costs - - Noise on unsupplied energy costs - - Noise on spilled energy costs - - Noise on virtual hydro cost - - Initial hydro reservoir levels - - Spatial time-series correlation - - Numeric Quality : load `[standard | high]` - - Numeric Quality : wind `[standard | high]` - - Numeric Quality : solar `[standard | high]` - - Other preferences - - Reservoir Level Initialization `[cold start | hot start]` - - Hydro Heuristic policy `[accomodate rule curves | maximize generation]` - - Hydro Pricing mode `[fast|accurate]` - - Power fluctuations `[free modulations | minimize excursions | minimize ramping]` - - Shedding policy `[shave peaks | minimize duration]` - - District marginal prices : `[average | weighed]` - - Day-ahead reserve management `[global | local]` - - Unit commitment mode `[fast | accurate]` - - Simulation cores `[minimum | low | medium | high | maximum]` - - Renewable Generation modeling `[aggregated | cluster]` - -## Tools - -- **Study manager** Launches the "study manager" external package (Please refer to dedicated documentation -for this package) - -- **Resources monitor** Indicates the amounts of RAM and disk space currently used and those required for a simulation -in the available modes (see [System requirements](09-system_requirements.md)). -Note that the "disk requirement" amount does not include the footprint of the specific "mps" files that may have -to be written aside from the regular output (see previous § "optimization preferences"). -Besides, the resources monitor shows the number of CPU cores available on the machine Antares is running on. - -- **Configure the temporary folder** Defines the location that will be used by Antares to store the temporary files of -the MC simulators. This location is used behind the scene by some Antares Simulator components (for instance scenario -builder or time-series analyzer). The default setting is the system temporary folder. - -## Window - -- **Toggle full window** Uses the whole window for display - -- **Inspector** Opens a window that gives general information on the study and allow quick browsing -through various area- or interconnection-related parameters. The Inspector window displays the content of the -Antares clipboard, e.g. areas and interconnections selected on the current study map. If the "Geographic Trimming" -option of the general simulation dashboard has the value "custom", the filtering parameters can be defined within -the Inspector window. Besides, areas currently selected, displayed in the Inspector window, -can be bundled into an "output district" by using the Configure/district command previously described - -- **Log viewer** Displays the log files regarding every Antares session performed on the study - - -[^4]:_Weekly optimization performs a more refined unit commitment, especially when the level selected in the "advanced parameters" menu is "accurate"._ - - diff --git a/docs/reference-guide/04-active_windows.md b/docs/reference-guide/04-active_windows.md deleted file mode 100644 index 8aaa5d523c..0000000000 --- a/docs/reference-guide/04-active_windows.md +++ /dev/null @@ -1,798 +0,0 @@ - -# Active windows - -Data can be reviewed, updated, deleted by selecting different possible active windows whose list and content -are described hereafter. On launching Antares, the default active window is "System Maps". - -## System Maps - -This window is used to define the general structure of the system, i.e. the list of areas and that of the interconnections. Only the area's names, location and the topology of the grid are defined at this stage. Different colors may be assigned to different areas. These colors may later be used as sorting options in most windows. They are useful to edit data in a fashion that has a geographic meaning (which the lexicographic order may not have). This window displays copy/paste/select all icons equivalent to the relevant EDIT menu commands. - -The top left side of the window shows a "mouse status" field with three icons. These icons (one for nodes, one for links and one for binding constraints) indicate whether a selection made on the map with the mouse will involve or not the related elements. When a copy/paste action is considered, this allows for instance to copy any combination of nodes, links and binding constraints. Status can be changed by toggling the icons. Default is "on" for the three icons. Two other purely graphic icons/buttons (no action on data) allow respectively to center the map on a given set of (x , y) coordinates, and to prune the "empty" space around the current map. Multiple additional maps may be defined by using the cross-shaped button located top right. A detailed presentation of all system map editor features can be found in the document "System Map Editor Reference Guide". - -## Simulation - -The main simulation window is divided up in two parts. On the left side are the general parameters while the right side is devoted to the time-series management. - -These two parts are detailed hereafter. - -### LEFT PART: General parameters - -- **Simulation** - - - _Mode:_ Economy, Adequacy [^5] - - _First day:_ First day of the simulation (e.g. 8 for a simulation beginning on the second week of the first - month of the year) - - _Last day:_ Last day of the simulation (e.g. 28 for a simulation ending on the fourth week of the first month - of the year) [^6] - -- **Calendar** - - - _Horizon:_ Reference year (static tag, not used in the calculations) - - - _Year:_ Actual month by which the Time-series begin (Jan to Dec, Oct to Sep, etc.) - - - _Leap Year:_ (Yes/No) indicates whether February has 28 or 29 days - - - _Week:_ In economy or adequacy simulations, indicates the frame (Mon- Sun, Sat-Fri, etc.) to use for - the edition of weekly results - - - _1st January:_ First day of the year (Mon, Tue, etc.) - -- **Monte-Carlo scenarios** - - - _Number:_ Number of MC years that should be prepared for the simulation (not always the same as the - Number of MC years actually simulated, see "selection mode" below) - - - _Building mode_: - - **Automatic** For all years to simulate, all time-series will be drawn at random - - **Custom** The simulation will be carried out on a mix of deterministic and probabilistic conditions, - with some time-series randomly drawn and others set to user-defined values. This option allows setting - up detailed "what if" simulations that may help to understand the phenomena at work and quantify various kinds of risk indicators. To set up the simulation profile, choose in the main menu: Configure/ MC scenario builder - - **Derated** All time-series will be replaced by their general average and the number of MC years - is set to 1. If the TS are ready-made or Antares-generated but are not to be stored in the INPUT folder, - no time-series will be written over the original ones (if any). If the time-series are built by Antares - and if it is specified that they should be stored in the INPUT, a single average-out time series will be stored - instead of the whole set. - - - _Selection mode_: - - **Automatic** All prepared MC years will actually be simulated. - - - **Custom** The years to simulate are defined in a list. To set up this list, choose in the main menu: - Configure/ MC scenario playlist [^7]. - -- **Output profile** - - - Simulation synthesis: - - **True** Synthetic results will be stored in a directory: - `Study_name/OUTPUT/simu_tag/Economy/mc-all` - - **False** No general synthesis will be printed out - - - Year-by-Year: - - **False** No individual results will be printed out - - **True** For each simulated year, detailed results will be printed out in an individual directory: - `Study_name/OUTPUT/simu_tag/Economy/mc-i-number - - - Geographic Trimming: - - **None** Storage of results for all areas, geographic districts, interconnections as well as all time spans - (hourly, daily, etc.) - - **Custom** Storage of the results selected with the "Geographic Trimming" command of the "Configure" - option available in the main menu. - Filters on areas, interconnections and time spans may also be defined as follows: - - On the map, select area(s) and/or interconnection(s) - - Open the inspector module (Main menu, Windows) - - Set adequate parameters in the "output print status" group - - - Thematic Trimming: - - **None** Storage, for the geographic selection defined previously, - of all variables defined in [Output Files](05-output_files.md) for Areas and Links. - - **Custom** Storage, for the geographic selection defined previously, of the variables selected with - the "Thematic Trimming" command of the "Configure" option available in the main menu. - - - MC Scenarios: - - **False** No storage of the time-series numbers (either randomly drawn or user-defined) used to - set up the simulation - - **True** A specific OUTPUT folder will be created to store all the time-series numbers drawn when - - preparing the MC years. - -### RIGHT PART: Time-series management - -For the different kinds of time-series that Antares manages in a non-deterministic way (load, thermal generation, hydro power, wind power, solar power or renewable depending on the option chosen): - -1. **Choice of the kind of time-series to use** -Either « ready-made » or «stochastic » (i.e. Antares-generated), defined by setting the value to either "on" or "off". Note that for Thermal time-series, the cluster-wise parameter may overrule this global parameter (see Thermal window description below). - -2. **For stochastic TS only**: - - **Number** Number of TS to generate - - - **Refresh** (Yes /No) ndicates whether a periodic renewal of TS should be performed or not - - - **Refresh span** Number of MC years at the end of which the renewal will be performed (if so required) - - - **Seasonal correlation** ("monthly" or "annual") Indicates whether the spatial correlation matrices to use are defined month by month or if a single annual matrix for the whole year should rather be used (see [Time-series analysis and generation](06-time_series_analysis_and_generation.md)) - - - **Store in input** - - **Yes** the generated time-series will be stored in the INPUT in replacement of the original ones (wherever they may come from) - - No: the original time-series will be kept as they were - - - **Store in output** - - **Yes**: the generated times-series will be stored as part of the simulation results - - **No**: no storage of the generated time-series in the results directories - -3. **General rules for building up the MC years** - - **Intra-modal**: - - **Yes** For each mode, the same number should be used for all locations (or 1 where there is only one TS), but this number may differ from one mode to another. For instance, solar power TS = 12 for all areas, while wind power TS number = 7 for all areas. - - **No** Independent draws - - **Inter-modal**: - - **Yes** For all modes, the same number should be used but may depend on the location (for instance, solar and wind power TS = 3 for area 1, 8 for area 2, 4 for area 3, etc.) - - **No** Independent draws - -A full meteorological correlation (for each MC year, one single number for all modes and areas) is, from a theoretical standpoint, accessible by activating "intra-modal" and " inter-modal" for all but the "thermal" kind of time-series. The availability of an underlying comprehensive multi-dimensional Meteorological data base of ready-made time-series is the crux of the matter when it comes to using this configuration. - -## User's Notes - -A built-in notepad for recording comments regarding the study. Such comments typically help to track successive input data updates (upgrading such interconnection, removing such plant, etc.). Another simple use is to register what has been stored in the "user" subfolder and why. Such notes may prove useful to sort and interpret the results of multiple simulations carried out at different times on various configurations of the power system. - -## Load - -This window is used to handle all input data regarding load. In Antares load should include transmission losses. It should preferably not include the power absorbed by pumped storage power plants. If it does, the user should neither use the "PSP" array (see window "Misc. Gen") nor the explicit modeling of PSP plants - -The user may pick any area appearing in the list and is then given access to different tabs: - -- The "time-series" tab display the "ready-made" 8760-hour time-series available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on the user's request. Different ways to update data are : - - - direct typing - - - copy/paste a selected field to/from the clipboard - - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values - (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - - Handle the whole (unfiltered) existing dataset to either - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - Versatile "Filter" functions allow quick access to user-specified sections of data -(e.g. display only the load expected in the Wednesdays of January, at 09:00, for time-series #12 to #19). Hourly load is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (size of thermal plants, interconnection capacities, etc.) - - - _Note that:_ - - - _If the "intra-modal correlated draw" option has not been selected in the_ **simulation** _window, - MC adequacy or economy simulations can take place even if the number of time-series is not the same - in all areas (e.g. 2 , 5 , 1 , 45 ,...)_ - - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, - every area should have either one single time-series or the same given number (e.g. 25 , 25 , 1 , 25...)_ - - - The "spatial correlation" tab gives access to the inter-area correlation matrices that will be used - by the stochastic generator if it is activated. Different sub-tabs are available for the definition of 12 monthly - correlation matrices and of an overall annual correlation matrix. - A matrix A must meet three conditions to be a valid correlation matrix: - - $$\forall i,\ \forall j,\ {A_{ii} = 100; -100 \le A_{ij} \le 100}; A\ symmetric; A\ positive\ semi\mbox{-}definite$$ - - When given invalid matrices, the TS generator emits an infeasibility diagnosis - - - The "local data" tab is used to set the parameters of the stochastic generator. - These parameters are presented in four sub-tabs whose content is presented in - [Time-series analysis and generation](06-time_series_analysis_and_generation.md). - - - The "digest" tab displays for all areas a short account of the local data - -## Thermal - -This window is used to handle all input data regarding thermal dispatchable power. - -The user may pick any area appearing in the area list and is then given access to the list of thermal plants -clusters defined for the area (e.g. "CCG 300 MW", "coal 600", etc.). Once a given cluster has been selected, -a choice can be made between different tabs: - -- The "time-series" tab displays the "ready-made" 8760-hour time-series available for simulation purposes. -These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series -stochastic generator, stored as input data on the user's request. Different ways to update data are : - - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a - 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only -the generation expected on Sundays at midnight, for all time-series). - - Hourly thermal generation is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (Wind generation, interconnection capacities, load, hydro generation, solar, etc.) - - - _Note that:_ - - - _If the "intra-modal correlated draws" option has not been selected in the_ **simulation** _window, - MC adequacy or economy simulations can take place even if the number of time-series is not the same in all - areas (e.g. 2, 5, 1, 45,etc.)_ - - - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, - every area should have either one single time-series or the same given number (e.g. 25, 25, 1, 25, etc.). - Note that, unlike the other time-series (load, hydro, etc.), which depend on meteorological conditions and - are therefore inter-area-correlated, the thermal plants time-series should usually be considered as uncorrelated. - Using the "correlated draws" feature makes sense only in the event of having to play predefined scenarios - (outside regular MC scope)_ - - -- The "TS generator" tab is used to set the parameters of the stochastic generator. -These parameters are defined at the daily scale and are namely, for each day: the average duration of -forced outages (beginning on that day), the forced outage rate, the duration of planned outages (beginning on that day), -the planned outage rate, planned outages minimum and maximum numbers. -Durations are expressed in days and rates belong to [0 , 1]. - - -- The "Common" tab is used to define the cluster's techno-economic characteristics : - - - Name - - Fuel used - - Location (Area) - - Activity status - - false: not yet commissioned, moth-balled, etc. - - true : the plant may generate - - Number of units - - Nominal capacity - - Full Must-run status - - false: above a partial "must-run level" (that may exist or not, see infra) plants - will be dispatched on the basis of their market bids. - - true: plants will generate at their maximum capacity, regardless of market conditions - - Minimum stable power (MW) - - Minimum Up time (hours) - - Minimum Down time (hours) - - Default contribution to the spinning reserve (% of nominal capacity) - - CO2 tons emitted per electric MWh - - Fuel efficiency (%) - - Cost generation [Set manually / Use cost timeseries] - - Marginal operating cost (€/MWh) - - Volatility (forced): a parameter between 0 and 1, see section [Time-series generation (thermal)](06-time_series_analysis_and_generation.md#time-series-generation-thermal) - - Volatility (planned): a parameter between 0 and 1, see section [Time-series generation (thermal)](06-time_series_analysis_and_generation.md#time-series-generation-thermal) - - Law (forced): Probabilistic law used for the generation of the forced outage time-series, can be set to either uniform or geometric - - Law (planned): Probabilistic law used for the generation of the planned outage time-series, can be set to either uniform or geometric - - Generate TS: Parameter to specify the behavior of this cluster for TS generation. **This cluster-wise parameter takes priority over the study-wide one.** It can hold three values: - - Force generation: TS for this cluster will be generated - - Force no generation: TS for this cluster will not be generated - - Use global parameter: Will use the parameter for the study (the one in the [Simulation Window](#simulation)). - - Fixed cost (No-Load heat cost) (€ / hour of operation ) - - Start-up cost (€/start-up) - - Market bid (€/MWh) - - Random spread on the market bid (€/MWh) - - Variable Operation&Maintenance cost (€/MWh, only used if **Cost generation** is set to **use cost timeseries**) - - Seasonal marginal cost variations (gas more expensive in winter, ...) - - Seasonal market bid modulations (assets costs charging strategy ) - - Nominal capacity modulations (seasonal thermodynamic efficiencies, special over-generation allowances, etc.). These modulations are taken into account during the generation of available power time-series - - Minimal generation commitment (partial must-run level) set for the cluster - - - _Note that:_ - - - _The **optimal dispatch plan** as well as **locational marginal prices** are based on **market bids**, - while the assessment of the **operating costs** associated with this optimum are based on **cost parameters**. - (In standard "perfect" market modeling, there is no difference of approaches because market - bids are equal to marginal costs)_ - - - _Note that:_ - - - _If `Cost generation` is set to `Set manually` Marginal and Market bid costs (€/MWh) are specified directly in `Common` tab and have the same value for all time-series and hours._ - - _If `Cost generation` is set to `Use cost timeseries` Marginal and Market bid costs (€/MWh) are calculated separately for all the time-series and hours using following equation:_\ - _Marginal_Cost[€/MWh] = Market_Bid_Cost[€/MWh] = (Fuel_Cost[€/GJ] * 3.6 * 100 / Efficiency[%]) + CO2_emission_factor[tons/MWh] * C02_cost[€/tons] + Variable_O&M_cost[€/MWh]_\ - _where Efficiency[%], CO2_emission_factor[tons/MWh] and Variable_O&M_cost[€/MWh] are specified in `Common` tab under operating costs and parameters, while Fuel_Cost[€/GJ] and C02_cost[€/tons] are provided as time-series in separate tabs._ - -## Hydro - -This section of the GUI is meant to handle all input data regarding hydro power, -as well as any other kind of energy storage system of any size (from a small battery to a large -conventional hydro-storage reservoir with or without pumping facilities, etc.): Hydro power being -historically the first and largest form of power storage, it stood to reason that it should play in -Antares the role of a "generic template" for all forms of storable power. This versatility, however, -comes at the price of a comparatively more complex data organization than for other objects, -which explains the comparatively long length of this chapter. - -In the main Window, the user may pick any area appearing in the list and is then given access to different tabs: - -- The "time-series" tab displays the "ready-made" time-series already available for simulation purposes. There are two categories of time-series (displayed in two different subtabs): the Run of River (ROR) time-series on the one hand and the Storage power (SP) time-series on the other hand. - - ROR time-series are defined at the hourly scale; each of the 8760 values represents the ROR power expected at a given hour, expressed in round number and in MW. The SP time-series are defined at the daily scale; each of the 365 values represents an overall SP energy expected in the day, expressed in round number and in MWh. These natural inflows are considered to be storable into a reservoir for later use. - - Both types of data may come from any origin outside Antares, or may have been formerly generated by the Antares time-series stochastic generator and stored as input data on the user's request. Different ways to update data are: - - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values - (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - - _Note that:_ - - - _For a given area, the number of ROR time-series and SP times-series **must** be identical_ - - _If the "intra-modal correlated draws" option was not selected in the_ **simulation** _window, - MC adequacy or economy simulations can take place even if the number of hydro time-series is not the same - in all areas (e.g. 2 , 5 , 1 , 45 ,...)_ - - _If the "intra-modal correlated draws" option was selected in the_ **simulation** _window, every - area should have either one single time-series or the same given number (e.g. 25 , 25 , 1 , 25...)_ - - -- The "spatial correlation" tab gives access to an annual inter-area correlation matrix that will be used by the stochastic generator if it is activated. Correlations are expressed in percentages, hence to be valid this matrix must be symmetric, p.s.d, with a main diagonal of 100s and all terms lying between (-100 ,+100) - - -- The "Allocation" tab gives access to an annual inter-area allocation matrix A(i,j) that may be used during a heuristic hydro pre-allocation process, regardless of whether the stochastic time-series generator is used or not. This matrix describes the weights that are given to the loads of areas (i) in the definition of the monthly and weekly hydro storage generation profiles of areas (j). The way this is done in detailed in [Miscellaneous](08-miscellaneous.md). - - -- The "local data" tab is used to set up the parameters of the stochastic generator_ **AND** _to define techno-economic characteristics of the hydro system that are used in Economy and Adequacy optimizations. For the purpose of versatility (use of the hydro section to model storage facilities quite different in size and nature), this "local tab" is itself divided up into four different subtabs whose list follows and which are further described: - - - Inflow Structure - - Reservoir Levels and water value - - Daily Power and Energy Credits - - Management options - -**Inflow Structure** - -This tab contains all the local parameters used for the stochastic generation of hydro time-series. These are namely: - -- The expectations, standard deviations, minimum and maximum values of monthly energies (expressed in MWh), monthly shares of Run of River within the overall hydro monthly inflow. -- The average correlation between the energy of a month and that of the next month (inter-monthly correlation). -- The average daily pattern of inflows within each month. Each day is given a relative "weight" in the month. If all days are given the same weight, daily energy time-series will be obtained by dividing the monthly energy in equal days. If not, the ratio between two daily energies will be equal to that of the daily weights in the pattern array. - -Overall hydro energy is broken down into two parts: Run of River- ROR and storage -STOR - -ROR energy has to be used on the spot, as it belongs to the general "must-run" energy category. - -STOR energy can be stored for use at a later time. The way how stored energy may actually be used depends -on the options chosen in the "management options" Tab and of the values of the parameters defined in the other Tabs. - -**Reservoir Levels and Water Values** - -Reservoir levels (left side) - -On the left side are defined 365 values for the minimum, average and maximum levels set for the reservoir -at the beginning of each day, expressed in percentage of the overall reservoir volume. The lower and upper level -time-series form a pair of so-called lower and upper "reservoir rule curves" - -Depending on the set of parameters chosen in the "management options" Tab, these rule curves may be used in -different ways in the course of both heuristic seasonal hydro pre-allocation process and subsequent weekly -optimal hydro-thermal unit-commitment and dispatch process. - -Water values (right side) - -On the right side is a table of marginal values for the stored energy, which depends on the date (365 days) and -of the reservoir level (101 round percentage values ranging from 0% to 100%). These values may have different origins; -they theoretically should be obtained by a comprehensive (dual) stochastic dynamic programming study carried out over -the whole dataset and dealing simultaneously with all reservoirs. - -Depending on the set options chosen in the "management options" Tab, these values may be used or not in the course of -the weekly optimal hydro-thermal unit-commitment and dispatch process. - -**Daily Power and Energy Credits** - -Standard credits (Bottom part) - -The bottom part displays two daily time-series (365 values) defined for energy generation/storage -(hydro turbines or hydro pumps). In each case, the first array defines the maximum power (generated or absorbed), -and the second defines the maximum daily energy (either generated or stored). - -For the sake of clarity, maximum daily energies are expressed as a number of hours at maximum power. - -Credit modulation (Upper part) - -The upper part displays two level-dependent (101 round percentage values ranging from 0% to 100%) time-series -of modulation coefficients defined for either generating or storing (pumping). - -These modulations, which can take any positive value, may (depending on the options chosen in the management -options Tab) be used to increase (value >1) or to decrease (value <1) the standard credits defined previously -for the maximum daily power and energies. - -**Management Options** - -This Tab is a general dashboard for the definition of how storage units, whatever their size or nature, should be managed. -It includes 15 parameters (out of which 7 are booleans) presented hereafter: - -- "Follow load" (y|n): defines whether an "ideal" seasonal generation profile should somehow follow the load OR an -"ideal" seasonal generation profile should remain as close as possible to the natural inflows -(i.e. instant generation whenever possible) - -- "Inter-daily breakdown" and "Inter-monthly breakdown" : parameters used in the assessment, through a -heuristic process, of an "ideal" seasonal generation profile, if the use of such a profile is required -(the heuristic itself is presented in [Miscellaneous](08-miscellaneous.md)) - -- "Intra-daily modulation": parameter which represents, for the storage power, the maximum authorized value for -the ratio of the daily peak to the average power generated throughout the day. This parameter is meant to allow -simulating different hydro management strategies. Extreme cases are : 1 : generated power should be constant throughout -the day 24 : use of the whole daily energy in one single hour is allowed - -- "Reservoir management" `y|n`: defines whether the storage should be explicitly modeled or not. - - Choosing "No" implies that available data allow or require that, regardless of the reservoir characteristics: - - - The whole amount of STOR energy of each month MUST be used during this month (no long-term storage) - - - The actual daily generation should follow, during the month, an "ideal" profile defined by the heuristic defined in [Miscellaneous](08-miscellaneous.md) - - Choosing "Yes" implies that available data allow or require explicit modeling of the storage facility, -regardless of whether a pre-allocation heuristic is used or not. - -- "Reservoir capacity": size of the storage facility, in MWh - -- "Initialize reservoir level on the 1st of": date at which the reservoir level should be initialized by a random draw. The "initial level" is assumed to follow a "beta" variable with expectation "average level", upper bound U=max level, lower bound L= min level, standard deviation = (1/3) (U-L) - -- "Use Heuristic Target" (y|n): defines whether an "ideal" seasonal generation profile should be heuristically determined or not. - - Choosing "No" implies that available data allow or require that full confidence should be put in water values determined upstream (through [dual] stochastic dynamic programming) OR that there are no "natural inflows" to the storage facility (battery or PSP, etc.) - - Choosing "Yes" implies that available data allow or require the definition of an "ideal" generation profile, that can be used to complement –or replace– the economic signal given by water values AND that there are "natural inflows" on which a generation heuristic can be based. - -- "Power-to-Level modulations (y|n)": defines whether the standard maximum daily energy and power credit should be or not multiplied by level-dependent modulation coefficients. - -- "Hard bounds on rule curves (y|n)": states whether, beyond the preliminary heuristic stage (if any), lower and upper reservoir rule curves should still be taken into account as constraints in the hydro-thermal unit commitment and dispatch problems. - -- "Use leeway (y|n)", lower bound L, upper bound U: states whether the heuristic hydro ideal target (**HIT**) should be followed exactly or not. - - Choosing "No" implies that, in optimization problems, the hydro energy generated throughout the time interval will be subject to an equality constraint, which may include short-term pumping cycles independent of water value: sum{ 1,t,T} (hydro(t)) – sum{1,t,T} (r. pump(t))= **HIT* - - Choosing "Yes", with bounds L and U, implies that, in optimization problems, the hydro energy generated throughout the time span will be subject to inequality constraints: L_*__HIT__ _<=sum{1,t,T} (hydro(t)) <= U\*_**HIT* - - Independently, short- or long-term pumping may also take place if deemed profitable in the light of water values. - - - "Use Water Value (y|n)": states whether the energy taken from / stored into the reservoir should be given the reference value defined in the ad hoc table OR should be given a zero value. - - - "Pumping Efficiency Ratio": setting the value to r means that, for the purpose of storing 1 gravitational MWh, pumps will have to use (1/r) electrical MWh. - -## Wind - -This window is used to handle all input data regarding Wind power. -This window is only accessible when the advanced parameter Renewable Generation modeling is set to "Aggregated". - -The user may pick any area appearing in the list and is then given access to different tabs: - -- The "time-series" tab display the "ready-made" 8760-hour time-series already available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on user's request. Different ways to update data are : - - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the wind generation expected between 17:00 and 21:00 in February, for time-series 1 to 100). - - Hourly wind generation is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (size of thermal plants, interconnection capacities, load, etc.) - - - _Note that:_ - - - _If the "intra-modal correlated draws" option has not been selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series is not the same in all areas (e.g. 2, 5, 1,45, ...)_ - - - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, every area should have either one single time-series or the same given number (e.g. 25, 25, 1, 25, ...)_ - -- The "spatial correlation" tab gives access to the inter-area correlation matrices that will be used by the stochastic generator if it is activated. Different sub-tabs are available for the definition of 12 monthly correlation matrices and an overall annual correlation matrix. - - A matrix A must meet three conditions to be a valid correlation matrix: - - $$\forall i,\ \forall j,\ {A_{ii} = 100; -100 \le A_{ij} \le 100}; A\ symmetric; A\ positive\ semi\mbox{-}definite$$ - - When given invalid matrices, the TS generator emits an infeasibility diagnosis - -- The "local data" tab is used to set the parameters of the stochastic generator. These parameters are presented in four subtabs whose content is presented in [Time-series analysis and generation](06-time_series_analysis_and_generation.md). - -- The "digest" tab displays for all areas a short account of the local data - - -## Solar - -This window is used to handle all input data regarding Solar power. Both thermal solar generation and PV solar generation are assumed to be bundled in this data section. -_This window is only accessible when the advanced parameter Renewable Generation modeling is set to "aggregatedâ€._ - -The user may pick any area appearing in the list and is then given access to different tabs: - -- The "time-series" tab display the "ready-made" 8760-hour time-series available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on the user's request. Different ways to update data are : - - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the solar power expected in August at noon, for all time-series). - - Hourly solar power is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (size of thermal plants, interconnection capacities, etc.) - - - _Note that:_ - - - _If the "intra-modal correlated draws" option was not selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series is not the same in all areas (e.g. 2 , 5 , 1 , 45 ,...)_ - - - _If the "intra-modal correlated draws" option was selected in the_ **simulation** _window, every area should have either one single time-series or the same given number (e.g. 25 , 25 , 1 , 25...)_ - -- The "spatial correlation" tab gives access to the inter-area correlation matrices that will be used by the stochastic generator if it is activated. Different sub-tabs are available for the definition of 12 monthly correlation matrices and of an overall annual correlation matrix. - - A matrix A must meet three conditions to be a valid correlation matrix: - - $$\forall i,\ \forall j,\ {A_{ii} = 100; -100 \le A_{ij} \le 100}; A\ symmetric; A\ positive\ semi\mbox{-}definite$$ - - When given invalid matrices, the TS generator emits an infeasibility diagnosis - -- The "local data" tab is used to set the parameters of the stochastic generator. These parameters are presented in four subtabs whose content is presented in [Time-series analysis and generation](06-time_series_analysis_and_generation.md). - -- The "digest" tab displays for all areas a short account of the local data - - -## Renewable - -This window is used to handle all input data regarding renewable generation. -_This window is only accessible when the advanced parameter Renewable Generation modeling is set to "cluster†(default value)._ - -The user may pick any area appearing in the area list and is then given access to the list of renewable clusters defined for the area (e.g. "Onshore Wind Farm 200MW", "Solar Rooftop 50MW", etc.). Once a given cluster has been selected, a choice can be made between different tabs: - -- The "time-series" tab displays the "ready-made" 8760-hour time-series available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on the user's request. Different ways to update data are : - - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the generation expected on Sundays at midnight, for all time-series). - - Hourly thermal generation is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (Wind generation, interconnection capacities, load, hydro generation, solar, etc.) - - - _Note that:_ - - - _If the "intra-modal correlated draws" option has not been selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series is not the same in all areas (e.g. 2, 5, 1, 45,etc.)_ - - - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, every area should have either one single time-series or the same given number (e.g. 25, 25, 1, 25, etc.). Note that, unlike the other time-series (load, hydro, etc.), which depend on meteorological conditions and are therefore inter-area-correlated, the thermal plants time-series should usually be considered as uncorrelated. Using the "correlated draws" feature makes sense only in the event of having to play predefined scenarios (outside regular MC scope)_ - - -- The "TS generator" tab is not accessible for this version. - - -- The "Common" tab is used to define the cluster's techno-economic characteristics : - - - Name - - Group: The group can be any one of the following: Wind Onshore, Wind Offshore, Solar Thermal, Solar PV, Solar Rooftop, Other RES 1, Other RES 2, Other RES 3, or Other RES 4. If not specified, the renewable cluster will be part of the group Other RES 1. - - Location (Area) - - Timeseries mode: - - Power generation means that the unit of the timeseries is in MW - - Production factor means that the unit of the timeseries is in p.u. (between 0 and 1, 1 meaning the full installed capacity) - - Activity status - - false: not yet commissioned, moth-balled, etc. - - true: the cluster may generate - - Number of units - - Nominal capacity (in MW per unit) - - -## Misc. Gen. - -This window is used to handle all input data regarding miscellaneous non dispatchable generation. - -On picking any area in the primary list, the user gets direct access to all data regarding the area, which amount to **8** ready-made 8760-hour time-series (expressed in MW): - -- CHP generation - -- Bio Mass generation - -- Bio-gas generation - -- Waste generation - -- Geothermal generation - -- Any other kind of non-dispatchable generation - -- A predefined time-series for the operation of Pumped Storage Power plants, if they are not explicitly modeled. A positive value is considered as an output (generating) to the grid, a negative value is an input (pumping) to the station. - - Note that the sum of the 8760 values must be negative, since the pumping to generating efficiency is lower than 1. The user may also use only the negative values (prescribed pumping), while transferring at the same time the matching generating credit on the regular hydro storage energy credit. - -- ROW balance: the balance with the rest of the world. A negative value is an export to ROW, a positive value is an import from ROW. These values acts as boundary conditions for the model. Different ways to update data are: - - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - -## Reserves / DSM - -This window is used to handle all input data regarding reserves and the potential of "smart" load management (when not modeled using "fake" thermal dispatchable plants). On picking any area in the primary list, the user gets direct access to all data regarding the area, which amount to **four** ready-made 8760-hour time-series (expressed in MW). Those reserves are available in either "adequacy" or "economy" simulations: - -- Day-ahead reserve: power accounted for in setting up the optimal unit-commitment and schedule of the following day(s), which must consider possible forecasting errors or last-minute incidents. If the optimization range is of one day, the reserve will be actually seen as "day-ahead". If the optimization range is of one week, the need for reserve will be interpreted as "week-ahead". (Adequacy and Economy simulations) - -- DSM: power (decrease or increase) to add to the load. A negative value is a load decrease, a positive value is a load increase. Note that an efficient demand side management scheme may result in a negative overall sum (All simulation modes). - -## Links - -This window is used to handle all input data regarding the interconnections. On picking any interconnection in the primary list, the user gets direct access to all data regarding the link, which are five annual parameters, a set of six ready-made 8760-hour time-series, and a flexible number of ready-made 8760-hour time-series corresponding to the capacities of the links. - -- The five parameters, used in economy or adequacy simulations are displayed in the "Parameters" and in the "Transmission capacities" tab. They are namely: - - - "Hurdle cost": set by the user to state whether (linear) transmission fees should be taken into account or not in economy and adequacy simulations - - "Transmission capacities": set by the user to state whether the capacities to consider are those indicated in 8760-hour arrays or if zero or infinite values should be used instead (actual values / set to zero / set to infinite) - - "Asset type": set by the user to state whether the link is either an AC component (subject to Kirchhoff's laws), a DC component, or another type of asset - - "Account for loop flows": set by the KCG [^9] to include (or not) passive loop flows in the formulation of the constraints enforcing Kirchhoff's laws - - "Account for PST": set by the KCG to include (or not) the settings of phase-shifting transformers in the formulation of the constraints enforcing Kirchhoff's laws - -- The "Parameters" tab displays six 8760-hour times-series, which are: - - - Hurdle cost direct: an upstream-to-downstream transmission fee, in €/MWh - - - Hurdle cost indirect: a downstream-to-upstream transmission fee, in €/MWh - - - Impedance: used in economy simulations to give a physical meaning to raw outputs, when no binding constraints have been defined to enforce Kirchhoff's laws (see "Output" section, variable "Flow Quad") OR used by the Kirchhoff's constraint generator to build up proper flow constraints (AC flow computed with the classical "DC approximation"). Since voltage levels are not explicitly defined and handled within Antares, all impedances are assumed to be scaled to some reference \\( U_{ref} \\) - - - Loop flow: amount of power flowing circularly though the grid when all "nodes" are perfectly balanced (no import and no export). Such loop flows may be expected on any "simplified" grid in which large regions (or even countries) are modeled by a small number of "macro" nodes, and should accordingly be accounted for. - - - PST min (denoted \\(Y^-\\) in [Kirchhoff Constraints Generator](07-kirchhoffs_constraint_generator.md)): lower bound of phase-shifting that can be reached by a PST installed on the link, if any (note : the effect of the active loop flow generated by the PST may be superimposed to that of the passive loop flow) - - - PST max (denoted \\(Y^+\\) in [Kirchhoff Constraints Generator](07-kirchhoffs_constraint_generator.md)): upper bound of phase-shifting that can be reached by a PST installed on the link, if any (note : the effect of the active loop flow generated by the PST may be superimposed to that of the passive loop flow) - - For the sake of simplicity and homogeneity with the convention used for impedance, PST settings are assumed to be expressed in \\( rad/U^2_{ref} \\) - - -- The "Transmission capacities" tab displays "ready-made" 8760-hour time-series already available for simulation purposes. -In this tab, the table "Direct" describes the upstream-to-downstream capacity, in MW, and the table "Indirect" describes the downstream-to-upstream capacity, in MW. - _Please note that Time-Series analysis and generation is not available for capacity Time-Series._ - Different ways to update data are : - - direct typing - - copy/paste a selected field to/from the clipboard - - load/save all the time-series from/to a file (usually located in the "user" subfolder) - - Apply different functions (+,-, *, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") - - Handle the whole (unfiltered) existing dataset to either: - - - Change the number of columns (function name: resize) - - Adjust the values associated with the current first day of the year (function name: shift rows) - - Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the generation expected on Sundays at midnight, for all time-series). - -- _Note that:_ - - - _For a given link, the number of Time-Series for the direct and indirect capacity must be equal. Otherwise, an issue will be raised when launching a simulation_ - - - _If the "intra-modal correlated draws" option was not selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series for direct/indirect capacity is not the same for all links (e.g. 2 , 5 , 1 , 45 ,...)_ - - - _If the "intra-modal correlated draws" option was selected in the_ **simulation** _window, every link should have either one single time-series for both the direct and indirect capacity, or the same given number of time-series (e.g. 25 , 25 , 1 , 25...)_ - -## Binding constraints - -This section of the GUI is used to handle all data regarding special constraints that one may wish to include in the formulation of the optimization problems to solve. - -The set of tabs described hereafter provides for that purpose all the means required to define arbitrary linear constraints on any subset of continuous variables involved in the modeling of the power system. - -Since no limitation is set on the number and content of the constraints that may be defined that way, it is the user's sole responsibility to make sure that these so-called "binding constraints" are realistic and meaningful, be it from a technical or economic standpoint. - -A typical situation in which this feature proves useful is, for instance, encountered when data at hand regarding the grid include an estimate of the impedances of the interconnections. - -In such cases, assuming that: - -- \\(Z_l\\) denotes the impedance of interconnections \\(l=1, L\\) -- A preliminary study of the graph modeling the grid has shown that it can be described by a set of independent meshes \\(c=1, C\\)(cycle basis of the graph) - -Then the DC flow approximation may be implemented, for each time-step of the simulation, by a set of C binding constraints between AC flows \\(F_l\\): - -$$ c= 1, ..., C : \sum_{i \in C}{sign(l,c)F_lZ_l = 0}$$ - -_Note that such specific binding constraints can be automatically generated within Antares by using the auxiliary module "Kirchhoff's Constraints Generator" further described in [Kirchhoff Constraints Generator](07-kirchhoffs_constraint_generator.md)._ - -Aside from such sets of constraints, which may help to give realistic geographic patterns to the flows, completely different sets of constraints may be also defined, such as those set up by the market organization, which may define precise perimeters for valid commercial flows [^10]. - -More generally, Antares allows to define three categories of binding constraints between transmission flows and/or power generated from generating units: - -- "hourly" binding constraints, which are applied to instant power (transmitted and/or generated) - -- "daily" binding constraints, that are applied to daily energies. This class makes more sense for commercial modeling (say: imports and exports from/to such and such area should be comprised between such and such lower bound and upper bound). Daily binding constraints are also commonly used to model specific facilities, such as pumped storage units operated on a daily cycle - -- "weekly" binding constraints, that are applied to weekly energies. Like the previous ones, these constraints may be used to model commercial contracts or various phenomena, such as the operation of a pumped storage power plant operated on a weekly cycle. - -The Binding Constraints section of the GUI involves six main tabs described hereafter: - -- **TAB "summary"** -Creation, edition or removal of a binding constraint. A binding constraint is here defined by four macroscopic attributes that can be set by the edit command: - - - Name (caption) - - Time-range (hourly, daily, weekly) - - Numerical type (equality, bounded above, below, on both sides) - - Status (active /enabled or inactive/disabled) - -- **TAB "weights"** -Definition of the coefficients given to each flow variable or generation variable in the formulation of the constraints. Two sub-tabs make it possible to handle the coefficients associated with transmission assets (links) and those associated with generation assets (thermal clusters). In both cases: - - - The lines of the tables show only the components (links or clusters) that are visible on the current map - - The columns of the tables show only the constraints that do not have non-zero weights attached to components that are nor visible on the current map - -- **TAB "offsets"** -Definition of the time-lag (in hours) assigned to each flow variable or generation variable in the formulation of the constraints. Two sub-tabs make it possible to handle the offsets associated with transmission assets (links) and those associated with generation assets (thermal clusters). In both cases: - - - The lines of the tables show only the components (links or clusters) that are visible on the current map - - The columns of the tables show only the constraints that do not have non-zero weights attached to components that are nor visible on the current map - -- **TAB "="** -Definition of the right-hand side of equality constraints. This RHS has either 8760 values (hourly constraints) or 365 values (daily or weekly constraints). Depending on the range actually chosen for the simplex optimization (see section **Configure** of the main menu), the weekly constraints RHS will either be represented by the sum of seven daily terms or by a set of seven daily terms (weekly constraint downgraded to daily status). - -- **TAB ">"** -Definition of the right-hand side of "bounded below" and "bounded on both sides" inequality constraints. This RHS has either 8760 values (hourly constraints) or 365 values (daily or weekly constraints). Depending on the range actually chosen for the simplex optimization (see section **Configure** of the main menu), the weekly constraints RHS will either be represented by the sum of seven daily terms or by a set of seven daily terms (weekly constraint downgraded to daily status). - -- **TAB "<"** -Definition of the right-hand side of "bounded above" and "bounded on both sides" inequality constraints. This RHS has either 8760 values (hourly constraints) or 365 values (daily or weekly constraints). Depending on the range actually chosen for the simplex optimization (see section **Configure** of the main menu), the weekly constraints RHS will either be represented by the sum of seven daily terms or by a set of seven daily terms (weekly constraint downgraded to daily status). - -_NOTE: The right-hand side of a binding constraint can be set to "inf" (for "bounded above" constraints) or "-inf" (for "bounded below" constraints) for any timestamp. In that case, the constraint will be ignored by the solver for this timestamp. Please note that it is the user's responsibility to ensure that these values are set in a consistent way._ - -**WARNING:** When some clusters are defined as being in must-run ("must-run" parameter set to "True"), these clusters are automatically removed from the binding constraints in order to avoid potential incompatibilities between these constraints and the power output imposed to the must-run clusters. The clusters which are removed from binding constraints are visible in the "Summary" tab, in which they are multiplied by N/As in the binding constraints. -In case a binding constraint only contains must-run clusters, it will be ignored in the simulation and subsequently identified as "Skipped" in the summary tab. -Please note that in the specific context of the adequacy simulation mode (in which all thermal clusters are considered as being fully must-run), **all thermal clusters will consequently be de-activated from the binding constraints**. This can lead to incorrect adequacy indicators in Antares studies containing binding constraints. - - -When defining binding constraints between (hourly) power, daily or weekly (energy) flows, special attention should be paid to potential conflicts between them or with the "basic" problem constraints. Lack of caution may result in situations for which the optimization has no solution. Consider for instance a case in which three variables X1, X2, X3 (whatever they physical meaning) are involved in the following binding constraints: - -$$X1 + X2 > 5$$ - -$$X2 < -3$$ - -$$X3 > 0$$ - -$$X1 + X3 < 7$$ - -These commitments are obviously impossible to meet and, if the economic simulator is run on a dataset including such a set of constraints, it will produce an infeasibility analysis that looks like the following. -``` -[solver][notic] Solver: Starting infeasibility analysis... -[solver][error] The following constraints are suspicious (first = most suspicious) -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 124 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 128 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 137 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 140 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 133 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 139 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 136 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 130 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 142 -[solver][error] Hydro reservoir constraint at area 'Germany' at hour 123 -``` - -This report should help you identify constraints that generate infeasible linear optimization problems such what is presented above. - -The advanced preference "Unfeasible Problems Behavior" gives to the user the ability to choose between four different strategies regarding these situations. - -## Economic Opt. - -This window is used to set the value of a number of area-related parameters that, aside from the costs of each generating plant, define the optimal solution that Antares has to find in economic simulations. These parameters are namely, for each area of the system: - -- The value of the unsupplied energy (also commonly denoted Value Of Lost Load,VOLL) , in €/MWh. This value should usually be set much higher than the cost of the most expensive generating plant of the area - -- The random spread within which the nominal unsupplied energy value is assumed to vary - -- The value of the spilled energy, in € /MWh. This value reflects the specific penalty that should be added to the economic function for each wasted MWh, if any. Note that even if this value is set to zero no energy will be shed needlessly - -- The random spread within which the nominal unsupplied energy value is assumed to vary - -- Three parameters named "shedding status" and related to different kinds of generation. If the system cannot be balanced without shedding some generation, these parameters give control on how each kind of generation ("Non dispatchable power","Dispatchable hydropower" and "Other dispatchable generating plants") should contribute to the shedding. Depending on the value chosen for the status, the generation can or cannot be shed to find a solution to the load/generation balance problem. Note that enforcing a negative status for all types of plants may lead to simulations scenarios for which there are no mathematical solutions. - -On running the economic simulator, such situations produce an infeasibility diagnosis. - - -## Miscellaneous - -In all previous windows showing Input data, the content can be filtered so as to reflect only items that are associated with Areas and Links defined as "visible" in a particular map. In that regard, binding constraints are considered as visible if and only if all of their non-zero weight associated objects are visible on the map. - - -[^5]: "Economy" simulations make a full use of Antares optimization capabilities. They require economic as well as technical input data and may demand a lot of computer resources. "Adequacy" simulations are faster and require only technical input data. Their results are limited to adequacy indicators. - -[^6]: In Economy an Adequacy simulations, these should be chosen so as to make the simulation span a round number of weeks. If not, the simulation span will be truncated: for instance, (1, 365) will be interpreted as (1, 364), i.e. 52 weeks (the last day of the last month will not be simulated). - -[^7]: changing the number of MC years will reset the playlist to its default values - -[^9]: KCG : Kirchhoff's constraints generator (see section 7) - -[^10]: A typical case is given by the "Flow-Based" framework today implemented in a large portion of the European electricity market. diff --git a/docs/reference-guide/05-output_files.md b/docs/reference-guide/05-output_files.md deleted file mode 100644 index 0902ec8366..0000000000 --- a/docs/reference-guide/05-output_files.md +++ /dev/null @@ -1,202 +0,0 @@ -# Output files - -The general file organization is the same for Economy and Adequacy simulations. - -Economy and Adequacy results may be displayed in the GUI ( "Output" in main menu) - -**Economy:** - -| OUTPUT/Simu id/economy/mc-all/ | | | | -|----------------------------------|---------------|-----------------|---------------------------------------| -| |/grid/... | | contains a summary file "digest.txt" | -| |/areas/name/...| | contains area-related results | -| |/links / name/...| | contains interconnection-related results | -| |/mc-ind /year_number| | | -| | |/areas/name/...| contains area-related results| -| | |/links/name/...| contains interconnection-related results| - -_("mc-all" files contain synthetic results over all years, "year-number" files contain results for a single year)_ -_The variables present in each file are detailed in the following sections._ -_In "Economy" simulations, all variables have a techno-economic meaning._ - -**Adequacy:** - -| OUTPUT/Simu id/adequacy/mc-all/ | | | | -|----------------------------------|---------------|-----------------|---------------------------------------| -| |/grid/... | | contains a summary file "digest.txt" | -| |/areas/name/...| | contains area-related results | -| |/links / name/...| | contains interconnection-related results | -| |/mc-ind /year_number| | | -| | |/areas/name/...| contains area-related results| -| | |/links/name/...| contains interconnection-related results| - -_("mc-all" files contain synthetic results over all years, "year-number" files contain results for a single year)_ -_The variables present in each file bear exactly the same name as in Economy simulations but do not have the same values._ -_The only variables that have a techno-economic meaning are the "Adequacy" indicators (unsupplied energy,LOLD,LOLP)_ - -**IMPORTANT** Adequacy and Economy files look the same but their content are specific - -In "Economy" and "Adequacy" simulations, the optimization ignores the "primary" and "strategic" reserves (however, it may include the [other] spinning and day-ahead reserves, depending on the settings made in "optimization preferences"). - -In "Adequacy" simulations, all dispatchable thermal units are given the "must-run" status (hence, they will generate at Pmax, regardless of the demand). As a consequence the only variables that are actually meaningful are the adequacy indicators (unsupplied energy, LOLD,LOLP), that may depend on assumptions made regarding the economic values of Unsupplied and spilled energies, and on hurdle costs on interconnections. -In the specific case where binding constraints are present in the study, **all thermal clusters will consequently be de-activated from the binding constraints**. This can lead to incorrect adequacy indicators in Antares studies containing binding constraints in "Adequacy" simulations. - -As a consequence, both "Adequacy" and "Economy" simulations yield the same values for the adequacy indicators under the following conditions: if hurdle costs on interconnections are higher than the difference between the maximum VOLL and the minimum VOLL assigned to the different areas of the system, and if no binding constraint is altered due to the fact that they contain clusters in must-run. - -The files and their content are hereafter described. - -## Economy and Adequacy, area results [^11] - -**15** files resulting from the combination of the following attributes: -**[values | id | details] X [hourly | daily | weekly | monthly | annual]** - -- The second attribute defines the time span over which the results are assessed: hourly detail, daily bundle, weekly bundle, monthly bundle, annual bundle. - -- The first attribute defines the nature of the results presented in the file : - -**Values** Values of different variables (price, load, overall generation issued from coal, etc.), the list of which is common to all areas of the interconnected system. Files of type "values" have therefore the same size for all areas. -These results appear under the label "general values" in the output GUI. - -**details** Values regarding the different dispatchable thermal generating plants of each area (e.g. "older 300 MW coal from the south coast"). The sizes of these files differ from one area to another. -These results appear under the label "thermal plants" in the output GUI. - -**id** Identifier (number) of the Monte-Carlo years for which were observed the extreme values of the different variables presented in the « values » files -These results appear under the label "record years" in the output GUI - -The area files that belong to the « values » class display **122** fields corresponding to the expectation, standard deviation, minimal and maximal values of the variables whose list is given hereafter. - -| variables | description | -|-----------|-------------| -| OV.COST | Overall cost = operating cost + unsupplied cost+ spilled cost+ hydro cost | -| OP.COST | Operating cost = Proportional costs + Non- proportional costs | -| MRG. PRICE | LMP : overall economic effect of a local 1MW load increase | -| CO2 EMIS. | Amount of CO2 emitted by all dispatchable thermal plants | -| NH3 EMIS. | Other pollutans than CO2: NH3, NOX, PM2\_5, PM5, PM10, NMVOC, OP1, OP2, OP3, OP4, OP5 EMIS. | -| BALANCE | Overall Import/export balance of the area (positive value : export) | -| ROW BAL | Import/export with areas outside the modeled system (positive value: import) [^12] | -| PSP | User-defined settings for pumping and subsequent generating | -| MISC. NDG | Miscellaneous non dispatchable generation | -| LOAD | Demand (including DSM potential if relevant) | -| H.ROR | Hydro generation, Run-of-river share | -| WIND | Wind generation (only when using aggregated _Renewable generation modeling_)| -| SOLAR | Solar generation (thermal and PV) (only when using aggregated _Renewable generation modeling_)| -| NUCLEAR | Overall generation of nuclear clusters | -| LIGNITE | Overall generation of dispatchable thermal clusters burning brown coal | -| COAL | Overall generation of dispatchable thermal clusters burning hard coal | -| GAS | Overall generation of dispatchable thermal clusters burning gas | -| OIL | Overall generation of dispatchable thermal clusters using petroleum products | -| MIX.FUEL | Overall gen. of disp. thermal clusters using a mix of the previous fuels | -| MISC.DTG | Overall gen. of disp. thermal clusters using other fuels | -| MISC.DTG 2 | Overall gen. of disp. thermal clusters using other fuels | -| MISC.DTG 3 | Overall gen. of disp. thermal clusters using other fuels | -| MISC.DTG 4 | Overall gen. of disp. thermal clusters using other fuels | -| WIND OFFSHORE | Wind Offshore generation (only when using clustered _Renewable generation modeling_) | -| WIND ONSHORE | Wind Onshore generation (only when using clustered _Renewable generation modeling_) | -| SOLAR CONCRT. | Concentrated Solar Thermal generation (only when using clustered _Renewable generation modeling_) | -| SOLAR PV | Solar Photovoltaic generation (only when using clustered _Renewable generation modeling_) | -| SOLAR ROOFT | Rooftop Solar generation (only when using clustered _Renewable generation modeling_) | -| RENW. 1 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | -| RENW. 2 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | -| RENW. 3 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | -| RENW. 4 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | -| H.STOR | Power generated from energy storage units (typically: Hydro reservoir) | -| H.PUMP | Power absorbed by energy storage units (typically: PSP pumps consumption) | -| H.LEV | Energy level remaining in storage units (percentage of reservoir size) | -| H.INFL | External input to the energy storage units (typically: natural inflows) | -| H.OVFL | Wasted natural inflow overflowing from an already full energy storage unit | -| H.VAL | Marginal value of stored energy (typically: shadow water value) | -| H.COST | Expenses /Income brought by energy storage actions (H.STOR,H.PUMP) | -| UNSP. ENRG | Unsupplied energy: adequacy indicator (Expected Energy Not Served–EENS) | -| SPIL. ENRG | Spilled energy (energy produced that cannot be used and has to be wasted) | -| LOLD | Loss of load duration: adequacy indicator (length of shortfalls) | -| LOLP | Loss of Load probability: adequacy indicator (probability of at least one hour of shortfall within the considered period, without normalization by the duration of the considered period) | -| AVL. DTG | Available dispatchable thermal generation (sum of av. power over all plants) | -| DTG. MRG | Disp. Ther. Gen. (AVL DTG – sum of all dispatched thermal generation) | -| MAX. MRG | Maximum margin: operational margin obtained if the hydro storage energy of the week were used to maximise margins instead of minimizing costs | -| DENS | Domestic Energy Not Supplied: the difference between the local production capabilities of an area and its local load[^adqp] | -| LMR. VIOL | Local Matching Rule Violation after the Antares Simulation as defined by the adequacy patch[^adqp] | -| SPIL. ENRG. CSR | Spilled Energy after the Curtailment Sharing Rule step of the dequacy patch[^adqp] | -| NP COST | Non-proportional costs of the dispatchable plants (start-up and fixed costs) | -| NODU | Number of Dispatched Units [^13] | -| Profit | Net profit of the cluster in euros ((MRG. PRICE - marginal cost of the cluster) * (dispatchable production of the cluster)[^15] | - -Note: The net profit is computed on full precision values for MRG. PRICE. The user may obtain slightly different results applying the given formula because MRG. PRICE values are rounded to 10^-2. - -## Economy and Adequacy, interconnection results [^14] -**10** files resulting from the combination of the following attributes: -**[values | id] X [hourly | daily | weekly | monthly | annual]** - -- The second attribute defines the period of time over which the results are assessed: hourly detail, daily bundle, weekly bundle, monthly bundle, annual bundle. -- The first attribute defines the nature of the results presented in the file. - - -**values** values of different variables (flow, congestion rent) the list of which is common to all interconnections. The files of type "values" have therefore the same size everywhere -These results appear under the label "general values" in the output GUI. - -**id** identifier (number) of the Monte-Carlo years for which were observed the extreme values of the different variables presented in the « values » files. -These results appear under the label "record years" in the output GUI. - - -The area files that belong to the « values » class display **28** fields corresponding to the expectation, standard deviation, minimal and maximal values of the variables whose list is given hereafter. - -| variables | description | -|-----------|-------------| -| FLOW LIN. | Flow (signed + from upstream to downstream) assessed by the linear optimization. These flows follow Kirchhoff's law only if these laws have been explicitly enforced by the means of suitable binding constraints | -| UCAP | Used capacity: absolute value of FLOW LIN. This indicator may be of interest to differentiate the behavior of interconnectors showing low average flows: in some cases this may indicate that the line is little used, while in others this may be the outcome of high symmetric flows | -| LOOP FLOW | Flow circulating through the grid when all areas have a zero import/export balance. This flow, to be put down to the simplification of the real grid, is not subject to hurdle costs in the course of the optimization | -| FLOW QUAD. | Flow computed anew, starting from the linear optimum, by minimizing a quadratic function equivalent to an amount of Joule losses, while staying within the transmission capacity limits. This calculation uses for this purpose the impedances found in the "Links" Input data. If congestions occur on the grid, these results are not equivalent to those of a DC load flow| -| CONG. FEE ALG | Algebraic congestion rent = linear flow \* (downstream price – upstream price) | -| CONG. FEE ABS | Absolute congestion rent = linear flow\* abs(downstream price–upstream price) | -| MARG. COST | Decrease of the system's overall cost that would be brought by the optimal use of an additional 1 MW transmission capacity (in both directions) | -| CONG PROB + | Up>Dwn Congestion probability = (NC+) / (total number of MC years) with:
    NC+ = number of years during which the interconnection was congested in the Up>Dwn way for **any** length of time within the time frame relevant with the file| -| CONG PROB - | Dwn>Up Congestion probability = (NC-) / (total number of MC years) with:
    NC- = number of years during which the interconnection was congested in the Dwn>Up way for **any** length of time within the time frame relevant with the file| -| HURD. COST | Contribution of the flows to the overall economic function through the "hurdles costs" component. For each hour:
    `if (FLOW.LIN –LOOP FLOW) > 0 `
    `HURD. COST = (hourly direct hurdle cost) * (FLOW LIN.)`
    `else HURD.COST = (hourly indirect hurdle cost) * (-1) * (FLOW LIN.)`| - -## Economy and Adequacy, other results - -Depending on the options chosen in the main simulation window, the output folders may also include either, both or none of the following sections: - -| OUTPUT/Simu id/ts-numbers/ | | | -|------------------------------|--------------------|--------------------------------| -| |/Load | /area names/... | -| |/Thermal | /area names/... | -| |/Hydro | /area names/... | -| |/Wind[^agg] | /area names/... | -| |/Solar[^agg] | /area names/... | -| |/Renewables[^ren] | /area names/... | -| |/NTC | /area names/... | - -These files contain, for each kind of time-series, the number drawn (randomly or not) in each Monte-Carlo year (files are present if "output profile / MC scenarios" was set to "true"). - -| OUTPUT/Simu id/ts-generator/ | | | -|------------------------------|--------------------|--------------------------------| -| |/Load | /batch number/area names/... | -| |/Hydro | /batch number/area names/... | -| |/Wind[^agg] | /batch number/area names/... | -| |/Solar[^agg] | /batch number/area names/... | - - -These files contain, for each kind of Antares-generated time-series, copies of the whole set of time-series generated. Batch numbers depend on the values set for the "refresh span" parameters of the stochastic generators (files are present if "store in output" was set to "true"). - -## Miscellaneous - -Alike Input data, output results can be filtered so as to include only items that are associated with Areas and Links defined as "visible" in the current map. In addition, the output filtering dialog box makes it possible to filter according to two special categories (**Districts** and **Unknown**) that are not related to standard maps: - -- **Districts** displays only results obtained for spatial aggregates -- **Unknown** displays only results attached to Areas or Links that no longer exist in the Input dataset (i.e. study has changed since the last simulation) - -[^11]: This description applies to both « MC synthesis » files and "Year-by-Year" files, with some simplifications in the latter case - -[^12]: Value identical to that defined under the same name in the "Misc Gen" input section. - -[^13]: NODU and NP Cost do not appear in "Adequacy" results since these variables are irrelevant in that context - -[^adqp]: Please note that this output variable is only available in the economy mode, when the adequacy patch is activated (see [Adequacy Patch](14-adequacy-patch.md)) - -[^14]: This description applies to both « MC synthesis » files and "Year-by-Year" files, with some simplifications in the latter case - -[^agg]: This output is only available if the parameter "renewable generation modelling" is set to "cluster" in the input of the simulation - -[^ren]: This output is only available if the parameter "renewable generation modelling" is set to "aggregated" in the input of the simulation - -[^15]: dispatchable production = power generation above min gen = (power generation) - (min gen modulation)*units*capacity diff --git a/docs/reference-guide/06-time_series_analysis_and_generation.md b/docs/reference-guide/06-time_series_analysis_and_generation.md deleted file mode 100644 index c4cca72f70..0000000000 --- a/docs/reference-guide/06-time_series_analysis_and_generation.md +++ /dev/null @@ -1,427 +0,0 @@ -# Time-series analysis and generation - -## General - -When ready-made time-series are not available or are too scarce for building the required number of Monte-Carlo annual simulation scenarios, Antares provides means to generate sets of stochastic time-series to use instead. - -The different categories of time-series call for wholly different generation processes: - -- For thermal power, the generator is based on the animation of a daily three-state Markov chain (available – planned outage – forced outage) attached to each plant. - -- For Hydro-power, the generator works out monthly time-series of energies, based on the assumption that they can be modeled by Log Normal variables with known correlations through space and time. So as to keep the model simple, for an interconnected system made of N areas, the user defines, along with the N expectations and N standard deviations of the monthly energies, the N X N correlation matrix R(n,m) of the logs of the annual hydro energies between the areas n,m, and the N average auto-correlations r(k) between one month and the next in each area k. The correlation **C(n,i,m,j)** between the logs of hydro energies in area **n**, month **i** and area **m**, month **j** is taken to be - -$$C(n,i,m,j) = R(n,m)*\sqrt{(r(n) \cdot r(m))^{|j-i|}}$$ - - -This most simplified model asks for considerably fewer data than a comprehensive 12N X 12N time-space matrix. Note that if R is positive semi-definite but C is not, matrix C is automatically transformed into a fitting p.s.d matrix and the data generation keeps going on (however, the log report will show a warning message). If the primary matrix R is not p.s.d, data are considered as corrupted, the generation stops and a fatal error message will be displayed in the log report - -- For Wind power, Solar power and Load, the required time-series are 8760-hour long and have to emulate as closely as possible the response of the system to variations of wind speed, sunshine and temperature. In all three cases, the rationale of the model is to offer the possibility to consider either the final variable to model (wind power output, solar power output, load) or an underlying intermediate variable (wind speed, nebulosity, deviation between load and the level expected in standard temperature conditions) as a stationary stochastic process, with given marginal laws, given auto-correlation functions and given spatial correlations (eventually, the values of the final variables and those of the core stationary process are tied by diurnal/seasonal rhythms and scaling functions). - -The identification of all relevant parameters can be made outside Antares by any appropriate means but can also be made automatically by the time-series analyzer, which is then to be fed with the largest available set of historical time-series. Note however that, using the time-series analyzer, one has to consider whether the time-series at hand are statistically meaningful or whether they need some pre-processing (for instance, if wind power time-series are gathered for a period within which the fleet has been expanded, the time-series to analyze should be expressed in % of installed power rather than in MW. For Solar power, the relevant variable to model as a stationary stochastic process is probably not the raw output of solar power but more likely a meteorological indicator related to the sky clarity (for instance , time-series of nebulosity expressed on a 0-100 scale may be used). - -Once generated by appropriate algorithms, the values of the stationary processes are turned into final values by using a number of parameters that put back in the series the diurnal and seasonal patterns that may have been observed in the course of the historical data analysis and that were temporarily removed to identify the core stationary processes. - - -## Time-series generation (load, wind, solar): principles - -For the generation of wind, solar and load time-series, Antares gives access to different marginal laws and autocorrelation functions presented hereafter. Note that wind speed modeling should usually be based upon a Weibull modeling, while almost all other situations are likely to be best modeled by Beta variables. - -The stationary processes are defined at a monthly scale. For each month, there are: - -- Four parameters for the definition of the marginal law - -TS Gen. Parameters : \\(\alpha\\), \\(\beta\\), \\(\gamma\\) and \\(\delta\\) - -| **Law** | \\(\alpha\\) | \\(\beta\\) | \\(\gamma\\) | \\(\delta\\) | **Expectation** | **Variance** | -|---------|:----------:|:---------:|:----------:|:----------:|:---------------:|:------------:| -| Uniform | N/A | N/A | \\(< \delta\\) | \\(> \gamma\\) | \\({(\delta - \gamma)\over 2}\\) | \\({(\delta - \gamma)^2\over 12}\\) | -| Beta | >0 | >0 | \\(< \delta\\) | \\(> \gamma\\) | \\(\gamma + {\alpha(\delta - \gamma)\over (\alpha + \beta)}\\) | \\(\alpha\beta(\delta - \gamma)^2\over (\alpha + \beta + 1)(\alpha + \beta)^2\\) | -| Normal | Any | >0 | N/A | N/A | \\(\alpha\\) | \\(\beta^2\\) | -| Weibull | >=1
    <50 | >0 | N/A | N/A | \\(\beta \Gamma (1 + {1\over\alpha})\\) | \\(\beta^2[\Gamma(1+{2\over \alpha}) - \Gamma (1 + {1\over \alpha})^2]\\) | -| Gamma | >=1
    <50 | >0 | N/A | N/A | \\(\alpha * \beta\\) | \\(\alpha * \beta^2\\) | - -_Uniform: uniform defined on (\\(\gamma\\), \\(\delta\\))._ -_Beta: Beta (\\(\alpha\\), \\(\beta\\)) defined on (\\(\gamma\\), \\(\delta\\))._ -_Normal: expectation \\(\alpha\\), standard deviation \\(\beta\\)._ -_Weibull: shape \\(\alpha\\), scale \\(\beta\\), defined on (0,+\\(\infty\\))._ -_Gamma: shape \\(\alpha\\), scale \\(\beta\\), defined on (0, +\\(\infty\\))._ - -In the expressions of expectation and variance, \\(\Gamma(x)\\) is the standard Euler Function. - - -- Two parameters for the definition of the autocorrelation function - -**TS Gen. Parameters : \\(\theta\\) and \\(\mu\\)** - -| **Law** | \\(\theta\\) | \\(\mu\\) | **Corr(Xt, Xt+h)** | -|-----|----|-----|--------| -| Pure exponential decay | \\(\theta > 0\\) | \\(\mu = 1\\) | \\(e^{-\theta h}\\) | -| Smoothed exponential decay [^decay] | \\(\theta > 0\\) | \\( 1 < \mu < 24\\) | \\(\Phi(\theta, \mu, h)\\) | - -$$\Phi(\theta, \mu, h)\ =\ {1\over A}\ *\ \sum_{i=0, \mu}{\ \sum_{j=h, h+\mu}{e^{-\theta|j-i|}}}$$ - -**with** - -$$A=\mu + 2 \sum_{i=1, \mu; j=1, \mu; j > i}{e^{-\theta(j-i)}}$$ - - -## Time-series generation (load, wind, solar): GUI - -The section of the GUI specific to the generation of wind, solar and load time-series comprises: - -1. **Spatial correlation matrices that are located within the "spatial correlation" tab of each path "Wind|Solar|Load / <area\_name>"** - - This tab contains a workspace for the description of 12 monthly spatial correlation matrices \\(\Xi\\) and one annual correlation matrix. For the stochastic generators to work properly, these matrices must meet the usual requirements (matrices must be p.s.d, symmetric, with all terms between -100 and +100, and a main diagonal made of 100s). If this is not the case, generators will emit an infeasibility diagnosis. Matrices can be either set up manually OR automatically filled out by the time-series analyzer (see next paragraph). - - Depending on the choices made in the main "simulation" window, the matrices used will be either the 12 monthly matrices or the annual matrix. Whether to use the first or the second option depends on the quality of the statistical data at hand: with high quality data (for instance, that derived from the analysis of a very large pool of historical data), use of monthly correlations is recommended because monthly differences between matrices have a physical meaning ; with less robust data (derived from a handful of historical data,…), use of the single annual correlation matrix should be preferred because it smooths out the numeric noise which impairs the monthly matrices. - -2. **Four parameters and four subtabs that are located within the "local" tab of each path "Wind|Solar|Load / <area\_name>"** - -**FOUR PARAMETERS** - -- Capacity: This first parameter is used to scale up time-series generated on the basis of the (\\(\alpha\\), \\(\beta\\), \\(\gamma\\), \\(\delta\\), \\(\theta\\), \\(\mu\\)) parameters described previously in the "principles" paragraph, together with coefficients characterizing the diurnal pattern (see below) - -- Distribution: This second parameter gives the type of marginal distribution of the stationary stochastic processes to generate (Beta, Weibull, Normal, Gamma, Uniform) - -- Translation: This third parameter has three possible values: - - - Do not use: parameter ignored - - Add before scaling: A specific 8760-hour array is added to the time-series produced by the primary stochastic generator, BEFORE use of the conversion table (optional) followed by the final multiplication by the capacity factor - - Add after scaling: A specific 8760-hour array is added to the time-series produced by the primary stochastic generator, AFTER use of the conversion table (optional) followed by the final multiplication by the capacity factor - -- Conversion: This fourth parameter has two possible values: - - - Do not use: Any transfer function that may be described in the "conversion" subtab (see below) should not be used for the final stage of data elaboration (for instance, if the primary parameters describe the physics of wind speeds, the time-series eventually produced should remain wind speeds and not wind power). - - - Use: The time-series produced by the stochastic generators (wind speeds, for instance) are turned into other values (wind power) by using the transfer function described in the "conversion" subtab. - -**FOUR SUBTABS** - -- Subtab "Coefficients" - A twelve-month table of values for the primary parameters \\(\alpha\\), \\(\beta\\), \\(\gamma\\), \\(\delta\\), \\(\theta\\), \\(\mu\\)
    - This table may be either filled out manually or automatically (use of the time-series analyzer) - -- Subtab "Translation" - Contains an 8760-hour array T to add to the time-series generated, prior or after scaling. This array can be either filled out manually or by the time-series analyzer. - -- Subtab "Daily profile" - A 24\*12 table of hourly / monthly coefficients K(hm) that are used to modulate the values of the stationary stochastic process by which the actual process is approximated. This table can be either filled out manually or by the time-series analyzer. - -- Subtab "Conversion" - A table of 2 \* N values (with 1<=N<=50) that is used to turn the initial time-series produced by the generators (for instance, wind speeds) into final data (for instance, wind power). The transfer function (speed to power, etc.) is approximated by N discrete points whose abscises X(N) an ordinates Y(N) are given by the table. - -## Time-series analysis (load, wind, solar) - -The time-series analyzer module available in Antares is meant to identify the values that should be given to the parameters used in the time-series generators (load, solar power, wind power) so as to fit best historical time-series at hand. - -**IMPORTANT: ** When the time-series analyzer is used, it automatically updates the parameters relevant to the analysis (for instance: analysis of "wind" time-series will overwrite all local and global "wind" parameters [correlation matrices] that may have been previously set manually). - -The primary TS analyzer window shows two tabs: - -**1. Tab "Time-series and areas"** - -- Time-series (load, wind, solar): class of parameters to be assessed by the analyzer - -- Browse: location of the historical time-series files. These are txt files in which 8760-hour time-series must be stored in adjacent columns separated by a tabulation - -- For each area: - - - Activity status - - yes: parameters will be assessed and updated by the analyzer - - no: the area will be skipped (**local** parameters for the area will remain unchanged, however **spatial** correlation with other areas will be reset to zero) - - - Distribution - - Type of distribution to fit (beta, normal, etc.) - - - Data - - Raw: data to analyze are the actual historical time-series - - Detrended: data to analyze are the time-series of the deviations to average (for instance: load time-series need to be analyzed in "detrended" mode while wind speeds can be analyzed in "raw" mode) - - - File to analyze - - Name of the file that should contain historical time-series to analyze - - Status - - Ready (a file bearing the expected name was found) - - Not found (no file found with the expected name) - -**IMPORTANT:** To generate stochastic data similar to the historical data analyzed, generation parameters must be kept consistent with the results of the analysis, which means, in the generators: - -- Keep the same: - - - Type of distribution - - Values for \\(\alpha\\), \\(\beta\\), \\(\gamma\\), \\(\delta\\) and for the diurnal–seasonal pattern (table of 12 X 24 values) - - Value for the "capacity" parameter (the analyzer automatically sets it to 1) - -- Besides: - - "Conversion" option must be set to "no" - - "Translation" option must be set to "do not use "if data were analyzed as "raw" and to "add after scaling" or "add before scaling" if data were analyzed as "detrended" (both options give the same value in this case because the scaling is 1:1) - -**2. Tab "Global settings"** - -- Temporary folder: workspace that can be used for the analysis (cleaned after use) - -- Analyzer settings - - - Short-term autocorrelation adjustment (%) - - Long-term autocorrelation adjustment (%)
    - These two parameters are used by Antares as targets for the fitting of \\(\theta\\) and \\(\mu\\) parameters. For instance, if the historical time-series autocorrelation function is such that Corr(T,T+ 18 hours)=90 % and Corr(T,T+60 hours)= 50%, and if the parameters in the analyzer are (ST = 90%,LT = 50%) , then it will search values of \\(\theta\\) and \\(\mu\\) matching the historical autocorr.function in two points(18 hours, 60 hours). - - - Trimming threshold (%)
    - In the spatial correlation matrices, terms lower than the threshold will be replaced by zeroes - -- Input data - - - Time-series per area (n)
    - limits the analysis to the first n historical time-series at hand - - Upper-bound (Max)
    - In the analysis, all values above Max in the historical files will be replaced by Max - - Lower-bound (Min)
    - In the analysis, all values below Min in the historical files will be replaced by Min - -**IMPORTANT:** For each month, time-series to analyze are assumed to represent a stationary stochastic signal modulated by 24 hourly shape-factors. All of these shape-factors are expected to be different from zero. If the signal is partly masked by sequences of zeroes (for instance, if solar power time-series are to be analyzed as such because time-series of nebulosity are not available), the analysis is possible but is subject to the following restrictions: - -- **Use of the "detrended" mode in the first Tab is mandatory** _(use of the "raw" mode would produce wrong correlation matrices)_ - -- **Short- and Long- Term autocorrelation parameters in the second Tab must be identical and set to 99%** _(to ensure that auto-correlation be assessed for the shortest possible time lag, i.e. one hour)_ - -**NOTICE:** For the whole year, the analyzer delivers a table of 12x24 hourly shape-factors consistent with the 12 sets of parameters identified for the stationary stochastic processes. The content of the table depends on the mode of analysis chosen: - -- **"raw"** analysis: for each month, the sum of the 24 hourly shape-factors is equal to 24 (i.e. each term is a modulation around the daily average). - -- **"detrended"** analysis: for the whole year, hourly coefficients are expressed relatively to the annual hourly peak of the (zero-mean) signal absolute value. (i.e. all factors belong to the [0,1] interval) - -## Time-series generation (thermal) - -The thermal time-series generation will only be launched: - - On thermal clusters that have the Generated TS parameter set to “Force generation†- - And, when in the Simulation window, the Stochastic TS parameter for Thermal is set to "Onâ€, on the thermal clusters that have the Generated TS parameter set to "Use global parameter". - -The stochastic generator for time-series of available dispatchable power generation works, for each plant of each set (cluster), with the following parameters: - -- The nominal plant capacity and a 8760-hour array of modulation coefficients to apply to it (default value: 1) - -- A 365-day array of forced outages rates ("FOR", lies in [0,1] ) - -- A 365-day array of planned outages rates ("POR", lies in [0,1]) - -- A 365-day array of forced outages average durations ("FOD" in days, integer, lies in [1,365]) - -- A 365-day array of planned outages average durations ("POD" in days, integer,lies in [1,365]) - -- A 365-day array of planned outages minimum number (PO Min Nb) (integer, lies in [0, PO Max Nb]) - -- A 365-day array of planned outages maximum number (PO Max Nb) (integer, lies in [PO Min Nb, Nb of units in the cluster] - -- Two parameters describing how forced outages durations may randomly deviate from their average value (law: uniform or geometric , volatility: lie in [0,1]) - -- Two parameters describing how planned outages durations may randomly deviate from their average value (law: uniform or geometric , volatility: lie in [0,1]) - -**1. Outage duration : meaning and modeling** - -In the thermal time-series generator, the concept of outage duration (either forced or planned) is simple enough: for any given plant affected by such an event, it is the duration of a single outage, expressed in days. - -The fact that 365 different values can be used to describe what may happen in the course of a year (for each kind of outages) means that the average outage duration may depend on the day the outage begins on. For instance, very short outages may be sometimes be planned on week-ends. Likewise, historical statistics can show that forced outages do not last the same average time in winter and summer, etc. - -In complement to the average value of the duration D of outages beginning on a particular day, the time-series generator allows to set two parameters that describe how the actual outage durations may deviate from the calendar-related average value. - -- The first parameter (law) can take either the value "uniform" or "geometric":
    - Uniform: the actual outage duration will be randomly drawn (one draw per outage), according to a **uniform distribution** centred on the average value **D**. The width of the interval [min duration, max duration] will depend on the value of the second parameter (volatility).
    - Geometric: the actual outage duration will be expressed as the sum of a fixed value F and a randomly drawn (one draw per outage) variable following a **geometric distribution** of expectation G, with **F+G=D**. The ratio of F to G will depend on the value of the second parameter (volatility). - - -- The second parameter (volatility) can take any value within [0,1]: - - - 0: The outage duration does not show any stochastic fluctuation at all.
    - Therefore, regardless of the chosen distribution law:
    - **
    actual duration = D
    ** - - - 1: The variability of the actual outage duration is as high as the chosen distribution law makes it possible, which means respectively that: - - - If choice = "uniform": **1 <= actual duration <= 2D-1** - - If choice = "geometric": **F = 0 and G = D**
    - (which in turn implies 1 <= actual duration <= #4D) - - - 0<V<1: The variability of the actual outage duration is such that the ratio \\(\sigma / D\\) of its standard deviation to its expectation has a value that depends on **V** , on **D** and on the chosen distribution law. More precisely: - - - If choice = "uniform": \\(\sigma / D = [{1/3}^{0.5}] \* V \* (D-1) / D \\)
    - and
    - **Duration min = D (1-V) + V**
    - **Duration max = D (1+V) - V** - - - If choice = "geometric": \\(\sigma / D = V \* [(D-1) / D]^{0.5}\\)
    - and
    - **Duration min = F**
    - **Duration max # 4D-3F**
    - _with F = D – G_
    - _G = 2z /[(1+4z)^0.5 - 1]_
    - _z = (V^2) \* D \* (D-1)_ - -**NOTE:** _The calculation time required for the generation of time-series does not depend of the kind of chosen law but depends on the fact that the volatility is null or not (it is minimal for zero-volatility)._ - -**NOTE:** _A geometric law associated with a volatility parameter V yielding a characteristic parameter F (according to the previous formulas) will produce a distribution summarized by:_ - -- _63 % of values in the interval [F, D]_ -- _23 % of values in the interval [D, 2D-F]_ -- _12 % of values in the interval [2D-F, 4D-3F]_ -- _2 % of values in the interval [4D-3F, infinite)_ - -**Remark:** _Antares is able to provide these options because it involves more than a simple Markov chain mechanism (intrinsically limited to : law = geometric, volatility = 1)_ - -**2. Outage rates: meaning and modeling** - -The concept of outage rate is not always clearly distinguished from the notion of failure rate, to which it is closely related. - -Outage rates OR represent the average **proportion** of time during which a plant is unavailable (for instance, OR = 5.2%). - -Failure rates FR represent the average **number** of outages **starting** during a period of time of a given length (for instance, FR = 1.5 per year). If the time step is short enough (typically one day, which is the value used in Antares), the failure rates are always lower than 1 (for instance, FR = (1.5 / 365) per day). - -When this condition is met and if the physical outage process can be modelled by a Poisson process, failure rates can be interpreted as probabilities. - -In Antares the following relation between failure rates FR, outage rates OR and outage durations OD is used: - -**
    FR = OR / [OR+ OD \* ( 1 – OR )]
    ** - -To determine whether a plant available on day D is still available on day D+1, the Antares stochastic generator therefore makes draws based on the failure rates equivalent to the data provided in the form of outage rates and outage durations. - -Since two processes may be described in the GUI, consecutive draws are made for each process so as to determine whether: - -- An outage of the first category begins (it will last for the specified duration) -- An outage of the second category begins (it will last for the specified duration) -- No outage occurs, the plant is still available on D+1 - -Whether to describe the "planned outage" process as a random process or not depends of the kind of data at hand, which is often related to the horizon of the studies to carry out: when actual overhauls plans are known, the PO rates can be set at 1 when the plant is deemed to be unavailable and to zero on the other days. - -For long term studies in which only general patterns are known, season-, month- or week- modulated rates and duration may be used to describe the "planned" process as a stochastic one. Another possible use of the model is to incorporate the overhauls plans in the "nominal capacity modulation" array, and consider the stochastic "planned outage" processor as a simulator for a second modality of forced outage (longer or shorter than the main component) - -**NOTE:** _Once the outage duration and outage rate are defined, the failure rate is completely determined. For the sake of clarity, the Antares GUI displays still another parameter often used in reliability analysis, which is the MTBF (Mean Time Between Failure). Relations between MTBF, FR and OR are:_ - -_**
    FR= 1 / ( MTBF+1 ) OR = OD / ( MTBF+OD )
    **_ - -**NOTE:** _When two stochastic processes of outages (forced and planned, or forced-type-1 and forced-type-2) are used, the overall resulting outage rate OOR is not equal to the sum of the two rates FOR and POR. Instead, the following relation holds:_ - -_**
    OOR = ( FOR + POR – 2\*FOR\*POR ) / (1 - FOR\*POR)
    **_ - -_The explanation of this formula lies in the definition of the different outages rates:_ - -_Over a long period of operation, FOR represents the ratio of the time spent in forced outages to the overall time not spent in planned outages._ - -_Likewise, POR represents the ratio of the time spent in planned outages to the overall time not spent in forced outages._ - -_OOR represents the ratio of the time spent in either forced or planned outages to the overall operation period._ - -_The period of operation can be broken down into three categories of hours:_ - -_F hours spent in forced outages_ - -_P hours spent in planned outages_ - -_A hours of availability_ - -_The following relations hold and explain the previous formula:_ - -_FOR = F/(A+F)_ - -_POR=P/(A+P)_ - -_OOR=(F+P)/(A+F+P)_ - -**3. Planned Outages Minimum and Maximum Numbers** - -In the description given so far regarding how outages are modeled, no true difference was made between "forced" and "planned" outages, i.e. both relied on unconstrained random draws. This is satisfactory only if the process to model through the "planned" data is actually little constrained, or not at all. - -In all other occurrences, it makes sense to define a general framework for the maintenance schedule. In Antares this is defined at the cluster scale by two specific 365-day arrays: - -
    PO Min Nb and PO Max Nb.
    - -These parameters are used by the time-series generator as constraints that **cannot be violated**, regardless of the raw outcome of regular random draws. To meet these constraints, the generator may have to anticipate or delay "planned" outages yielded by the primary random draws stage. If data regarding planned outage rates and planned outage Max and Min numbers are not consistent, the Max and Min Numbers take precedence. - -_Examples (for simplicity'sake, they are described here with only one value instead of 365):_ - -_Cluster size = 100 PO rate =10% PO Min Nb=0 PO Max Nb= 100_ - -- _Actual number in [0,100], average = 10, wide fluctuations (unconstrained)_ - -_Cluster size = 100 PO rate =10% PO Min Nb=7 PO Max Nb= 11_ - -- _Actual number in [7,11], average = 10 (to remain within the bounds, some outages will be anticipated, while others will be delayed)_ - -_Cluster size = 100 PO rate =0% PO Min Nb=10 PO Max Nb= 10_ - -- _Actual number =10 (to remain within the bounds, outages are set up even if none come from random draws)_ - -## Time-series analysis (thermal) - -The stochastic generator for time-series of available dispatchable power generation needs to be given assumptions regarding forced & planned outages rates & durations. Depending on the quality and quantity of statistics at hand, these estimates can be either described as "flat" (same constant values used from the beginning to the end of the year) or as more or less modulated signals, with the possibility of choosing different values for each day of the year. - -Different ways can be considered to work out values for FOR,POR,FOD,POD from historical data regarding outages. For any (family of) plant(s) to study, notations have to be defined with respect to the "calendar accuracy" chosen by the user. For the sake of clarity, assume from now on that the user wants to assess weekly rates and durations, that is to say: describe the whole year with 52 values for rates and durations, for both forced and planned outages (within any given week, identical values will therefore be assigned to the seven days of the week). - -With the following notations: - -- D(w) = Overall cumulated statistical observation time available for week (w) - for instance, for w = 1= first week of January : D(w) = 3500 days coming from 10 years of observation of 50 identical plants - -- Df(w) = Within D(w), overall time spent in forced outages, either beginning during week w or before (for instance , Df(1) = 163 days) - -- Dp(w) = Within D(w), overall time spent in planned outages, either beginning during week w or before (for instance, Dp(1) = 22 days) - -- Kf(w) = Number of forced outages beginning during week (w) - (for instance, Kf(1) = 26) - -- Kp(w) = Number of planned outages beginning during week (w) - (for instance, Kp(1) = 3) - -- FOT(w) = Overall cumulated time (expressed in days) spent in forced outages beginning during week (w) (for instance, FOT(1)= 260) - Note that if outages last more than one week FOT(w) necessarily includes days from weeks w+1, w+2,… - -- POT(w) = Overall cumulated time (expressed in days) spent in planned outages beginning during week (w) (for instance, POT(1) = 84) - Note that if outages last more than one week POT(w) necessarily includes days from weeks w+1, w+2,… - -The following formulas can be used : - -**FOD (w) = FOT(w) / Kf(w)** - -**POD (w) = POT(w) / Kp(w)** - -**FOR(w) = FOD(w) / [FOD(w) + ( (D(w) - Dp(w)) / Kf(w))]** - -**POR(w) = POD(w) /[POD(w) + ( (D(w) - Df(w))) / Kp(w))]** - -_For the examples given above, the estimated parameters would therefore be :_ - -_FOD(1) = 10 (days)_ - -_POD(1) = 28 (days)_ - -_FOR(1) = 0.0695 # 7 %_ - -_POR(1) = 0.0245 # 2.5 %_ - -_These values should eventually (using the GUI or other means) be assigned to the first seven days of January._ - -## Time-series generation and analysis (hydro) - -The stochastic hydro generator assesses monthly time-series of energies, based on the assumption that they can be modeled by Log Normal variables. The values generated are interpreted as monthly amounts of hydro energies generated (sum of Run of River – ROR – and hydro storage – HS) or as amounts of hydro inflows, depending on the modeling chosen for the area (straightforward estimate of energies generated or explicit management of reservoirs). - -The historical data to work from depend on the kind of modeling chosen (statistics of monthly generation in the first case, or statistics of monthly inflows in the second case). - -In both cases, assuming that a large number of historical time-series of energies are available, the rationale of the assessment of parameters is the following (from now on, "energies" mean either "ROR and HS energies generated" or "inflows to ROR and HS"), - -1. For each area n, build up annual energy time-series **A(n)** by aggregation of the original monthly energy time-series **M(n)**. For each pair of areas (n,m) , assess the correlation **R(n,m)** between the random variables **Log(A(n))** and **Log(A(m))**. Expressed in percentage, matrix **R** should be used to fill out the "spatial correlation tab" of in the active window "hydro" - -2. For each area n, build up two monthly time-series derived from the original array **M(n)**, by proceeding as follows. Assuming that **M(n)** has K elements (for instance, K= 180 if 15 years of statistics are available): - - - **M'(n)** = time-series of K-1 elements obtained by deleting the first element of the time-series Log(M(n)) - - **M''(n)** = time-series of K-1 elements obtained by deleting the last element of the time-series Log(M(n)) - - Assess the correlation **IMC(n)** between the random variables **M'(n)** and **M''(n)**. This value (lying in [-1,1]) should be used to fill out the field "inter-monthly correlation value" of the "local data" tab in the "hydro" active window. - -3. For each area n, build up 12 monthly energy time-series derived from the original array **M(n)** by extracting from **M(n)** the values related to each month of the year (**M1(n)**= time-series of energies in January,…, **M12(n)** = time-series of energies in December.) - - Assess the expectations and standard deviations of the 12 random variables **M1(n)** ,…, **M12(n)**. These values should be used to fill out the fields "expectation" and "std deviation" of the "local data" tab in the "hydro" active window. - - Aside from expectation and standard deviations, minimum and maximum bounds can be freely set on the monthly overall energies (ROR + HS). Whether to assess these bounds by examination of historical data or on the basis of other considerations depends on the context of the studies to carry out. - -4. For each area n, extract from the 12 monthly overall energy time-series **M1(n) ,…, M12(n)** the contribution of the 12 monthly time-series of ROR energies **R1(n),…, R12(n)**. - - Assess the expectations of the 12 random variables **R1(n)/M1(n),…., R12(n)/M12(n)** . These values should be used to fill out the fields "ROR share" of the "local data" tab in the "hydro" active window. - -[^decay]: Obtained by the generation of purely exponentially autocorrelated values (parameter \\(\theta\\) ) followed by a moving average transformation (parameter \\(\mu\\) ). \\(\theta\\) and \\(\mu\\) should be carefully chosen so as to accommodate at best the experimental data at hand. If meaningful historical data are available, this identification may be directly made using the Antares time-series analyzer. \ No newline at end of file diff --git a/docs/reference-guide/07-kirchhoffs_constraint_generator.md b/docs/reference-guide/07-kirchhoffs_constraint_generator.md deleted file mode 100644 index 91cc58469a..0000000000 --- a/docs/reference-guide/07-kirchhoffs_constraint_generator.md +++ /dev/null @@ -1,49 +0,0 @@ -# Kirchhoff's Constraint Generator - -Binding Constraints introduced in [Active windows](04-active_windows.md) can take many forms (hourly, daily, weekly), involve flows or thermal generated power, etc. Sets of binding constraints of special interest are those which can be used to model and enforce Kirchhoff's second law on the AC flows. - -In other words, it is possible to make Antares work as a genuine DC OPF, provided that consistent binding constraints are written down for each cycle belonging to any cycle basis of the graph made out from all AC components of the power system (V vertices, E edges). - -The declaration of binding constraints can be made manually through the regular GUI. However, it is preferable not to carry out this task that way because there are many different possible formulations, among which some are better than others: - -- In a fully connected graph (V, E), there are as many binding constraints to write down as there are cycles in any cycle basis of the graph, which amounts to (E+1-V). The number of different possible basis is equal to that of spanning trees, which can be assessed by the Kirchhoff's theorem [^15] - -- Among all cycle basis, some should be preferred to others because they lead to a sparser constraint matrix. - -To get around this issue, the KCG is an autonomous Antares module (much like the time-series analyzer) which automatically instantiates a set of adequate binding constraints that will enforce Kirchhoff's law on the AC subgraph of the power system. The graph cycle basis associated with the generated constraints is optimal, in that sense that it leads to a constraint matrix as sparse as possible. -To achieve that, the KCG implements an efficient algorithm yielding a minimal cycle basis [^16] and, for all cycles of the chosen basis, generates constraints of the form: - -$$c= 1, ..., C : \sum_{l \in C}{sign(l,c)F_lZ_l} = 0$$ - -Where \\(Z_l\\) are the impedances (parameters) and \\(F_l\\) are the flows (variables). - -Beyond this basic purpose, the KCG is meant to provide additional modeling capacities, so as to allow the representation of two important phenomena: - -- As a rule, the power system graph represented in Antares in not fully detailed, it is usually more a "backbone" approximation, in which "vertices" are not equivalent to individual bus-bars. More likely, vertices of the graph stand for whole regions, or even countries: as a consequence, it is highly possible that when all Areas/Vertices have a zero-balance (neither import, nor export), there are real physical flows between them, so-called "loop flows". If assessments of the level of these loop flows are available (and filled out as link input data), the KCG may include them (on user's request) in the binding constraints formulation, which becomes: - -$$c= 1, ..., C : \sum_{l \in C}{sign(l,c)F_lZ_l} = \sum_{l \in C}{sign(l,c)\varphi_lZ_l}$$ - -- To mitigate the effects of actual loop flows, or more generally to allow the transmission assets to give the maximum of their potential, the power system may include components such as phase-shifting transformers, whose function can be modeled by changing the formulation of the binding constraints. Provided that estimates of the shifting capacities (\\(Y_l^-\\), \\(Y_l^+\\)) of the installed PST are known and filled out in the link data section, the KCG will (on user's request) automatically reformulate the binding constraints as: - -$$c= 1, ..., C : Y_c^- + \sum_{l \in C}{sign(l,c)\varphi_lZ_l} \leq \sum_{l \in C}{sign(l,c)F_lZ_l} \leq Y_c^+ + \sum_{l \in C}{sign(l,c)\varphi_lZ_l}$$ - -with: - -$$Y_c^- = \sum_{l \in C}{Min(sign(l,c)Y_l^-, sign(l,c)Y_l^+)}$$ - -$$Y_c^+ = \sum_{l \in C}{Max(sign(l,c)Y_l^-, sign(l,c)Y_l^+)}$$ - -Besides, the KCG takes into account the fact that the "best estimates" of all critical data (loop flows, phase-shifting ratings, or even impedances) may vary in time: In such cases, the KCG formulates as many different binding constraints as necessary to model this operating context diversity, and relax them when appropriate (by setting the right hand sides of the equation to +/- infinite) - -From a practical standpoint, assessments of \\(Y^-, Y^+\\) should be derived from knowledge about the actual components installed on the grid, while \\(Z_l\\) and \\( \varphi_l \\) can be estimated by various methods. - -In addition to the previous functionalities, the KCG's GUI also includes the following options: - -- Choice of a specific period of time for which the constraints should be applied, while completely relaxed at other moments -- Before actual generation of binding constraints, preview of the "minimal length" spanning tree used as starting point for the optimal basis algorithm (left column of the table – links displayed with "0" do not belong to the tree) -- Before actual generation of binding constraints, preview of the "optimal cycle basis" used as starting point for constraints generation (right column of the table – links displayed with "n" appear in n different cycles of the basis) - - -[^15]: The number of spanning trees is equal to the absolute value of any cofactor of the graph incidence matrix - -[^16]: Mehlhorn K., Michail D. (2005) _Implementing Minimum Cycle Basis Algorithms_. In: Experimental and Efficient Algorithms. WEA 2005. Lecture Notes in Computer Science, vol 3503. diff --git a/docs/reference-guide/08-miscellaneous.md b/docs/reference-guide/08-miscellaneous.md deleted file mode 100644 index 93796f6183..0000000000 --- a/docs/reference-guide/08-miscellaneous.md +++ /dev/null @@ -1,559 +0,0 @@ -# Miscellaneous - -## Antares at one glance - -This section gives a summary of the whole simulation process followed by Antares in Economy simulations (Adequacy being simplified variant of it): - -1. Load or Generate [stochastic generators] Time-series of every kind for all system areas - -2. For each Monte-Carlo year, pick up at random or not [scenario builder] one time-series of each kind for each area/link - -3. For each area and each reservoir: - - 1. Split up the annual overall hydro storage inflows into monthly hydro storage generation, taking into account reservoir constraints, hydro management policy and operation conditions (demand, must-run generation, etc.) [heuristic + optimizer] - - 2. For every day of each month, break down the monthly hydro energy into daily blocks, taking into account hydro management policy and operation conditions (demand, must-run generation, etc.) [heuristic + optimizer]. Aggregate daily blocks back into weekly hydro storage energy credits (used if the final optimization is run with full weekly 168-hour span) - - 3. For each week of the year (daily/weekly hydro energy credits are now known in every area), run a three-stage 168-hour optimization cycle (or seven 24-hour optimizations, if the optimization preference is set to "daily"). This aim of this cycle is to minimize the sum of all costs throughout the optimization period. This sum may include regular proportional fuel costs, start-up and no-load heat costs, unsupplied and spilled energy costs, and hurdle costs on interconnection. The solution has to respect minimum and maximum limits on the power output of each plant, minimum up and down durations, as well as interconnection capacity limits and "binding constraints" at large (which may be technical – e.g. DC flow rules – or commercial – e.g. contracts). Note that an accurate resolution of this problem requires mixed integer linear programming (because of dynamic constraints on thermal units). A simplified implementation of this approach is used when the advanced parameter "Unit commitment" is set on "accurate". This high quality option may imply long calculation times. This is why, when "Unit commitment" is set on "fast", Antares makes further simplifications that save a lot of time (starting costs are not taken into account within the optimization step but are simply added afterwards, units within a thermal cluster are subject to starting up/shutting down constraints more stringent than the minimum up/down durations). In both cases, the general optimization sequence is as follows: - - i. Minimization of the overall system cost throughout the week in a continuous relaxed linear optimization. Prior to the optimization, an 8760-hourly vector of operating reserve R3 (see next section) may be added to the load vector (this will lead in step (ii) to identify plants that would not be called if there were no reserve requirements. Their actual output will be that found in step (iii), wherein the load used in the computations takes back its original value) - - ii. So as to accommodate the schedule resulting from (i), search for integer values of the on/off variables that satisfy the dynamic constraints with the smallest possible cost increase. - - iii. Take into account the integer variables found in (ii) and solve again the optimal schedule problem for the week. - -## Operating reserves modeling - -Many definitions may be encountered regarding the different operating reserves (spinning / non spinning, fast / delayed, primary-secondary-tertiary, frequency containment reserve – frequency restoration reserve – replacement reserve, etc.). - -Besides, all of them need not be modeled with the same level of accuracy in a simulator such as Antares. Furthermore, the best way to use the concept is not always quite the same in pure Adequacy studies and in Economy studies. - -Several classes of reserves may therefore be used in Antares; how to use them at best depend on the kind and quality of operational data at hand, and on the aim of the studies to carry out; though all kinds of reserves may always be defined in the INPUT dataset, the set of reserves that will effectively be used depends on the kind of simulations to run. Note that any or all classes of reserves may be ignored in a given simulation (without being removed from the INPUT dataset) by setting the matching "optimization preference" to "ignore reserve X": - -- **Pre-allocated reserve on dispatchable thermal plants (R0)**
    - This reserve (which corresponds to the parameter "spinning" attached to the thermal plants) is expressed as a percentage of the nominal capacity of the plants. It is simply used as a derating parameter: for instance, a 1000 MW plant with a 2.5% spinning parameter will not be able to generate more than 975 MW. It is important to notice that, if the plant is not scheduled on, it will NOT contribute to the spinning reserve (to be effectively available, the 25 MW of reserve would need the plant to be started). This first class of reserve is available for **Adequacy** as well as for **Economy**. - -- **Day-ahead reserve (R3):**
    - This reserve is available in **Adequacy** and **Economy** simulations, with the following meaning: - "For any day D, to be able to accommodate last-minute random variations of the expected demand and/or generation (as they were seen from day D -1), a certain amount of power (R3) should be ready to be available at short notice". -
    - In actual operating terms, R3 is a complex (spinning/non-spinning) mix as well as (hydro/thermal) mix. It may involve or not part of the primary and secondary power/frequency regulation reserves. R3 may represent as much as the overall amount of frequency containment reserve, frequency restoration reserve and replacement reserve required for operation on day D, as seen from day D-1. -
    - In the simulations, R3 is construed as a "virtual" increase of the load to serve, which influences the optimal unit commitment and dispatch (because of minimum stable power levels and minimum On / Down times). - -**IMPORTANT:** - -The optimization makes sure that, should the need arise, reserve R3 will actually be available where it is needed **BUT** there is no commitment regarding whether this service should be provided by an increase of local generation, a decrease of exports or even an increase of imports: the optimizer will choose the mix leading to the minimal cost for the system. - -Note that this "standard" feature of Antares makes it possible to assess the potential value of keeping some headroom in interconnections for the purpose of transferring operating reserves, when "remote" reserves are less expensive than domestic ones. - -The table below gives an overview of the different reserves available in Antares - -| | _Economy_ | _Adequacy_ | -|:---:|:---:|:---:|:---:| -| _R0_ | _Yes_ | _Yes_ | -| _R3_ | _Yes_ | _Yes_ | - - -## The heuristic for seasonal hydro pre-allocation - - -This heuristic, first introduced in broad terms in [Active windows](04-active_windows.md), chapter "hydro", is fully detailed in this paragraph. - -Basically, the seasonal hydro pre-allocation process comprises two stages carried out two times -(first time: monthly scale; second time: daily scale). - -- Stage 1: Definition of an allocation ideal modulation profile, which may be based (or not) on local and/or - remote load profiles. -- Stage 2: Mitigation of the previous raw profile to obtain a feasible hydro ideal target, - compatible as much as possible with reservoir rule curves. - -The description given hereafter makes use of the following local notations, -not be confused with those of the document "optimization problem formulation" -(dedicated to the optimal hydro-thermal unit-commitment and dispatch problem): - -- \\(Z\\) Number of Areas (zones \\(z\\)) in the system -- \\(M_{zh}\\) Hourly time-series of cumulated must-generation of all kinds for zone \\(z\\) -- \\(M_{zd}\\) Daily time-series of cumulated must-generation of all kinds for zone \\(z\\) (sum of \\(M_{zh}\\)) -- \\(M_{zm}\\) Monthly time-series of cumulated must-generation of all kinds for zone \\(z\\) (sum of \\(M_{zh}\\)) -- \\(M_{z.}\\) Either \\(M_{zd}\\) or \\(M_{zm}\\), relevant time index "." is defined by the context -- \\(L_{z.}\\) Time-series of "natural" load for zone \\(z\\) -- \\(A\\) Inter-area hydro-allocation matrix (dimension_ \\(x Z\\) ) \\(A_{uv}\\) is a weight given to the load -of area \\(u\\) in the definition of the monthly and daily primary hydro generation target of area \\(v\\) - Extreme cases are: - - - **A is the identity matrix** - The hydro storage energy monthly and weekly profiles of each zone \\(z\\) depend only on the local demand and - must-run generation in \\(z\\) - - **A has a main diagonal of zeroes** - The hydro storage energy monthly and weekly profiles of each zone \\(z\\) do not depend at all on the local - demand and must-run generation in \\(z\\) -- \\(L_{z.}^+\\) Time-series of "net" load for zone \\(z\\), defined as: \\(L{z.}^+ = L{z.} - M{z.}\\) -- \\(L_{z.}\\) Time-series of "weighted" load for zone \\(z\\), defined as:_ \\(L_{z.} = A^t L_{z.}^+\\) - -All following parameters are related to the generic zone \\(z\\): - -- \\(\alpha\\) "inter-monthly generation breakdown" parameter - -- \\(\beta\\) "inter-daily generation breakdown" parameter - -- \\(j\\) "follow-load" parameter - -- \\(\mu\\) "reservoir-management" parameter - -- \\(S\\) Reservoir size - -- \\(\overline{S_d}\\) Reservoir maximum level at the end of day d, expressed as a fraction of \\(S\\) (rule curve) - -- \\(\underline{S_d}\\) Reservoir minimum level at the end of day d, expressed as a fraction of \\(S\\) (rule curve) - -- \\(S_0\\) Reservoir initial level at the beginning of the first day of the "hydro-year" - -- \\(I_d\\) Natural inflow of energy to the reservoir during day d - -- \\(I_m\\) Natural inflow of energy to the reservoir during month m (sum of \\(I_d\\) - -- \\(\overline{W_d}\\) Maximum energy that can be generated on day d (standard credit) - - All following variables, defined for both stages, are related to the generic zone: - -- \\(S_d^k\\) Reservoir level at the end of day d, at the end of stage k of pre-allocation - -- \\(S_m^k\\) Reservoir level at the end of month m, at the end of stage k of pre-allocation - -- \\(O_d^k\\) Overflow from the reservoir on day d, at the end of stage k of pre-allocation (inflow in excess to an already full reservoir) - -- \\(W_d^k\\) Energy to generate on day d, at the end of stage k of pre-allocation - -- \\(W_m^k\\) Energy to generate on month m, at the end of stage k of pre-allocation - - -Following variables and parameters are local to linear optimization problems \\(M\\) & \\(D(m)\\) -solved within the heuristic. For the sake of clarity, the same generic index is used for all time steps, -knowing that in \\(M\\) there are 12 monthly time-steps, while in \\D(m)t\\) there are from 28 to 31 daily -time-steps. Costs \\(\gamma_{Var}\\) given to these variables are chosen to enforce a logical hierarchy -of penalties (letting the reservoir overflow is worse than violating rule curves, which is worse than deviating -from the generation objective assessed in stage 1, etc.) - -- \\(Y\\) Generation deficit at the end of the period, as compared to the objective aimed at - -- \\(O_t\\) Overflow from the reservoir on time step \\(t\\) - -- \\(G_t, \overline{G_t}\\) Optimal generation and maximum generation on time step \\(t\\) - -- \\(T_t\\) Generation objective assessed in the first stage, for time step t ( \\(W_m^1\\) or \\(W_d^1\\)) - -- \\(S_t, \overline{S_t}, \underline{S_t}\\) Optimal stock level, maximum level, minimum level at the end of time step \\(t\\) - -- \\(I_t\\) Natural inflow on time step \\(t\\) - -- \\(D_t\\) Deviation (absolute difference) between target reached and initial aim - -- \\(\Delta\\) Maximum deviation throughout the period - -- \\(V_t^+\\) Amplitude of the violation of the upper rule curve at time step \\(t\\) - -- \\(V_t^-\\) Amplitude of the violation of the lower rule curve at time step \\(t\\) - -- \\(Y\\) Maximum violation of lower rule curve throughout the period - - -**General heuristic for each zone** - -_Begin_ - -$$if (not.\mu) : \{ S \leftarrow \infty ; \underline{S_d} \leftarrow 0; \overline{S_d}; S_0 \leftarrow S/2 \}$$ - -_M1:_ - -$$if (j \text{ and } \mu) : \text{for } m\in [1, 12]: W_m^1 \leftarrow \frac{L_m^{\alpha}.(\sum_{m}{I_m})}{(\sum_{m}{L_m^{\alpha}})}$$ - -$$else: \text{for } m\in [1, 12]: \{W_m^1 \leftarrow I_m\}$$ - - -_M2:_ - -$$\text{for } m\in [1, 12]: W_m^2 \leftarrow \text{Solution of linear problem M}$$ - -_D1:_ - -$$if (j): \text{for } d\in [1, 31]: W_d^1 \leftarrow \frac{L_d^{\beta}. (W_m^2)}{(\sum_{d\in m}{L_d^{\beta}})}$$ - -$$else: \text{for } d\in [1, 31]: W_d^1 \leftarrow \frac{I_d . (W_m^2)} {(\sum_{d\in m}{I_d})}$$ - -_D2:_ - -$$\text{for } m \in [1, 12]: W_{d\in m}^2 \leftarrow \text{Solution of linear problem D(m)}$$ - -_End_ - -Note: In the formulation of the optimal hydro-thermal unit-commitment and dispatch problem (see dedicated document), the reference hydro energy __HIT__ used to set the right hand sides of hydro- constraints depends on the value chosen for the optimization preference "simplex range" and is defined as follows: - -- Daily : for each day **d** of week \\(\omega\\) : \\(HIT = W_d^2\\) -- Weekly : for week \\(\omega\\): \\(HIT = \sum_{d\in \omega}{W_d^2}\\) - -**Optimization problem M** - -$$\min_{G_t, S_t, ...}{\gamma_{\Delta}\Delta + \gamma_Y Y + \sum_{t}{(\gamma_D D_t + \gamma_{V+} V_t^+ + \gamma_{V-} V_t^-)}}$$ - -s.t - -$$S_t \geq 0$$ - -$$S_t \leq S$$ - -\\(S_t + G_t - S_{t-1} = I_t\\) (see note [^monthly_allocation]) - -$$\sum_{t}{G_t} = \sum_{t}{T_t}$$ - -$$G_t - D_t \leq T_t$$ - -$$G_t + D_t \geq T_t$$ - -$$V_t^- + S_t \geq \underline{S_t}$$ - -$$V_t^+ - S_t \geq -\overline{S_t}$$ - -$$Y - V_t^- \geq 0$$ - - -**Optimization problems \\(D(m)\\)** - -$$\min_{G_t, S_t, ...}{\gamma_{\Delta}\Delta + \gamma_Y Y + \sum_{t}{(\gamma_D D_t + \gamma_{V-} V_t^- + \gamma_{O} O_t + \gamma_S S_t)}}$$ -s.t - -$$S_t \geq 0$$ - -$$S_t \leq S$$ - -$$G_t \geq 0$$ - -$$G_t \leq \overline{G_t}$$ - -\\(S_t + G_t + O_t - S_{t-1} = I_t\\) (see note [^daily_allocation]) - -\\(\sum_{t}{G_t + Y} = \sum_{t}{T_t} + Y_{m-1}\\) (value of Y previously found in solving **\\(D(m-1)\\)**) - -$$G_t - D_t \leq T_t$$ - -$$G_t + D_t \geq T_t$$ - -$$\Delta - D_t \geq 0$$ - -$$V_t^- + S_t \geq \underline{S_t}$$ - -$$Y - V_t^- \geq 0$$ - -## Conventions regarding colors and names - -- Names for areas, thermal plants, etc. - Name length should not exceed 256 characters. - Characters must belong to: - { A-Z , a-z , 0-9 , - , \_ , ( , ) , & , comma , space } - - -- Colors: - After being entered in the GUI, some numeric fields can see their color change. The meaning of that is: - - Turn to red: invalid value. Saving the study in this state is possible, but the field will have to be corrected at some point in the future. Should the simulator be launched on the dataset, it will detect an error and stop. - - - Turn to orange: value is valid, though unusual (user may want to double-check data). - - -- Abbreviations : - - Fields requiring to be filled out with "YES" or "NO" can alternatively accept "Y" , "1" or "N" , "0" - - Fields requiring to be filled out with "ON" or " OFF" can alternatively accept "true", "1" or "false", "0" - - Fields requiring to be filled out with "annual" or "monthly" can alternatively accept "a" or "m" - - Fields requiring to be filled out with: "Raw" ,"Detrended"," Beta", "Normal", "Uniform", " Gamma", " Weibull" can alternatively accept: "R", "D", " B", "N", "U", "G", "W" - - -## Definition of regional districts - -Typical uses of the "district" feature are: - -1) On a large system, define an "all system" zone to get an overall synthesis on all the system nodes - -2) In a study involving different countries modeled by different regions, define "country" macro-nodes to aggregate regional results to the national level. - -3) In a study using some specific modeling such as PSP modeling with fake nodes, define a local cluster involving all the relevant real and fake nodes to simplify the edition of results. - -Hereafter is described the process to follow to bypass the GUI for the definition of districts.
    -It is based on the edition of a special "sets.ini" file. - -**IMPORTANT :** -- Make sure that the sets.ini file is ready for use before opening the Antares study. Attempts to update the sets.ini file while the study is opened will not be effective. -- Definition of meaningless districts (references to nodes that do not exist,…) will generate warnings in the GUI log files. - -**HOW TO UPDATE / CREATE the file** : Use Notepad (or equivalent) - -**WHERE TO FIND / STORE THE FILE** : INPUT/areas/sets.ini - -**PRINCIPLE:** - -The file is divided in consecutive sections, one for each district to define. - -A section contains: - -a) A header line that gives its name to the district. The header syntax is: `[district_name]` - To avoid confusion with the real area names, the results regarding this macro-area will later be found in the OUTPUT files under a name bearing the prefix "@", i.e. `@district_name` - -b) A list of parametrized building rules to be processed in their apparition order. - The different elementary rules are: - += area\_name : add the area "area\_name" to the district
    - -= area\_name : remove the area "area\_name" from the district
    - apply-filter = add-all : add all areas to the district
    - apply-filter = remove-all : remove all areas (clear the district) - -c) A special "output" parameter that defines whether the results for the district will actually be computed or not -(this latter option allows inactivating parts of the sets.ini without altering the file). - The syntax is: `output=false` or `output= true`. - -**EXAMPLES OF SETS.INI FILES** - -a) File defining a single district named "set1" involving three areas named "area1, area3, area42": - -```ini -[set1] -+ = area1 -+ = area3
    -+ = area42 -output = true -``` - -b) File defining a district gathering all areas but five: - -```ini -[most of the system -apply-filter = add-al -- = country -- = neighbour -- = fake antenna 1 -- = region -- = region 3 -output = true -``` -c) File defining two districts, the current simulation will ignore the second one: - -```ini -[All countries] -apply-filter= add-all -output=true - - -[All but one] -apply-filter = add-all --= special region 12 -output=false -``` - -## The Annual System Cost Output file - -In addition to the general files introduced in [Output Files](05-output_files.md), the Output folder of each economic or adequacy simulation includes, at its root, a file "Annual\_System\_Cost.txt" It presents the metrics of a global Monte-Carlo variable further denoted ASC. - -The value of ASC for any given simulated year is defined as the sum, over all areas and links, of the annual values of the area-variable "OV.COST" and of the link-variable "HURD. COST". - -The metrics displayed in the "Annual system cost" file take the form of four values: - -- Expectation EASC - -- Standard deviation SASC - -- Minimum LASC - -- Maximum UASC - -As with all other random variables displayed in the Antares Output section, the computed standard deviation of the variable can be used to give a measure of the confidence interval attached to the estimate of the expectation. For a number of Monte-Carlo years N, the law of large numbers states for instance that there is a 95 % probability for the actual expectation of ASC to lie within the interval: - -
    **EASC +/- 1.96 (SASC / sqrt(N))**
    - -There is also a 99.8 % probability that it lies within the interval: - -
    **EASC +/- 3 (SASC / sqrt(N))**
    - -## The "export mps" optimization preference - -This preference can be set either on "false" or "true". Choosing either value does not influence the way calculations are carried out, nor does it change their results. - -The effect of this preference is that, if the "true" value is selected, Antares will produce and store in the simulation output folder two files for every linear problem solved in the whole simulation. - -The first file ("problem" file) contains a standardized description of the mathematical problem solved by Antares' built-in linear solver. The format standard used in this file is known as "mps". - -The second file ("criterion" file) contains the value of the optimal (minimum) value found for the objective function of the optimization problem (overall system cost throughout a day or a week). - -All commercial as well as Open Source linear solvers are able to process mps files. As a consequence, tests aiming at comparing Antares' solver with other commercial solutions can be easily carried out: all that has to be done is to submit the mps problem to the solver at hand and measure its performances (calculation time, criterion value) with those of Antares. - -Note that this kind of comparisons brings no information regarding the quality of the physical modelling on which the simulation is based. It is useful, however, to gather evidence on mathematical grounds. - -File names are structured as follows: - -- When the optimization preference "simplex range" is set on "week":
    - Problem-MC year-week number-date-time.mps
    - Criterion-MC year-week number-date-time.txt - -- When the optimization preference "simplex range" is set on "day":
    - Problem-MC year-week number-date-time-day number.mps
    - Criterion-MC year-week number-date-time-day number.txt - -Besides, each economic problem generally demands to be solved through two successive optimization problems. Files related to these two problems will bear almost the same name, the only difference being the "time" suffix. The files related to the second optimization (final Antares results) are those that bear the latest tag. - -Finally, it is possible that, on special occasions (very small files), the files attached to the two optimization rounds begin to be printed within the same second. In that case, an additional suffix is added before the mps or txt extension. - -**Note that:** - -- _The disk space used to store mps file is not included in the disk resources assessment displayed in the resources monitor menu._ - -- _The extra runtime and disk space resulting from the activation of the "mps" option may be quite significant. This option should therefore be used only when a comparison of results with those of other solvers is actually intended._ - -## The "Unfeasible Problems Behavior" optimization preference - -This preference can take any of the four values: - -Error Dry, Error Verbose, Warning Dry, Warning Verbose - -If "Error Dry" or "Error Verbose" is selected, the simulation will stop right after encountering the first mathematically unfeasible optimization (daily or weekly) problem. No output will be produced beyond this point. Should the dataset contain several unfeasible problems (i.e. regarding different weeks of different MC years), it is possible that successive runs of the same simulation stop at different points (if parallel computation is used, the triggering problem may differ from one run to the other). - -If "Warning Dry" or "Warning Verbose" is selected, the simulation will skip all mathematically unfeasible optimization (daily or weekly) problems encountered, fill out all results regarding these problems with zeroes and resume the simulation. The hydro reservoir levels used for resuming the simulation are those reached at the end of the last successful week. - -With "Dry" options no specific data are printed regarding the faulty problem(s). With "Verbose" options, the full expression of the faulty problem(s) is printed in the standard "mps" format, thus allowing further analysis of the infeasibility issue. - -## The "Reservoir Level Initialization" advanced parameter - -This parameter can take the two values "cold start" or "hot start". [default: cold start]. Simulations results may in some circumstances be heavily impacted by this setting, hence proper attention should be paid to its meaning before considering changing the default value. - -**General:** - -This parameter is meant to define the initial reservoir levels that should be used, in each system area, when processing data related to the hydro-power storage resources to consider in each specific Monte-Carlo year (see [Active windows](04-active_windows.md)). - -As a consequence, Areas which fall in either of the two following categories are not impacted by the value of the parameter: -- No hydro-storage capability installed -- Hydro-storage capability installed, but the "reservoir management" option is set to "False" - -Areas that have some hydro-storage capability installed and for which explicit reservoir management is required are concerned by the parameter. The developments that follow concern only this category of Areas. - -**Cold Start:** - -On starting the simulation of a new Monte-Carlo year, the reservoir level to consider in each Area on the first day of the initialization month (see [Active windows](#active-windows)) is randomly drawn between the extreme levels defined for the Area on that day. - -More precisely: - -- The value is drawn according to the probability distribution function of a "Beta" random variable, whose four internal parameters are set so as to adopt the following behavior: - Lower bound: Minimum reservoir level. - Upper bound: Maximum reservoir level - Expectation: Average reservoir level - Standard Deviation: (1/3) (Upper bound-Lower bound) - -- The random number generator used for that purpose works with a dedicated seed that ensures that results can be reproduced - [^17] from one run to another, regardless of the simulation runtime mode (sequential or parallel) - and regardless of the number of Monte-Carlo years to be simulated [^18]. - -**Hot Start:** - -On starting the simulation of a new Monte-Carlo year, the reservoir level to consider in each Area on the first day of the initialization month is set to the value reached at the end of the previous simulated year, if three conditions are met: - -- The simulation calendar is defined throughout the whole year, and the simulation starts on the day chosen for initializing the reservoir levels of all Areas. - -- The Monte-Carlo year considered is not the first to simulate, or does not belong to the first batch of years to be simulated in parallel. In sequential runtime mode, that means that year #N may start with the level reached at the end of year #(N-1). In parallel runtime mode, if the simulation is carried out with batches of B years over as many CPU cores, years of the k-th batch - [^19] may start with the ending levels of the years processed in the (k-1)-th batch. - -- The parallelization context (see [System requirements](#9-system-requirements)) must be set so as to ensure that the M Monte-Carlo years to simulate will be processed in a round number of K consecutive batches of B years in parallel (i.e. M = K\*B and all time-series refresh intervals are exact multiple of B). - -The first year of the simulation, and more generally years belonging to the first simulation batch in parallel mode, are initialized as they would be in the cold start option. - -**Note that:** - -- _Depending on the hydro management options used, the amount of hydro-storage energy generated throughout the year may either match closely the overall amount of natural inflows of the same year, or differ to a lesser or greater extent. In the case of a close match, the ending reservoir level will be similar to the starting level. If the energy generated exceeds the inflows (either natural or pumped), the ending level will be lower than the starting level (and conversely, be higher if generation does not reach the inflow credit). Using the "hot start" option allows to take this phenomenon into account in a very realistic fashion, since the consequences of hydro decisions taken at any time have a decisive influence on the system's long term future._ - -- _When using the reservoir level "hot start" option, comparisons between different simulations make sense only if they rely on the exact same options, i.e. either sequential mode or parallel mode over the same number of CPU cores._ - -- _More generally, it has to be pointed out that the "hydro-storage" model implemented in Antares can be used to model "storable" resources quite different from actual hydro reserves: batteries, gas subterraneous stocks, etc._ - -## The "Hydro Heuristic policy" advanced parameter - -This parameter can take the two values "Accommodate rule curves" or "Maximize generation". [default: Accommodate rule curves]. - -**General:** - -This parameter is meant to define how the reservoir level should be managed throughout the year, either with emphasis put on the respect of rule curves or on the maximization of the use of natural inflows. - -**Accommodate rule curves:** - -Upper and lower rule curves are accommodated in both monthly and daily heuristic stages (described page 58). In the second stage, violations of the lower rule curve are avoided as much as possible (penalty cost on \\(\Psi\\). higher than penalty cost on Y). This policy may result in a restriction of the overall yearly energy generated from the natural inflows. - -**Maximize generation:** - -Upper and lower rule curves are accommodated in both monthly and daily heuristic stages (described page 58). In the second stage, incomplete use of natural inflows is avoided as much as possible (penalty cost on Y higher than penalty cost on \\(\Psi\\)). This policy may result in violations of the lower rule curve. - -## The "Hydro Pricing mode" advanced parameter - -This parameter can take the two values "fast" or "accurate". [default: fast]. - -Simulations carried out in "accurate" mode yield results that are theoretically optimal as far as the techno-economic modelling of hydro (or equivalent) energy reserves is concerned. It may, however, require noticeably longer computation time than the simpler "fast" mode. - -Simulations carried out in "fast" mode are less demanding in computer resources. From a qualitative standpoint, they are expected to lead to somewhat more intensive (less cautious) use of stored energy. - -**General:** - -This parameter is meant to define how the reservoir level difference between the beginning and the end of an optimization week should be reflected in the hydro economic signal (water value) used in the computation of optimal hourly generated /pumped power during this week. - -**Fast:** - -The water value is taken to remain about the same throughout the week, and a constant value equal to that found at the date and for the level at which the week_ **begins** _is used in the course of the optimization. A value interpolated from the reference table for the exact level reached at each time step within the week is used ex-post in the assessment of the variable "H.COST" (positive for generation, negative for pumping) defined in [Output Files](05-output_files.md). This option should be reserved to simulations in which computation resources are an issue or to simulations in which level-dependent water value variations throughout a week are known to be small. - -**Accurate:** - -The water value is considered as variable throughout the week. As a consequence, a different cost is used for each "layer" of the stock from/to which energy can be withdrawn/injected, in an internal hydro merit-order involving the 100 tabulated water-values found at the date at which the week **ends**. A value interpolated from the reference table for the exact level reached at each time step within the week is used ex-post in the assessment of the variable "H.COST" (positive for generation, negative for pumping) defined in [Output Files](05-output_files.md). This option should be used if computation resources are not an issue and if level-dependent water value variations throughout a week must be accounted for. - -## The "Unit Commitment mode" advanced parameter - -This parameter can take the two values "fast" or "accurate". [default: fast]. - -Simulations carried out in "accurate" mode yield results that are expected to be close to the theoretical optimum as far as the techno-economic modelling of thermal units is concerned. They may, however, require much longer computation time than the simpler "fast" mode. - -Simulations carried out in "fast" mode are less demanding in computer resources. From a qualitative standpoint, they are expected to lead to a more costly use of thermal energy. This potential bias is partly due to the fact that in this mode, start-up costs do not participate as such to the optimization process but are simply added ex post. - -**General:** - -In its native form [^20], the weekly optimization problem belongs to the MILP (Mixed Integer Linear Program) class. The Integer variables reflect, for each time step, the operational status (running or not) of each thermal unit. Besides, the amount of power generated from each unit can be described as a so-called semi-continuous variable (its value is either 0 or some point within the interval [Pmin , Pmax]). Finally, the periods during which each unit is either generating or not cannot be shorter than minimal (on- and off-) thresholds depending on its technology. - -The Unit Commitment mode parameter defines two different ways to address the issue of the mathematical resolution of this problem. In both cases, two successive so-called "relaxed" LP global optimizations are carried out. In-between those two LPs, a number of local IP (unit commitment of each thermal cluster) are carried out. - -Besides, dynamic thermal constraints (minimum on- and off- time durations) are formulated on time-indices rolling over the week; this simplification brings the ability to run a simulation over a short period of time, such as one single week extracted from a whole year, while avoiding the downside (data management complexity, increased runtime) of a standard implementation based on longer simulations tiled over each other (illustration below). - -![Standard_Implementation](Standard_Implementation.png) - -![Antares_Implementation](Antares_Implementation.png) - -**Fast:** - -In the first optimization stage, integrity constraints are removed from the problem and replaced by simpler continuous constraints. - -For each thermal cluster, the intermediate IP looks simply for an efficient unit-commitment compatible with the operational status obtained in the first stage, with the additional condition (more stringent than what is actually required) that on- and off- periods should be exact multiple of the higher of the two thresholds specified in the dataset. - -In the second optimization stage, the unit commitment set by the intermediate IPs is considered as a context to use in a new comprehensive optimal hydro-thermal schedule assessment. The amount of day-ahead (spinning) reserve, if any, is added to the demand considered in the first stage and subtracted in the second stage. Start-up costs as well as No-Load Heat costs are assessed in accordance with the unit-commitment determined in the first stage and are added ex post. - -**Accurate:** - -In the first optimization stage, integrity constraints are properly relaxed. Integer variables describing the start-up process of each unit are given relevant start-up costs, and variables attached to running units are given No-Load Heat costs (if any), regardless of their generation output level. Fuel costs / Market bids are attached to variables representing the generation output levels. - -For each thermal cluster, the intermediate IP looks for a unit-commitment compatible with the integrity constraints in the immediate neighborhood of the relaxed solution obtained in the first stage. In this process, the dynamic thresholds (min on-time, min off-time) are set to their exact values, without any additional constraint. - -In the second optimization stage, the unit commitment set by the intermediate IP is considered as a context to use in a new comprehensive optimal hydro-thermal schedule assessment. The amount of day-ahead (spinning) reserve, if any, is added to the demand considered in the first stage and subtracted in the second stage. - -## The "Renewable Generation modeling" advanced parameter - -This parameter can take the two values “aggregated†or “clusterâ€. For a new study, it will default to cluster. For a legacy (Antares version <8.1.0) study it will default to aggregated. - -If the parameter is set to "aggregatedâ€, the user will have access to the Wind & Solar windows, but not the Renewable window. When the parameter is set to “cluster", the Renewable window will be available, but not the Wind nor the Solar windows. The data stored in the windows that are not available will always be conserved. However, only Renewable data (and not the wind and solar data) will be considered for the calculations when the parameter is set to “clusterâ€. And only the wind and solar data (and not the renewable data) will be considered for the calculations when the parameter is set to “aggregatedâ€. - -The Renewable window can be filled out with the different renewable clusters inside each node. Each renewable cluster needs to have a group specified or will default to the «Other RES 1» group. Production Timeseries can be filled out much like the Thermal production ones. Note that unlike thermal clusters, negative production values are allowed. The Renewable window is described in more details in the “4. Active Windows†section. In the Simulation window, only “Ready-made†timeseries can be selected for renewables for now. This should be modified in a future release. The MC scenario builder for Renewables works the same way as for Thermal Clusters. - -[^monthly_allocation]: In the first equation, \\(S_{t-1}\\) is either the initial stock \\(S_0\\) or the final stock of the previous year (hydro hot start) - -[^daily_allocation]: In the first equation, \\(S_{t-1}\\) is either the initial stock used in M or the final stock of the previous month (\\(D(m-1)\\) - -[^17]: As long as the System's list of Areas does not change - -[^18]:E.g. : if three playlists A,B,C are defined over 1000 years (A: years 1 to 1000, B: years 1 to 100, C: Years 13,42,57,112), initial reservoir levels in each Area are identical in the playlists' intersection (years 13,42,57) - -[^19]: If the playlist is full, these years have numbers # (k-1)B+1 ,…., #kB - -[^20]: Described in the note "Optimization Problems Formulation" diff --git a/docs/reference-guide/09-system_requirements.md b/docs/reference-guide/09-system_requirements.md deleted file mode 100644 index ebe54419a5..0000000000 --- a/docs/reference-guide/09-system_requirements.md +++ /dev/null @@ -1,87 +0,0 @@ -# System requirements - -## Operating system - -Antares\_Simulator code is cross-platform (Windows/Linux/Unix) and installation packages for various versions of these OS are available at: [_https://antares-simulator.org_](https://antares-simulator.org/) - -## Hard drive disk - -Installed alone, the Antares simulator does not require a lot of HDD space (less than 1 GB). Installation packages including companion tools (study manager, graph editor) are however significantly heavier. The proper storage of data (i.e. both Input and Output folders of Antares studies) may require a large amount of space. The disk footprint of any individual study mainly depends on: - -- The size of the power system modeled (number of Areas, Links, Thermal clusters, etc.) -- The number of ready-made Time-Series and the number of Time-Series to be generated at runtime and stored afterwards -- The activation of output filters (Geographic Trimming and / or Thematic Trimming) -- The number of Monte-Carlo years involved in the simulation session (if the storage of detailed year-by-year results is requested) -- The status of the "export mps" optimization preference - -At any moment, the amount of disk resources required for a simulation is accessible through the Tools/resources monitor menu. - -## Memory - -The amount of RAM required for a simulation depends on: - -- The size of the power system modeled (number of Areas, Links, Thermal clusters, etc.) -- The number of ready-made Time-Series and that of Time-Series to be generated at runtime -- The simulation mode (adequacy, economy with "fast" or "accurate" unit commitment) -- The execution mode (default or parallel) - -At any moment, the amount of RAM resources required for a simulation is accessible through the Tools/resources monitor menu. - -## Multi-threading - -The GUI of Antares and all I/O operations on Input / Output files automatically benefit from full multi-threading on the local machine's CPU cores. Multi-threading is also available on the proper calculation side, on a user-defined basis. - -Provided that hardware resources are large enough, this mode may reduce significantly the overall runtime of heavy simulations. - -To benefit from multi-threading, the simulation must be run in the following context: - -- In the "run" window, the option "parallel" must be selected - [^21] -- The simulation mode must be either "Adequacy" or "Economy" - -When the "parallel" solver option is used, each Monte-Carlo year is dispatched as an individual process on the available CPU cores.
    -The number of such individual processes depends on the characteristics of the local hardware and on the value given to the study-dependent " **simulation cores**" advanced parameter. This parameter can take five different values (Minimum, Low, Medium, High, Maximum). The number of independent processes resulting from the combination (local hardware + study settings) is given in the following table, which shows the CPU allowances granted in the different configurations. - -**Simulation Cores:** - -| _Machine_
    _Size [^22]_ | _Minimum_ | _Low_ | _Medium_ | _Large_ | _Maximum_ | -|:---:|:---:|:---:|:---:|:---:|:---:| -| _1_ | 1 | 1 | 1 | 1 | 1 | -| _2_ | 1 | 1 | 1 | 2 | 2 | -| _3_ | 1 | 2 | 2 | 2 | 3 | -| _4_ | 1 | 2 | 2 | 3 | 4 | -| _5_ | 1 | 2 | 3 | 4 | 5 | -| _6_ | 1 | 2 | 3 | 4 | 6 | -| _7_ | 1 | 2 | 3 | 5 | 7 | -| _8_ | 1 | 2 | 4 | 6 | 8 | -| _9_ | 1 | 3 | 5 | 7 | 8 | -| _10_ | 1 | 3 | 5 | 8 | 9 | -| _11_ | 1 | 3 | 6 | 8 | 10 | -| _12_ | 1 | 3 | 6 | 9 | 11 | -| _S > 12_ | 1 | Ceil(S/4) | Ceil(S/2) | Ceil(3S/4) | S-1 | -**
    CPU allowances in parallel mode
    ** - -**Note**: The number of independent threads actually launched by Antares in parallel mode may appear smaller than that shown in the table above. In this case, the resources monitor menu and the dashboard displayed on starting the simulation indicates: - -simulation cores: **nn** reduced to **pp** - -**nn** is the regular allowance and **pp** is the practical value that the solver has to work with. Allowance reduction may occur if the built-in Time-Series generators are activated, their "refresh" status is set to "Yes" and the values given to the "refresh span" parameters are not appropriate (parallel execution demand that refresh operations do not take place within a bundle of parallel years). Optimal use of the "parallel" execution mode is obtained when all activated built-in time –series generators are set up in either of the two following ways: -- Refresh status : **No** -- Refresh status : **Yes**, refresh span = **Ki \* (CPU allowance)** , with **Ki >= 1** - -Examples of reduction from an initial allowance of 12 cores are given hereafter. The reduced allowance is the size of the **smallest** bundle of parallel years between two consecutive "refresh" (it indicates the slowest point of the simulation [^23]). Note that RAM requirements displayed in the resources monitor are, contrariwise, assessed on the basis on the **largest** bundle of parallel years encountered in the simulation). - -![Reduced_Allowance](Reduced_Allowance.png) - -The Table indicates either the refresh status (No) or the refresh span (the associated refresh status "yes" is implicit). - - -[^21]: Options « default » do not perform multi-threaded optimizations - -[^22]: This hardware characteristic, independent from Antares general parameters and from study parameters, can be checked with the Resources monitor tool ([Commands](03-commands.md)) - -[^23]: When the number of MC years to run is smaller than the allowance, the parallel run includes all of these years in a single bundle and there is no "reduced allowance" message - -[^24]: - The smallest bundle in this case is the ninth (year number 97 to year number 100).The first 8 bundles involve 12 MC years each. - diff --git a/docs/reference-guide/10-command_line.md b/docs/reference-guide/10-command_line.md deleted file mode 100644 index 0d151481c2..0000000000 --- a/docs/reference-guide/10-command_line.md +++ /dev/null @@ -1,136 +0,0 @@ -# Using the command line - -Several executable parts of Antares\_Simulator can be run in command line from a console. The list and general syntax of these components is given hereafter. - -_In all cases, arguments " –h" or "–help" can be used to get help_ - -**The solver executable : antares-8.3-solver** - -- Simulation - -|command|meaning| -|:---|:---| -|-i, --input | Study folder | -|--expansion | Force the simulation in expansion mode | -|--economy | Force the simulation in economy mode | -|--adequacy | Force the simulation in adequacy mode | -|--parallel | Enable the parallel computation of MC years | -|--force-parallel=VALUE | Override the max number of years computed simultaneously | - -- Parameters - -|command|meaning| -|:---|:---| -|-n, --name=VALUE | Set the name of the new simulation to VALUE | -|-g, --generators-only | Run the time-series generators only | -|-c, --comment-file=VALUE | Specify the file to copy as comments of the simulation | -|-f, --force | Ignore all warnings at loading | -|--no-output | Do not write the results in the output folder | -|-z, --zip-output | Force the write of results into a single zip archive | -|-y, --year=VALUE | Override the number of MC years | -|--year-by-year | Force the writing the result output for each year
    (economy only) | -|--derated | Force the derated mode | - -- Optimization - -|command|meaning| -|:---|:---| -|--optimization-range | Force the simplex optimization range ('day' or 'week') | -|--no-constraints | Ignore all binding constraints| -|--no-ts-import | Do not import timeseries into the input folder.
    (This option may be useful for running old studies without upgrade)| -|-m, --mps-export | Export anonymous mps weekly or daily optimal UC+dispatch linear | -|-s, --named-mps-problems | Export named mps weekly or daily optimal UC+dispatch linear | - -- Misc. - -|command|meaning| -|:---|:---| -|--progress | Display the progress of each task | -|-p, --pid=VALUE | Specify the file where to write the process ID | -|-v, --version | Print the version of the solver and exit | -|-h, --help | Display this help and exit | -|--list-solvers | Display a list of LP solvers available through OR-Tools and exit | -|--use-ortools --ortools-solver=Sirius | Use the standard Antares solver through the OR-Tools modelling library | -|--use-ortools --ortools-solver=Coin | Use the Coin solver through the OR-Tools modelling library | - -**antares-8.3-study-updater** - -|command|meaning| -|:---|:---| -|-i, --input=VALUE | Add an input folder where to look for studies
    This argument is mandatory.| -|-c, --clean | Clean all studies found | -|--remove-generated-timeseries | Remove time-series which will be regenerated by
    the ts-generators | -|-d, --dry | List the study folders which may be upgraded and do nothing else | -|--force-readonly | Force read-only mode for all studies found | -|-v, --version | Print the version and exit | -|-h, --help | Display this help and exit | - -**antares-8.3-study-finder** - -|command|meaning| -|:---|:---| -|-i, --input=VALUE | Add an input folder where to look for studies.
    When no input folder is given, the current working dir is used. | -|-e, --extra | Print the version of the study | -|--csv | Print in a CSV format (semicolon) | -|-v, --version | Print the version and exit | -|-h, --help | Display this help and exit | - -**antares-8.3-study-cleaner** - -|command|meaning| -|:---|:---| -|-i, --input=VALUE | An input folder where to look for studies | -|--dry | List the folder only and do nothing | -|--mrproper | Suppress the outputs and logs files | -|-v, --version | Print the version and exit | -|-h, --help | Display this help and exit | - -**antares-8.3-config** - -|command|meaning| -|:---|:---| -|-p, --print | Print the current configuration | -|-v, --version | Print the version and exit | -|-h, --help | Display this help and exit | - -**antares-8.3-batchrun** - -- Studies - -|command|meaning| -|:---|:---| -|-i, --input=VALUE | The input folder, where to look for studies on which to run simulations | - -- Simulation mode - -|command|meaning| -|:---|:---| -|--expansion | Force the simulation(s) in expansion mode | -|--economy | Force the simulation(s) in economy mode | -|--adequacy | Force the simulation(s) in adequacy mode | - -- Parameters - -|command|meaning| -|:---|:---| -|-n, --name=VALUE | Set the name of the new simulation outputs | -|-y, --year=VALUE | Override the number of MC years | -|-f, --force | Ignore all warnings at loading | -|--no-output | Do not write the results in the output folder | -|--year-by-year | Force the writing of the result output for each year | - -- Optimization - -|command|meaning| -|:---|:---| -|--no-ts-import | Do not import timeseries into the input folder. | -|--no-constraints | Ignore all binding constraints | - -- Extras - -|command|meaning| -|:---|:---| -|--solver=VALUE | Specify the antares-solver location | -|--parallel | Enable the parallel computation of MC years | -|--force-parallel=VALUE | Override the max number of years computed simultaneously | -|--verbose |Display detailed logs for each simulation to run | diff --git a/docs/reference-guide/11-modeling.md b/docs/reference-guide/11-modeling.md deleted file mode 100644 index 668ba95743..0000000000 --- a/docs/reference-guide/11-modeling.md +++ /dev/null @@ -1,445 +0,0 @@ -# Formulation of the optimisation problems - -**_Antares\_Simulator Modeling and Optimization_** - -**Document available on : [https://antares-simulator.org](https://antares-simulator.org/)** - - -## Introduction - -The purpose of this document is to give every user of the **Antares\_Simulator** model (regardless of its version number), a detailed and comprehensive formulation of the main optimization problems solved by the application's inner optimization engine. - -The aim of the information presented hereafter is to provide a transparent access to the inner workings of the software from a **formal** standpoint. Note that, aside from this conceptual transparency, the software itself offers an option that makes it possible for the user to print, in a standardized format, any or all of the optimization problems actually solved in the course of an **Antares\_Simulator** session - -Used together with the elements developed in the next pages, this **practical** access to the internal model implemented the tool allows fair and open benchmarking with comparable software. Besides, another important issue regarding transparency is addressed by the release of **Antares\_Simulator** as an Open Source Gnu GPL 3.0 application. - -So as to delimit the scope of the present document with as much clarity as possible, it is important to notice that a typical **Antares\_Simulator** session involves different steps that are usually run in sequence, either automatically or with some degree of man-in-the-loop control, depending on the kind of study to perform. - -These steps most often involve: - -1. GUI session dedicated to the initialization or to the updating of various input data sections (load time-series, grid topology, wind speed probability distribution, etc.) -2. GUI session dedicated to the definition of simulation contexts (definition of the number and consistency of the ";Monte-Carlo years"; to simulate) -3. Simulation session producing actual numeric scenarios following the directives defined in (b) -4. Optimization session aiming at solving all of the optimization problems associated with each of the scenarios produced in (c). -5. GUI session dedicated to the exploitation of the detailed results yielded by (d) - -The scope of this document is exclusively devoted to step (d). Note that equivalent information regarding the other steps may be found in other documents made available either: - -- Within the application itself, in the "; ?"; menu -- On the **Antares\_Simulator** website (download section) : [https://antares-simulator.org](https://antares-simulator.org/) -- In technical publications referenced in the bibliography section of the website - -The following picture gives a functional view of all that is involved in steps (a) to (e). In this illustration, Step (d), whose goal is to solve the problems introduced in this document, is materialized by the red box. - -The number and the size of the individual problems to solve (a least-cost hydro-thermal unit-commitment and power schedule, with an hourly resolution and throughout a week, over a large interconnected system) make optimization sessions often computer-intensive. Note that the content of the blue ";hydro energy manager"; box appearing on the previous figure, whose purpose is to deal with energy storage issues at the seasonal scale, is not detailed in the present document but in the ";General Reference Guide";. - -Depending on user-defined results accuracy requirements, various practical options allow to simplify either the formulation of the weekly UC & dispatch problems (e.g. do not account for constraints associated with operational reserves) or their resolution (i.e. find, for the native MILP, an approximate solution based on two successive LPs). For the sake of simplicity and clarity, the way these options are used to revise the primary problem formulation is not detailed hereafter. Likewise, many simplifications are introduced to keep notations as light as possible. This is why, for instance, the overall sum of load, wind power generation, solar power generation, run of the river generation, and all other kinds of so-called ";must-run"; generation is simply denoted ";load"; in the present document. - -## Typology of the problems solved - -In terms of power studies, the different fields of application Antares has been designed for are the following: - -- **Generation adequacy problems :** assessment of the need for new generating plants so as to keep the security of supply above a given critical threshold - -What is most important in these studies is to survey a great number of scenarios that represent well enough the random factors that may affect the balance between load and generation. Economic parameters do not play as much a critical role as they do in the other kinds of studies, since the stakes are mainly to know if and when supply security is likely to be jeopardized (detailed costs incurred in more ordinary conditions are of comparatively lower importance). In these studies, the default Antares option to use is the ";Adequacy"; simulation mode. - -- **Transmission project profitability :** assessment of the savings brought by a specific reinforcement of the grid, in terms of decrease of the overall system generation cost (using an assumption of fair and perfect market) and/or improvement of the security of supply (reduction of the loss-of-load expectation). - -In these studies, economic parameters and the physical modeling of the dynamic constraints bearing on the generating units are of paramount importance. Though a thorough survey of many ";Monte-Carlo years"; is still required, the number of scenarios to simulate is not as large as in generation adequacy studies. In these studies, the default Antares option to use is the ";Economy"; simulation mode. - -- **Generation and/or Transmission expansion planning:** rough assessment of the location and consistency of profitable reinforcements of the generating fleet and/or of the grid at a given horizon, on the basis of relevant reference costs and taking into account feasibility local constraints (bounds on the capacity of realistic reinforcements). - -These long term studies clearly differ from the previous ones in the sense that the generation and transmission assets that define the consistency of the power system are no longer passive parameters but are given the status of active problem variables. In the light of both the nature and the magnitude of the economic stakes, there is comparatively a lesser need than before for an accurate physical modeling of fine operational constraints or for an intensive exploration of a great many random scenarios. The computer intensiveness of expansion studies is, however, much higher than that of the other types because the generic optimization problem to address happens to be much larger. - -The common rationale of the modeling used in all of these studies is, whenever it is possible, to decompose the general issue (representation of the system behavior throughout many years, with a time step of one hour) into a series of standardized smaller problems. - -In **Antares\_Simulator**, the ";elementary "; optimization problem resulting from this approach is that of the minimization of the overall system operation cost over a week, taking into account all proportional and non-proportional generation costs, as well as transmission charges and ";external"; costs such as that of the unsupplied energy (generation shortage) or, conversely, that of the spilled energy (generation excess). - -In this light, carrying out generation adequacy studies or transmission projects studies means formulating and solving a series of a great many week-long operation problems (one for each week of each Monte-Carlo year ), assumed to be independent. This generic optimization problem will be further denoted **,** where is an index encompassing all weeks of all Monte-Carlo years. - -Note that this independency assumption may sometimes be too lax, because in many contexts weekly problems are actually coupled to some degree, as a result of energy constraints (management of reservoir-type hydro resources, refueling of nuclear power plants, etc.). When appropriate, these effects are therefore dealt with before the actual decomposition in weekly problems takes place, this being done either of the following way (depending on simulation options): - -1. Use of an economic signal (typically, a shadow ";water value";) yielded by an external preliminary stochastic dynamic programming optimization of the use of energy-constrained resources. -2. Use of heuristics that provide an assessment of the relevant energy credits that should be used for each period, fitted so as to accommodate with sufficient versatility different operational rules. - -Quite different is the situation that prevails in expansion studies, in which weekly problems cannot at all be separated from a formal standpoint, because new assets should be paid for all year-long, regardless of the fact that they are used or not during such or such week : the generic expansion problem encompasses therefore all the weeks of all the Monte-Carlo years at the same time. More details can be found in the Antares Xpansion documentation. - -The next sections of this document develop the following subjects: - -- Notations used for \\(\mathcal{P}^k\\) - -- Formulation of \\(\mathcal{P}^k\\) - -- Complements to the standard problems (how to make **Antares\_Simulator** work as a SCOPF ) - -- Miscellaneous complements to the standard problems - -## Notations - -### General notations -**TODO : add units** - -| Notation | Explanation | -| ------------ | ------------- | -| \\( k \in K \\) | optimization periods (weeks) over which \\(P\\) and \\(P^k\\) are defined (omitted for simplicity) | -| \\(t \in T\\) | individual time steps of any optimization period \\( k\in K\\) (hours of the week) | -| \\(G(N,L)\\) | undirected graph of the power system (connected) | -| \\(n \in N\\) | vertices of \\(G\\), \\(N\\) is an ordered set | -| \\(l \in L\\) | edges of \\(G\\) | -| \\(A\\) | incidence matrix of \\(G\\), dimension \\(N\times L\\) | -| \\(g\\) | spanning tree of \\(G\\) | -| \\(C_g\\) | cycle basis associated with \\(g\\), dimension \\(L\times (L+1-N)\\) | -| \\(L_n^+\subset L\\) | set of edges for which \\(n\\) is the upstream vertex | -| \\(L_n^-\subset L\\) | set of edges for which \\(n\\) is the downstream vertex | -| \\(u_l \in N\\) | vertex upstream from \\(l\\) | -| \\(d_l \in N\\) | vertex downstream from \\(l\\) | -| \\(u \cdot v\\) | inner product of vectors \\(u\\) and \\(v\\) | -| \\(u_\uparrow^p\\) | vector resulting from the permutation on \\(u \in \mathbb{R}^s\\) : \\( u\_\uparrow^p(i)=u(i+p\, \mathrm{mod}\,s)\\) | - - -### Grid -**TODO : add units** - -| Notation | Explanation | -| ------------ | ------------- | -| \\(C_l^+ \in \mathbb{R}^T_+\\) | initial transmission capacity from \\(u_l\\) to \\(d_l\\) (variable of \\(P\\) and \\(P^k\\)) | -| \\( \overline{C}\_l^+ \in \mathbb{R}^T\_+ \\) | maximum transmission capacity from \\(u_l\\) to \\(d_l\\) (variable of \\(P\\), not used in \\(P^k\\)) | -| \\(C_l^- \in \mathbb{R}^T_+\\) | initial transmission capacity from \\(d_l\\) to \\(u_l\\) (variable of \\(P\\) and \\(P^k\\)) | -| \\( \overline{C}^{-}\_l\in \mathbb{R}^T\_{+} \\) | maximum transmission capacity from \\(d_l\\) to \\(u_l\\) (variable of \\(P\\), not used in \\(P^k\\)) | -| \\(\Psi_l \in \mathbb{R}_+\\) | weekly cost of a maximum capacity investment | -| \\(x_l \in [0,1]\\) | transmission capacity investment level | -| \\(F_l^+ \in \mathbb{R}^T_+\\) | power flow through \\(l\\), from \\(u_l\\) to \\(d_l\\) | -| \\(F_l^- \in \mathbb{R}^T_+\\) | power flow through \\(l\\), from \\(d_l\\) to \\(u_l\\) | -| \\(F_l\in \mathbb{R}^T\\) | total power flow through \\(l\\), \\(F_l=F_l^+-F_l^-\\) | -| \\(\tilde{F}_t \in \mathbb{R}^T\\) | system flow snapshot at time \\(t\\) | -| \\(\gamma_l^+\in \mathbb{R}^T\\) | transmission cost through \\(l\\), from \\(u_l\\) to \\(d_l\\). Proportional to the power flow | -| \\(\gamma_l^-\in \mathbb{R}^T\\) | transmission cost through \\(l\\), from \\(d_l\\) to \\(u_l\\). Proportional to the power flow | -| \\(Z_l \in \mathbb{R}\_+\\) | overall impedance of \\(l\\) | - -### Thermal units -**TODO : add units** - -| Notation | Explanation | -| ------------ | ------------- | -| \\(\theta \in \Theta_n\\) | thermal clusters (sets of identical units) installed in node \\(n\\) | -| \\(\Theta\\) | set of all thermal clusters of the power system \\(\Theta = \cup_{n\in N} \Theta_n\\) | -| \\(\overline{P}\_\theta \in \mathbb{R}^T_+\\) | maximum power output from cluster \\(\theta\\), depends on units availability | -| \\(\underline{P}\_\theta \in \mathbb{R}^T_+\\) | mimimum power output from cluster \\(\theta\\), units availability allowing | -| \\(P_\theta \in \mathbb{R}^T_+\\) | power output from cluster \\(\theta\\) | -| \\(\chi_\theta \in \mathbb{R}^T\\) | power output from cluster \\(\theta\\) | -| \\(\sigma_\theta^+ \in \mathbb{R}^T\\) | startup cost of a single unit in cluster \\(\theta\\) | -| \\(\tau_\theta \in \mathbb{R}^T\\) | running unit in \\(\theta\\) : cost independent from output level (aka NoLoadHeatCost) | -| \\(l_\theta \in \mathbb{R}_+\\) | unit in \\(\theta\\) : minimum stable power output when running | -| \\(u_\theta \in \mathbb{R}_+\\) | unit in \\(\theta\\) : maximum net power output when running | -| \\(\Delta_\theta^+ \in \lbrace 1,\dots, \|T\|\rbrace\\) | unit in \\(\theta\\) : minumum on time when running | -| \\(\Delta_\theta^- \in \lbrace 1,\dots, \|T\|\rbrace\\) | unit in \\(\theta\\) : minumum off time when not running | -| \\(\Delta_\theta = \max(\Delta_\theta^-, \Delta_\theta^+) \\) | duration above which both state changes are allowed | -| \\(M_\theta \in \mathbb{N}^T\\) | number of running units in cluster \\(\theta\\) | -| \\(\overline{M}_\theta \in \mathbb{N}^T\\) | maximum number of running units in cluster \\(\theta\\) | -| \\(\underline{M}_\theta \in \mathbb{N}^T\\) | minimum number of running units in cluster \\(\theta\\) | -| \\(M_\theta^+ \in \mathbb{N}^T\\) | number of units in cluster changing from state off to state on in cluster \\(\theta\\) | -| \\(M_\theta^- \in \mathbb{N}^T\\) | number of units in cluster changing from state on to state off in cluster \\(\theta\\) | -| \\(M_\theta^{--} \in \mathbb{N}^T\\) | number of units in cluster changing from state on to state outage cluster \\(\theta\\) | - -### Reservoir-type hydropower units (or other power storage facilities) -**TODO : add units** - -| Notation | Explanation | -| ------------ | ------------- -| \\(\lambda \in \Lambda_n\\) | reservoirs connected to node \\(n\\) | -| \\(\Sigma_\lambda \in \mathbb{R}_+\\) | size of reservoir \\(\lambda\\) : amount of energy that can be stored in \\(\lambda\\) | -| \\(Q\in \mathbb{N}\\) | number of discrete levels defined in reservoir | -| \\(\overline{W}\_\lambda \in \mathbb{R}_+\\) | maximum energy output from \\(\lambda\\) throughout the optimization period | -| \\(\underline{W}\_\lambda \in \mathbb{R}_+\\) | minimum energy output from \\(\lambda\\) throughout the optimization period | -| \\(\overline{H}\_\lambda \in \mathbb{R}_+^T\\) | maximum power output from reservoir \\(\lambda\\). Note : \\(\sum_{t\in T} \overline{H}\_{\lambda\_t} \geq \underline{W}\_\lambda\\) | -| \\(\underline{H}\_\lambda \in \mathbb{R}_+^T\\) | minimum power output from reservoir \\(\lambda\\). Note : \\(\sum_{t\in T} \underline{H}\_{\lambda\_t} \leq \overline{W}\_\lambda\\) | -| \\(H\_\lambda \in \mathbb{R}_+^T\\) | power output from reservoir \\(\lambda\\) | -| \\(r\_\lambda \in \mathbb{R}_+\\) | maximum ratio between output power daily peak and daily average (\\(1 \leq r\_\lambda \leq 24\\)) | -| \\(\varepsilon\_\lambda \in \mathbb{R}\\) | reference water value associated with the reservoir's initial state (date, level) | -| \\(\varepsilon^*\_\lambda \in \mathbb{R}\\) | random component added to the water value (dispatch smoothing effect) | -| \\(\eta\_\lambda \in \mathbb{R}^Q\\) | reference water value associated with the reservoir's final state (date) | -| \\(\rho\_\lambda \in \mathbb{R}_+\\) | efficiency ratio of pumping units (or equivalent devices) available in reservoir \\(\lambda\\) | -| \\(\overline{\Pi}\_\lambda \in \mathbb{R}_+^T\\) | maximum power absorbed by pumps of reservoir \\(\lambda\\) | -| \\(\Pi\_\lambda \in \mathbb{R}_+^T\\) | power absorbed by pumps of reservoir \\(\lambda\\) | -| \\(I\_\lambda \in \mathbb{R}^T_+\\) | natural power inflow to reservoir \\(\lambda\\) | -| \\(O\_\lambda \in \mathbb{R}_+^T\\) | power overflowing from reservoir \\(\lambda\\) : part of inflow that cannot be stored | -| \\(\overline{R}\_\lambda \in \mathbb{R}_+^T\\) | upper bound of the admissible level in reservoir \\(\lambda\\) | -| \\(\underline{R}\_\lambda \in \mathbb{R}_+^T\\) | lower bound of the admissible level in reservoir \\(\lambda\\) | -| \\(R\_\lambda \in \mathbb{R}^T_+\\) | stored energy level in reservoir \\(\lambda\\) | -| \\(\mathfrak{R}\_{\lambda_q} \in \mathbb{R}_+\\) | filling level of reservoir layer \\(q\\) at time \\(T\\) (end of the week) | - -### Binding constraints - -In problems \\(\mathcal{P}^k\\), the need for a versatile modelling of the power system calls for the introduction of an arbitrary number of linear binding constraints between system's variables throughout the grid, expressed either in terms of hourly power, daily energies or weekly energies. -These constraints may bind together synchronous flows as well as thermal units power outputs. They may be related to synchronous values or bear on different times. -Herebelow, the generic notation size is used for the relevant dimension of the set to which parameters belong. - -These dimensions stand as follow - -\\(\mathrm{size}=T=168\\) : applicable to lower and upper bounds of constraints between hourly powers -\\(\mathrm{size}=\frac{T}{7}=24\\) : applicable to lower and upper bounds of constraints between daily energies -\\(\mathrm{size}=\frac{T}{168}=1\\) : applicable to lower and upper bounds of constraints between weekly energies - -Generic notations for binding constraints : - -| Notation | Explanation | -| ------------ | ------------- | -| \\(e \in E\\) | set of all grid interconnections and thermal clusters. \\(E = L \cup \Theta\\) | -| \\(b \in B\\) | binding constraints | -| \\(B_h \subset B\\) | subset of \\(B\\) containing the binding constraints between hourly powers | -| \\(B_d \subset B\\) | subset of \\(B\\) containing the binding constraints between daily energies | -| \\(B_w \subset B\\) | subset of \\(B\\) containing the binding constraints between weekly energies | -| \\(\alpha_e^b \in \mathbb{R}\\) | weight of \\(e\\) (flow within \\(e\\) or output from \\(e\\)) in the expression of constraint \\(b\\) | -| \\(o_e^b \in \mathbb{N}\\) | time offset of \\(e\\) (flow within \\(e\\) or output from \\(e\\)) in the expression of constraint \\(b\\) | -| \\(u^b \in \mathbb{R}^{\mathrm{size}}\\) | upper bound of binding constraint \\(b\\) | -| \\(l^b \in \mathbb{R}^{\mathrm{size}}\\) | lower bound of binding constraint \\(b\\) | - -### Demand, security uplift, unsupplied and spilled energies -| Notation | Explanation | -| ------------ | ------------- | -| \\(D_n \in \mathbb{R}^T\\) | net power demand expressed in node \\(n\\), including must-run generation | -| \\(S_n \in \mathbb{R}^T_+\\) | demand security uplift to be faced in node \\(n\\), by activation of security reserves | -| \\(\delta_n^+ \in \mathbb{R}^T\\) | normative unsupplied energy value in node \\(n\\). Value of lost load - VOLL | -| \\(G_n^+ \in \mathbb{R}^T_+\\) | unsupplied power in the nominal state | -| \\(\delta_n^- \in \mathbb{R}^T\\) | normative spilled energy value in node \\(n\\) (value of wasted energy) | -| \\(G_n^- \in \mathbb{R}^T_+\\) | spilled power in the nominal state | - - -## Formulation of problem \\(\mathcal{P}^k\\) - -Superscript k is implicit in all subsequent notations of this section (omitted for simplicity's sake) - -## Objective -$$ - \min\_{M\_\theta \in \mathrm{Argmin} \Omega\_{\mathrm{unit com}}}(\Omega\_{\mathrm{dispatch}}) -$$ - - -with - - -\\( -\displaystyle \Omega\_{\mathrm{dispatch}} = \Omega\_{\mathrm{transmission}}+\Omega\_{\mathrm{hydro}}+\Omega\_{\mathrm{thermal}}+\Omega\_{\mathrm{unsupplied}}+\Omega\_{\mathrm{spillage}} -\\) - - -\\( -\displaystyle \Omega\_{\mathrm{transmission}}=\sum_{l \in L} \gamma_l^+ \cdot F_l^+ + \gamma_l^- \cdot F_l^- -\\) - - -\\( -\displaystyle \Omega\_{\mathrm{hydro}} = \sum\_{n \in N} \sum\_{\lambda in \Lambda\_n} (\varepsilon\_\lambda + \varepsilon^*\_\lambda)\cdot(H\_\lambda - \rho\_\lambda \Pi\_\lambda + O\_\lambda) - \sum\_{n \in N} \sum\_{\lambda \in \Lambda\_n}\sum\_{q=1}^Q \eta\_{\lambda\_q} \mathfrak{R}\_{\lambda_q} -\\) - - -\\( -\displaystyle \Omega\_{\mathrm{thermal}}=\sum\_{n \in N} \sum\_{\theta \in \Theta\_n} \chi\_\theta \cdot P\_\theta + \sigma\_\theta^+ \cdot M\_\theta^+ + \tau\_\theta \cdot M\_\theta -\\) - - -\\( -\displaystyle \Omega\_{\mathrm{unsupplied}}=\sum\_{n \in N} \delta_n^+ \cdot G_n^+ -\\) - - -\\( -\displaystyle \Omega\_{\mathrm{spillage}}=\sum\_{n \in N} \delta_n^- \cdot G_n^- -\\) - -\\(\Omega\_{\mathrm{unit com}}\\) is the expression derived from \\(\Omega\_{\mathrm{dispatch}}\\) by replacing all variables that depend on the system's state by their equivalent in the uplifted state. - -## Constraints related to the nominal system state - -Balance between load and generation: - -First Kirchhoff's law: - -\\( -\displaystyle \forall n \in N, \sum\_{l \in L\_n^+} F_l - \sum\_{l \in L\_n^-} F_l = \left( G\_n^+ + \sum\_{\lambda \in \Lambda\_n}(H\_\lambda - \Pi\_\lambda) + \sum\_{\theta \ \in \Theta\_n} P\_\theta\right)-(G\_n^-+D\_n) -\\) - - -On each node, the unsupplied power is bounded by the net positive demand: - -\\( -\displaystyle \forall n \in N, 0 \leq G\_n^+ \leq \max(0, D_n) -\\) - -On each node, the spilled power is bounded by the overall generation of the node (must-run + dispatchable power): - -\\( -\displaystyle \forall n \in N, 0 \leq G_n^- \leq -\min(0, D_n) + \sum\_{\lambda \in \Lambda\_n}H\_\lambda + \sum\_{\theta \ \in \Theta\_n} P\_\theta -\\) - -Flows on the grid: - -\\( -\displaystyle \forall l \in L, 0 \leq F\_l^+ \leq C\_l^+ +(\overline{C}^{+}\_l - C\_l^+)x\_l -\\) - -\\( -\displaystyle \forall l \in L, 0 \leq F\_l^- \leq C\_l^- +(\overline{C}^{-}\_l - C\_l^-)x\_l -\\) - -\\( -\displaystyle \forall l \in L, F\_l = F\_l^+ - F\_l^- -\\) - -Flows are bounded by the sum of an initial capacity and of a complement brought by investment - -Binding constraints : - -\\( -\displaystyle \forall b \in B\_h, l^b \leq \sum\_{e \in E} \alpha\_e^b (F\_e)\_{\uparrow}^{o\_e^b} \leq u^b -\\) - -\\( -\displaystyle \forall b \in B\_d, \forall k \in \lbrace 0,\dots,6\rbrace, l^b \leq \sum\_{e \in E} \alpha\_e^b \sum\_{t \in \lbrace 1,\dots,24\rbrace} (F\_e)\_{\uparrow {24k+t}}^{o\_e^b} \leq u^b -\\) - -\\( -\displaystyle \forall b \in B\_w, l^b \leq \sum\_{e \in E} \alpha\_e^b \sum\_{t \in T} F\_{e\_t} \leq u^b -\\) - -Reservoir-type Hydro power: - -The energy generated throughout the optimization period is bounded - -\\( -\displaystyle \forall n \in N, \forall \lambda \in \Lambda\_n, \underline{W}\_{\lambda} \ leq \sum\_{t\in T} H\_{\lambda\_t} \leq \overline{W}\_{\lambda} -\\) - -FIXME : RHS -\\( -\displaystyle \forall n \in N, \forall \lambda \in \Lambda\_n, \sum\_{t\in T} H\_{\lambda\_t} - \sum\_{t\in T} \rho\_t \Pi\_{\lambda\_t} = \overline{W}\_{\lambda} -\\) - -Instantaneous generating power is bounded - -\\( -\displaystyle \forall n \in N, \forall \lambda \in \Lambda\_n, \underline{H}\_{\lambda} \leq H\_{\lambda} \leq \overline{H}\_{\lambda} -\\) - -Intra-daily power modulations are bounded - -\\( -\displaystyle \forall n \in N, \forall \lambda \in \Lambda\_n, \forall k \in \lbrace 1, \ldots, 6 \rbrace, \frac{\max\_{t \in \lbrace 24k+1,\ldots, 24k+24 \rbrace} H\_{\lambda\_t}}{\sum\_{t \in \lbrace 24k+1,\ldots, 24k+24 \rbrace} H\_{\lambda\_t}} \leq r\_{\lambda} -\\) - -Instantaneous pumping power is bounded - -\\( -\displaystyle \forall n \in N, \forall \lambda \in \Lambda\_n, 0 \leq \Pi\_{\lambda} \leq \overline{\Pi}\_{\lambda} -\\) - -Reservoir level evolution depends on generating power, pumping power, pumping efficiency, natural inflows and overflows - -Reservoir level is bounded by admissible lower and upper bounds (rule curves) - -Thermal units : - -Power output is bounded by must-run commitments and power availability - -The number of running units is bounded - -Power output remains within limits set by minimum stable power and maximum capacity thresholds - -Minimum running and not-running durations contribute to the unit-commitment plan. Note that this modeling requires that one at least of the following conditions is met: - -### Constraints related to the uplifted system state (activation of security reserves) - -All constraints to previously defined for regular operation conditions are repeated with replacement of all variables by their twins when they exist. - -Besides, in the expression of constraints , all occurrences of are replaced by \\(D_n + S_n\\) - -## Antares as a SCOPF ("flow-based model") - -When problems \\(\mathcal{P}^k\\) do not include any instance of so-called ";binding constraints"; and if no market pools are defined, the flows within the grid are only committed to meet the bounds set on the initial transmission capacities, potentially reinforced by investments (problem ).In other words, there are no electrical laws enforcing any particular pattern on the flows, even though hurdles costs and may influence flow directions through an economic signal. - -In the general case, such a raw backbone model is a very simplified representation of a real power system whose topology and consistency are much more complex. While the full detailed modeling of the system within Antares is most often out of the question, it may happen that additional data and/or observations can be incorporated in the problems solved by the software. - -In a particularly favorable case, various upstream studies, taking account the detailed system characteristics in different operation conditions (generating units outages and/or grid components outages N, N-1 , N-k,…) may prove able to provide a translation of all relevant system limits as a set of additional linear constraints on the power flowing on the graph handled by Antares. - -These can therefore be readily translated as ";hourly binding constraints";, without any loss of information. This kind of model will be further referred to as a "flow-based model". Its potential downside is the fact that data may prove to be volatile in short-term studies and difficult to assess in long-term studies. - -## Antares as a SCOPF ("KL model") - -When a full flow-based model cannot be set up (lack of robust data for the relevant horizon), it remains possible that classical power system studies carried on the detailed system yield sufficient information to enrich the raw backbone model. An occurrence of particular interest is when these studies show that the physics of the active power flow within the real system can be valuably approached by considering that the edges of behave as simple impedances .This model can be further improved if a residual (passive) loop flow is to be expected on the real system when all nodes have a zero net import and export balance (situation typically encountered when individual nodes actually represent large regions of the real system). This passive loop flow should therefore be added to the classical flow dictated by Kirchhoff's rules on the basis of impedances . This model will be further referred to as a "KL model". Different categories of binding constraints, presented hereafter, make it possible to implement this feature in and - -### Implementation of Kirchhoff's second law - -The implementation ofKirchhoff's second law for the reference state calls for the following additional hourly binding \\(L+1-N\\) constraints: - -\\( -\forall t \in T, C\_{g}^t Diag(Z\_{l}) \tilde{F}\_{t} = 0 -\\) - -### Implementation of a passive loop flow - -In cases where a residual passive loop flow should be incorporated in the model to complete the enforcement of regular Kirchhoff's rules, the binding constraints mentioned in 7.1 should be replaced by: - -\\( -\forall t \in T, C\_{g}^t Diag(Z\_{l}) \tilde{F}\_{t} = C\_{g}^t Diag(Z\_{l}) \tilde{\phi}\_{t} -\\) - -### Modelling of phase-shifting transformers - -In cases where the power system is equipped with phase-shifting transformers whose ratings are known, ad hoc classical power studies can be carried out to identify the minimum and maximum flow deviations and phase-shift that each component may induce on the grid. The following additional notations are in order: - -| Notation | Explanation | -| ------------ | ------------- | -| \\(\Pi\_{l}^{+shift} \in \mathbb{R}\_{+}\\) | Maximum positive shifting ability of a device equipping link \\(l\\)| -| \\(\Pi^{+shift} \in \mathbb{R}^{L}\\) | Snapshots formed by all positive synchronous deviations \\(\Pi\_{l}^{+shift} \in \mathbb{R}\_{+}\\) | -| \\(\Pi\_{l}^{+shift} \in \mathbb{R}\_{-}\\) | Maximum negative shifting ability of a device equipping link \\(l\\)| -| \\(\Pi^{-shift} \in \mathbb{R}^{L}\\) | Snapshots formed by all negative synchronous deviations \\(\Pi\_{l}^{-shift} \in \mathbb{R}\_{-}\\) | - -The enhancement of the model with a representation of the phase-shifting components of the real system then requires to re-formulate as follows the binding constraints defined in 7.2: - -\\( -\forall t \in T, C\_{g}^t Diag(Z\_{l}) \tilde{\phi}\_{t} - \Pi^{-shift} \leq C\_{g}^t Diag(Z\_{l}) \tilde{F}\_{t} \leq C\_{g}^t Diag(Z\_{l}) \tilde{\phi}\_{t} + \Pi^{+shift} -\\) - -### Modelling of DC components - -When the power system graph contains edges that represent DC components, additional notations need be defined: - -The proper modeling of the system then requires that all constraints identified in 7.1, 7.2, 7.3 be formulated using notations instead of - -### Implementation of security rules N-1,..., N-k - -Upstream power system classical calculations on the detailed system are assumed to have provided appropriate estimates for line outage distribution factors (LODFs) for all components involved in the contingency situations to consider. The following additional notations will be further used: - -The implementation of security rules for the chosen situations requires the following additional binding constraints: - -## Antares as a SCOPF (";KL+FB model";) - -If the information context is rich enough, it is possible to set up a hybrid model based on both previous approaches: on the one hand, a ";KL layer"; makes use of the best available estimates for grid impedances and loop flows, so as to instantiate physically plausible flow patterns; on the other hand, a ";FB layer"; sets multiple kinds of limits on the admissible flow amplitudes, as a result of various operation commitments. - -To work appropriately, such a hybrid model needs an additional auxiliary layer that performs a mapping between the two ";twin"; FB and KL grid layers. - -## Miscellaneous - -### Modelling of pumped storage power plants - -A number of specific equipments, as well as particular operation rules or commercial agreements, can be modelled with appropriate use of binding constraints. A typical case is that of a pumped storage power plant operated with a daily or weekly cycle. Such a component can be modelled as a set of two virtual nodes connected to the real grid through one-way lines. On one node is attached a virtual load with zero VOLL, which may absorb power from the system. On the other node is installed a virtual generating unit with zero operation cost, which may send power to the system. The flows on the two virtual lines are bound together by a daily or weekly constraint (depending on the PSP cycle duration), with a weight set to fit the PSP efficiency ratio. Besides, time offsets may be included in the constraints to take into account considerations regarding the volume of the PSP reservoir (additional energy constraint). - -[1](#sdfootnote1anc) The development of the product is a continuous process resulting in the dissemination of a new version each year. As a rule, version N brings various improvements on the code implemented in version N-1 and enhances the functional perimeter of the tool. This document presents the general optimization problem formulation as it is formalized so far in the last version of disseminated version of **Antares\_Simulator** (V7). - -[2](#sdfootnote2anc) Reference guide , section « optimization preferences : ";export mps problems"; - -[3](#sdfootnote3anc) For the sake of simplicity, the **Antares\_Simulator** application will be further denoted « Antares » - -[4](#sdfootnote4anc)See «hydro» sections of the General Reference Guide (";hydro"; standing as a generic name for all types of energy storage facilities) - -[5](#sdfootnote5anc)This does not actually limit the model's field of application: all datasets can easily be put in a format that meets this commitment - -[6](#sdfootnote6anc) FB stands for « flow-based », denomination used in the framework given to the internal electricity market of western Europe - -[7](#sdfootnote7anc) KL stands for ";Kirchhoff- and-Loop";. Such a model was used in the European E-Highway project ([http://www.e-highway2050.eu](http://www.e-highway2050.eu/)) - -[8](#sdfootnote8anc) A common situation is that KL and FB are defined at different spatial scales and describe different topologies: the KL layer has typically a fairly large number of small-sized regions, while the FB layer consists of fewer wide market zones. The role of the auxiliary layer is to implement the appropriate relationship between physical regions and trade zones. - -Copyright © RTE 2007-2019 – Version 7.1.0 - -Last Rev : M. Doquet - 16 OCT 2019 diff --git a/docs/reference-guide/12-attribution_notices.md b/docs/reference-guide/12-attribution_notices.md deleted file mode 100644 index be1dafd062..0000000000 --- a/docs/reference-guide/12-attribution_notices.md +++ /dev/null @@ -1,37 +0,0 @@ -# APPENDIX : ATTRIBUTION NOTICES - -**Antares\_Simulator** - -**Copyright 2007-2022 RTE - Authors: The Antares\_Simulator Team** - -Antares\_Simulator 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. - -There are special exceptions to the terms and conditions of the license as they are applied to this software. View the full text of the exceptions in file COPYING.txt in the directory of a distribution of the software in source form. - -Antares\_Simulator 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 Antares\_Simulator. If not, see <[https://www.gnu.org/licenses/](https://www.gnu.org/licenses/) >. - -**Antares\_Simulator 8.3 uses external libraries and makes extensive use of the following persons' or companies code. Source and binary forms of these programs are distributed along with Antares\_Simulator with NO WARRANTY:** - -- Wxwidgets 3.1.3 Copyright (c) 1998-2017 The wxWidget Team - [https://github.com/wxWidgets/wxWidgets.git](https://github.com/wxWidgets/wxWidgets.git) - license: wxWindows Library License,V3.1 [https://spdx.org/licenses/wxWindows.html](https://spdx.org/licenses/wxWindows.html) - -- libYuni 1.1.0 [https://github.com/libyuni](https://github.com/libyuni) - license: Mozilla Public License 2.0 [https://spdx.org/licenses/MPL-2.0.html](https://spdx.org/licenses/MPL-2.0.html) - -- Mersenne Twister Copyright (c) 1997-2002 M.Matsumoto and T.Nishimura - license: 3-clause BSD [https://spdx.org/licenses/BSD-3-Clause.html](https://spdx.org/licenses/BSD-3-Clause.html) - -- strtod library Copyright (c) 1988-1993 The Regents of the University of California - Copyright (c) 1994 Sun Microsystems, Inc - license: ISC license [https://spdx.org/licenses/ISC.html](https://spdx.org/licenses/ISC.html) - -- Sirius\_Solver Copyright (c) 2007-2018 RTE - [https://github.com/rte-france/sirius-solver.git](https://github.com/rte-france/sirius-solver.git) - license: Apache 2.0 [https://spdx.org/licenses/Apache-2.0.html](https://spdx.org/licenses/Apache-2.0.html) - -- OR-Tools Copyright (c) 2010-2020 Google LLC - [https://github.com/rte-france/or-tools.git](https://github.com/rte-france/or-tools.git) - license: Apache 2.0 [https://spdx.org/licenses/Apache-2.0.html](https://spdx.org/licenses/Apache-2.0.html) diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md deleted file mode 100644 index 24b4d64abb..0000000000 --- a/docs/reference-guide/13-file-format.md +++ /dev/null @@ -1,250 +0,0 @@ -# Study format changes -This is a list of all recent changes that came with new Antares Simulator features. The main goal of this document is to lower the costs of changing existing interfaces, both GUI and scripts. -## v8.7.1 -### Input -### Short-term storage -If no value is specified for `initiallevel`, then a default value of 50% is used. Note that this value is used only if `initialleveloptim=false`, and that `false` is the default value for `initialleveloptim`. - -## v8.7.0 -### Input -#### Scenarized RHS for binding constraints -- For each binding constraint, file **input/bindingconstraints/<id>.txt** is split into 3 files: - - **input/bindingconstraints/<id>_lt.txt** - - **input/bindingconstraints/<id>_gt.txt** - - **input/bindingconstraints/<id>_eq.txt** - - Each of these files can be either empty or have N column of 8674 rows - -- In file **input/bindingconstraints/bindingconstraints.ini**, add property `group` to every section -- Binding constraints in the same group must have the same number of RHS columns (3 files described above for their respective types). Exception: a constraint in a group can have empty RHS or only one RHS column -- In file **settings/scenariobuilder.dat**, add prefix `bc` for every group of binding constraints. The syntax is the following -``` -bc,, = -``` -This line is not mandatory for every group & MC year. If absent, the TS number will be drawn randomly (usual behavior). - -- 0 <= MC Year < generaldata.ini/general.nbyears -- 1 <=TS number <= number of columns for the group - -#### Thermal cluster new properties -For each thermal cluster, in existing file **input/thermal/clusters/<area>/list.ini**, under existing sections **<cluster>**, following properties added: - -* `costgeneration` [string] can take values `useCostTimeseries` or be excluded from the section if `SetManually` is selected (default behavior). -* `efficiency` [float] between 0-100 (default = 100). Unit is "percentage". -* `variableomcost` [float] excluded from the section if default value 0 is selected (default behavior). Unit is Euro / MWh - -For each thermal cluster, new files added **input/thermal/series/<area>/<cluster>/CO2Cost.txt** and **input/thermal/series/<area>/<cluster>/fuelCost.txt**. **fuelCost.txt** and **CO2Cost.txt** must either have one column, or the same number of columns as existing file **series.txt** (availability). The number of rows for these new matrices is 8760. - -### Output -#### Scenarized RHS for binding constraints -Add directory **bindingconstraints** to output directory **ts-numbers**. For every binding constraint group, add a file **ts-numbers/bindingconstraints/<group>.txt** containing the TS numbers used for that group. - -## v8.6.0 -### Input -#### Short-term storage -* Add directories **input/st-storage/clusters** and **input/st-storage/series** -* For each area, add directory **input/st-storage/clusters/<area id>/list.ini** -* This file contains the multiple sections whose name is ignored. Each section contains these properties: - * `name` [str] - * `group` [str]. Possible values: "PSP_open", "PSP_closed", "Pondage", "Battery", "Other1", ... , "Other5". Default Other1 - * `efficiency` [double] in range 0-1 - * `reservoircapacity` [double] > 0 - * `initiallevel` [double] in range 0-1 - * `withdrawalnominalcapacity` [double] > 0 - * `injectionnominalcapacity` [double] > 0 - * `initialleveloptim` [bool] - -* For each short-term-storage object, add the corresponding time-series in directory **input/st-storage/series/<area id>/<STS id>**. All of these files contain 8760 rows and 1 column. - * **PMAX-injection.txt** All entries must be in range 0-1 - * **PMAX-withdrawal.txt** All entries must be in range 0-1 - * **inflows.txt** All entries must be > 0 - * **lower-rule-curve.txt** All entries must be in range 0-1 - * **upper-rule-curve.txt** All entries must be in range 0-1 - -#### Pollutant emission factors -In files **input/thermal/cluster/area/list.ini** add properties `nh3`, `nox`, `pm2_5`, `pm5`, `pm10`, `nmvoc`, `so2`, `op1`, `op2`, `op3`, `op4`, `op5` [double]. These properties are emission factors similar to the existing one for CO2. - -#### Adequacy patch -In file **settings/generaldata.ini**, in section `adequacy patch` add property `enable-first-step` [bool]. Default value = `true` Enable or disable DENS column - -#### Hydro Pmin -For each area, new file added **input/hydro/series/<area>/mingen.txt**. This file has one or more columns, and 8760 rows. The number of columns may be 1, or identical to the number of columns in existing file **mod.txt**. - -### Output -#### Short-term storage -* For every short-term storage group, add 3 columns in files **values-<period>.txt** (mc-all & mc-ind) - * `ST--withdrawal` - * `ST--injection` - * `ST--level` -* For every area, add file **details-STstorage-<period>.txt** (mc-all & mc-ind) containing the same columns, but this time for every short-term storage object. - -#### Pollutant emission factors -In files **economy/mc-all/areas/** add column: CO2 EMIS. One colum for every pollutant: CO2, NH3, NOX, PM2\_5, PM5, PM10, NMVOC, OP1, OP2, OP3, OP4, OP5 - -## v8.5.2 -### Input -In file **settings/generaldata.ini**, in section `optimization`, link-type is now deprecated - -## v8.5.0 -### Input -In file **settings/generaldata.ini**, in section `adequacy patch`, add properties - -* `price-taking-order` [string] can take values `DENS` (default value) and `Load`. -* `include-hurdle-cost-csr` [bool]. Default value = `false` -* `check-csr-cost-function` [bool]. Default value = `false` -* `threshold-initiate-curtailment-sharing-rule` [double]. Default value = `0.0` -* `threshold-display-local-matching-rule-violations` [double]. Default value = `0.0` -* `threshold-csr-variable-bounds-relaxation` [int]. Default value = `3` - -### Output -* If `include-adq-patch` is set to `true`, add column `LMR VIOL.` in files **values-<period>.txt** (mc-all & mc-ind) -* If `include-adq-patch` is set to `true`, add column `SPIL. ENRG. CSR` in files **values-<period>.txt** (mc-all & mc-ind) -* If `include-adq-patch` is set to `true`, add column `DTG MRG CSR` in files **values-<period>.txt** (mc-all & mc-ind) - -## v8.4.0 -### Input -#### Zero/infinite capacity for physical links only -In file **settings/generaldata.ini**, in section `optimization`, change admissible values for key `transmission-capacities` [str]: - -* `local-values` (formerly `true`, default) uses the local capacity of all links -* `null-for-all-links` (formerly `false`) sets the capacity of all links to 0 -* `infinite-for-all-links` (formerly `infinite`) sets the capacity of all links to +infinity -* `null-for-physical-links` sets the capacity of physical links to 0, uses the local capacity for virtual links -* `infinite-for-physical-links` sets the capacity of physical links to +infinity, uses the local capacity for virtual links - -Previous values (`true`, `false` and `infinite`) are still admissible for compatibility. - -### Remove "Split MPS" -In existing section `optimization`, remove property `include-split-exported-mps` [bool]. This property will be ignored (no error) for compatibility. - -#### Result format -In file **settings/generaldata.ini**, in existing section `output`, add property `result-format` [str]. Default value = `txt-files`. If this property is set to `zip`, all results are written into a single zip archive, instead of multiple files. - -### Output -#### Result format -If property `output/result-format` is set to `zip`, all results are stored in a single archive. The hierarchy within this archive remains identical, for example **economy/mc-all/areas/**. Otherwise, txt files are created like in previous versions. - -## v8.3.2 -### Writing MPS files -MPS files of first optimization used to be overwritten by MPS files of second optimization. Not anymore. -Now user can choose to print : -* no MPS file, -* MPS files related to the first optimization (named **problem-<week>-<year>--optim-nb-1.txt**), -* MPS files related to the second optimization (named **problem-<week>-<year>--optim-nb-2.txt**), -* MPS files related to the both optimizations. - -In the **generaldata.ini** input file, corresponding values for **include-exportmps** are : **none**, **optim-1**, **optim-2**, **both-optims**. - -Compatibility with existing values is maintained (**true** = **both-optims**, **false**=**none**). - -### Marginal price of a binding constraint -#### Input -In the context of the addition of a new output variable (marginal price associated to a binding constraint), file **input/bindingconstraints/bindingconstraints.ini** get 2 new parameters for each binding constraint. -They control which marginal price time granularity is printed, either regarding year by year or synthesis results. - -* `filter-year-by-year`. Default value = hourly, daily, weekly, monthly, annual -* `filter-synthesis`. Default value = hourly, daily, weekly, monthly, annual - -#### Marginal cost for binding constraints -Still on the binding constraints marginal price results, 2 new folders **binding_constraints** are created inside any simulation output folder, more precisely under **mc-ind** and **mc-all**. - -Examples : -* **output/yyyymmdd-hhmmeco/economy/mc-ind/00001/binding_constraints** -* **output/yyyymmdd-hhmmeco/economy/mc-all/binding_constraints** - -These folders are meant to contain results of any kind regarding binding constraints marginal price (year by year or synthesis). - -Examples of output files inside these folders : -* **binding-constraints-hourly.txt** -* **binding-constraints-weekly.txt** - -## v8.3.1 -### Output -Add file **execution_info.ini**, containing information about the execution time for the various steps of a study, as well as study related information that affects performance. - -```ini -[durations_ms] -hydro_ventilation = 7 -mc_years = 693 -post_processing = 0 -study_loading = 51 -synthesis_export = 731 -total = 1526 -yby_export = 114 - -[number_of_calls] -hydro_ventilation = 1 -mc_years = 1 -post_processing = 1 -study_loading = 1 -synthesis_export = 1 -total = 1 -yby_export = 1 - -[optimization problem] -constraints = 1008 -non-zero coefficients = 15894 -variables = 1512 - -[study] -antares version = 831 -areas = 3 -enabled bc = 0 -enabled daily bc = 0 -enabled hourly bc = 0 -enabled thermal clusters = 1 -enabled weekly bc = 0 -links = 2 -max parallel years = 1 -ortools solver = xpress -ortools used = true -performed years = 1 -unit commitment = fast -``` - -## v8.3.0 -### Input -In file **settings/generaldata.ini**, add section `adequacy patch`, with properties - -* `include-adq-patch` [bool]. Default value = `false` -* `set-to-null-ntc-from-physical-out-to-physical-in-for-first-step` [bool]. Default value = `true` -* `set-to-null-ntc-between-physical-out-for-first-step` [bool]. Default value = `true` - -In existing section `optimization`, add property `include-split-exported-mps` [bool]. Default value = `false` - -Add variables `DENS` and `Profit by plant`, which may be used for thematic trimming, see file **settings/generaldata.ini**, section `variables selection`. - -For each area, add a new file **input/areas/<area>/adequacy_patch.ini** containing a single section `adequacy-patch`. This section contains a single property `adequacy-patch-mode`, that can take values - -* `outside` -* `inside` -* `virtual` - -Example -``` -[adequacy-patch] -adequacy-patch-mode = outside -``` - -### Output -* If `include-adq-patch` is set to `true`, add column `DENS` in files **values-<period>.txt** (mc-all & mc-ind) -* Add `Profit by plant` column in files **details-<period>.txt** (mc-all & mc-ind) -* If `include-split-exported-mps` is set to `true`, create split MPS files in the output folder -* Add file **time_measurement.txt**, containing performance data - -NOTE: **period** can be any of the following - -* `hourly` -* `daily` -* `weekly` -* `monthly` -* `annual` - -## v8.2.0 -### Input -* For each link, the first two columns of file **input/links/<area 1>/<area 2>.txt** have been moved to **input/links/<area 1>/capacities/<area 2>_direct.txt** and **input/links/<area 1>/capacities/<area 2>_indirect.txt** respectively. Note that these two files may contain more than one column, but must contain the same number of columns. The 6 remaining columns have been moved to area **input/links/<area 1>/<area 2>_parameters.txt**. - -* In file **settings/generaldata.ini**, add `hydro-debug` [bool] key to existing section `output`. Default value is `false`. - -### Output -If parameter `hydro-debug` is enabled, a **debug** directory is created in the output folder. diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md deleted file mode 100644 index eebcbeda5f..0000000000 --- a/docs/reference-guide/14-adequacy-patch.md +++ /dev/null @@ -1,237 +0,0 @@ -# Adequacy Patch calculation - -## Foreword - -The operational algorithm of Euphémia market coupling implements "de-optimization" rules in order to fix the sharing of “Energy Not Served†(ENS) between the market areas when there is any (in a way to ensure a certain fairness in the sharing of this ENS): this is what we call the adequacy patch. -The requirement of fairness rules in the sharing of ENS within Antares studies increased with the introduction of flow-based modelling. Previously, this problem was mainly solved with the hurdle cost mechanism (small costs on interconnections) limiting exports from areas where ENS was encountered. However, implicit rules in Antares for sharing ENS, even outside the Flow-Based domain, are not fully satisfactory, even with hurdle costs, because they prioritize the treatment of ENS in countries directly connected to countries with margins, to the detriment of more distant countries. In a context of decommissioning of coal and nuclear plants in France and in Europe, cases of simultaneous ENS over the domain will increase. Consequently, the need of adequacy patch to share fairly this ENS is arising. - -It should be noted that, in the current implementation of the patch within Antares, the implementation covers only one of the three main features of the ‘curtailment sharing and minimization’ principles in EUPHEMIA, namely: - -1. Local matching constraint. - -2. Secondary problem of sharing of curtailment by the quadratic term. - -3. The implemented solution does not yet consider the feature in EUPHEMIA, related to ‘minimization of curtailment’ in the primal problem which includes an extra penalty term directly in the global objective function in EUPHEMIA by multiplying the maximum curtailment ratio with a large M pre-factor in the total welfare. - -## Local matching rule (Antares Simulator 8.3) - -The rule implemented is called the « Local Matching » rule: - -- This rule consists in satisfying **ENS \\(\leq\\) DENS** (Domestic Energy not Served) for all physical areas inside the adequacy patch. -- It specifies that an area cannot export more than its local margin. - -This means that an area which can serve local demand with local generation, should never have ENS. - -_**Notes**_ - -- _The local matching rule is only part of the economic mode of Antares (Not the Adequacy mode);_ -- _DENS outputs of Antares, for all selected areas, are available in the General values tab, as year-by-year and synthetic results. All the statistic values for it are calculated as well (min, max, mean, standard deviation). For the areas not part of the patch, the output DENS is set to 0._ - -### Specifications of the evolution concerning the optimization problem - -To calculate the DENS used to constrain the ENS variations of each area, a first iteration is performed. During this first iteration, the usual optimization problem is slightly modified before being solved. The objective of this first iteration is to get an ENS of each area which will represent its DENS. In order to achieve this, links between areas are forced to have a capacity of 0. To ensure that customizable models will still work using this new feature, different categories are created for the areas, enabling different behaviours as needed. The different categories are: - -- "virtual": The area is a virtual area, -- "physical outside": The area is a physical area not included in the adequacy patch domain, -- "physical inside": The area is a physical area included in the adequacy patch domain. - -In case Flow-Based is represented in the study, the "hub" node introduced for the Flow-based modelling should also be included in the list of physical areas (this one should be declared by the user in its list of physical nodes). - -#### First iteration - -In the first iteration, the following link capacities in the following direction will be set to 0 MW: - -- node "physical inside" <-> node "physical inside" -- node "physical inside" -> node "physical outside" -- node "physical outside" -> node "physical inside": optional/user defined (default `true`), -- node "physical outside" <-> node "physical outside": optional/user defined (default `true`). - -Once the first iteration is completed, we have access to the DENS value, which represents the ability of an area to fulfil its local load thanks to its local production capacities: -- DENS = ENS for each physical area inside the adequacy patch perimeter - -#### Second iteration - -During the second iteration, all link capacities between physical nodes are set to the values provided as input data (as it is done in the current Antares version). The only change compared to a simulation without the adequacy patch is that the upper bound of the ENS on the areas included in the patch is now constrained by the DENS found during the first iteration. This is introduced in the optimization problem for physical areas that are declared in the adequacy patch domain (areas declared as "physical inside"): - -- ENS $\le$ DENS - (for all physical areas inside the adequacy patch). - -## Curtailment sharing rule (Antares Simulator 8.5) - -The second implemented rule is called the « Curtailment Sharing » rule (henceforth CSR). - -The idea is that when countries on the network have positive DENS, they should have relatively similar levels of unsupplied energy (as the name suggests, so that the curtailment is shared). The quantity that is to be measured and compared across countries is: ENS/PTO where PTO is the Price Taking Orders. There are different options of defining the PTOs. In this development we will consider two: - -- PTOs are the DENS of the country -- PTOs are the Load of the country - -The considered countries are only nodes “2†(areas defined as physical areas inside the adequacy patch), the problem to be solved is an hourly problem. Precisely, the hourly problem to be solved concerns only hours for which of the sum of the ENS in all nodes “2†is exceeding a user-defined threshold. If it is not the case, all the treatments described below should be ignored for this hour and the algorithm should then consider the next hour. So, at that step, we will solve the CSR quadratic optimization problem on a reduced domain, limited to nodes “2†and the links that exist between these nodes 2. - -_**Notes**_ - -- _Local matching and curtailment sharing rule are only part of the economic mode of Antares (Not the Adequacy mode);_ - -_**Convention**_: - -- _A is any node of type “2†in the network, an area that is defined as a physical area inside the adequacy patch. Each variable/parameter/constraint applied on A is implicitly applied to any node of type "2â€;_ -- _B represents any node of type "2†linked to A;_ -- _A is alphabetically before B, therefore their link in Antares would be called A/B. Furthermore, regarding the flow on this link (variable that contains the algebraic value of the power flow between the 2 nodes to be optimized):_ - - _if the flow value is positive, the power flow goes from node A to node B, it is an export for node A and an import for node B;_ - - _if the flow value is negative, the power flow goes from node B to node A, it is an import for node A and an export for node B._ - -### Variable definitions - -- Flows over links variables (3 set of variables: “Flowâ€, “Flow_direct†and “Flow_indirect"): -Inside the optimization problem, the “flow†variable is actually split in 2 positive variables for the resolution. It is required in order to write some constraints. We define the 2 positive variables, “Flow_direct†and “Flow_indirect†with this simple relation: -Flow = Flow_direct – Flow_indirect - -- “net_position†variable: -“net_position (node A)†is the balance between node A and all other nodes “2†connected to node A. - -- “ENS†variable: -“ENS (node A)†contains the ENS to be optimized for that node. - -- “Spillage†variable: -“Spillage (node A)†contains the Spillage to be optimized for that node. - -### Parameter definitions - -- “net_position_init†parameter: -The “net_position_init (node A)†parameter value is the value of the “net_position†calculated from the output of the Antares calculation for node A, considering results we get from the Antares calculation at the end of Local matching rule optimization. - -- “ENS_init†parameter: -The “ENS_init (node A)†parameter value is the value of the “ENS†obtained from the output of the Antares calculation for node A at the end of Local matching rule optimization. - -- “DENS_new†parameter: The “DENS_new (node A)†parameter value is an update of the value of the “DENS†parameter which takes into account the result of Antares calculation (therefore different than the one estimated in Local matching rule optimization). - -- “Spillage_init†parameter: -The “Spillage_init (node A)†parameter value is the value of the “Spillage†obtained from the output of the Antares calculation for node A at the end of Local matching rule optimization. - -- “Hurdle cost†parameter on links: -This parameter, fixed on links, is kept from the Antares optimization problem. -Like “flows†we can split “Hurdle cost†in “Hurdle_cost_direct†and “Hurdle_cost_indirect†- -### Constraints and relations between variables - -- **Constraints on “Flowsâ€, “Flow_direct†and “Flow_indirect†variables:** -These variables should have exactly the same constraints than the ones considered in the Antares problem: - - - NTC constrains (independent lower and upper bounds for each link). - - Flowbased binding constraints to be extracted from the hourly binding constraint list. - -- **Relation between “Flows†over links and “net_position†on nodes:** -The value of “net_position (node A)†is deduced from “flow†variable as follows: - - - net_position (node A) = $\sum$ algebraic “Flows†over links involving node A - Remember that: - - - a “Flow†that goes from another node “2†to node A is an import for node A and should be counted positively - - a “Flow†that goes from node A to another node “2†is an export for node A and should be counted negatively. - -- **The detailed formulation for calculating the value of “net_position (node A)†is, for all “nodes 2 upstream†and all “nodes 2 downstreamâ€:** - - net_position (node A) = $\sum$ flow_direct (node 2 upstream -> node A) + $\sum$ flow_indirect (node A <- node 2 downstream) - $\sum$ flow_indirect (node 2 upstream <- node A) - $\sum$ flow_direct (node A -> node 2 downstream) - - Considering that: - - - “Node 2 upstream†is any node “2†which name in alphabetic order is before node A - - “Node 2 downstream†is any node “2†which name in alphabetic order is after node A - -- **Formula for calculating DENS_new parameter:** - - DENS_new (node A) = max [ 0; ENS_init (node A) + net_position_init (node A) - DTG.MRG (node A)] - - Depending on the parameter in the GUI that includes or not possible imports from nodes “1†to nodes “2†in the DENS calculation, we should modify this formula. Precisely, it is when “NTC from physical areas outside to physical areas inside adequacy patch†is set to null then the formulation such be modified as follows: - - - DENS_new (node A) = max [ 0; ENS_init (node A) + net_position_init (node A) + $\sum$ flows (node 1 -> node A) - DTG.MRG (node A)] - - The detailed formulation for calculating the last term is, for all “nodes 1 upstream†and all “nodes 1 downstreamâ€: - - - $\sum$ flows (node 1 -> node A) = $\sum$ flow_direct (node 1 upstream -> node A) + $\sum$ flow_indirect (node A <- node 1 downstream) - - Considering that: - - “Node 1 upstream†is any node “1†which name in alphabetic order is before node A - - “Node 1 downstream†is any node “1†which name in alphabetic order is after node A - - The consideration of a correct DENS_new as presented above should ensure that the Local Matching Approach is respected, (node A) can’t be "Exporting†and having ENS after CSR. - -- **Relation induced by node balancing conservation:** - - ENS (node A) + net_position (node A) – spillage (node A) = ENS_init (node A) + net_position_init (node A) – spillage_init (node A) - - Actually, this simplified formulation takes into account that these variables are the only ones we are allowed to update by this optimization (power generation for all nodes and power flows between other nodes than nodes “2†will not be modified). - -- **Constraint induced by Local matching rule:** - - - ENS (node A) $\le DENS_{new}(node~A)$ - -- **Positivity constraints:** - - - ENS (node A) $\ge$ 0 - - spillage (node A) $\ge$ 0 - -_**Notes**_ - -- _“Spillage†variable and “Spillage_init†parameter have been introduced only to deal with some situations for which “Flowbased†constraints, combining with adequacy patch rules, lead to an increase of Total ENS over the different nodes “2â€. Such increase of Total ENS could happen for 2 reasons:_ - - - _We have new violations of Local Matching rule and the optimal solution found by Antares is no longer a valid solution, regards to this rule;_ - - _The curtailment sharing rule target is to minimize $\sum$(ENS$^2$/PTO) and such objective is not exactly equivalent than minimizing Total ENS._ - - _As a matter of fact, if we sum over all nodes “2†the relation induced by node balancing conservation, as the sum of all “net_position†is null, it leads to:_ - - - _Total ENS – Total Spillage = Total ENS_init – Total Spillage_init, over all nodes “2â€_ - - _So, an increase of Total ENS will necessarily leads to the same increase of Total Spillage._ - -- _Spillage results after curtailment sharing rule quadratic optimization are presented in the separate column inside Antares output, titled “SPIL. ENRG. CSR†so the user has access to the spillage results both prior to and after CSR optimization._ -- _In order to avoid solver issues, lower and upper boundaries of the ENS and Spillage variables can be relaxed using GUI option “Relax CSR variable boundariesâ€. Following relaxations can be imposed:_ - - $-10^{-m} \le ENS(node~A) \le DENS_{new} (node~A) + 10^{-m}$ - - $-10^{-m} \le spillage(node~A) \le + \infty$ - - Where $m$ is an integer defined by the user. - -### Objective function - -- Minimize $\left[ \sum\frac{ENS^2}{PTO} + \sum \frac{1}{M} \left( hurdle cost direct \times flow direct \right) + \sum \frac{1}{M} \left( hurdle cost indirect \times flow_ indirect \right) \right]$ - -The 2 latest terms are introduced to minimize loop flows in the considering domain, and $M$ is the highest curtailment cost between a links's origin and destination nodes, used to adapt the scale of hurdle costs to this new objective (in practice, those tend to be the same for all nodes, typically 3000€/MW or 10000€/MW). -In order to assess the quality of the CSR solution additional verification can be imposed by activating GUI option “Check CSR cost function value prior and after CSR optimizationâ€. Values of the objective function prior to and after quadratic optimization will be calculated and compared. If the objective function value after the quadratic optimization has decreased, the new CSR solution will be accepted and presented in the Antares output. However, if after quadratic optimization the objective function value has increased (or stayed the same), LMR solution will be adopted as the final one and warning will be logged out with the appropriate information (year, hour cost prior to quad optimization, cost after quadratic optimization). - -- $QUAD 0 = \left[ \sum \frac{ENS init^2}{PTO} + \sum \frac{1}{M} \left( hurdle cost direct \times flow direct init \right) + \sum \frac{1}{M} \left( hurdle cost indirect \times flow indirect init \right) \right]$ -- $QUAD 1 = \left[ \sum \frac{ENS final^2}{PTO} + \sum \frac{1}{M} \left( hurdle cost direct \times flow direct final \right) + \sum \frac{1}{M} \left( hurdle cost indirect \times flow indirect final \right) \right]$ - -If: - -- $QUAD 0 \le QUAD 1$ -(CSR does not improve QUAD) then the “_init†solution is kept and the CSR solution is hence disregarded. -- $QUAD 0 > QUAD 1$ -(CSR does improve QUAD) then the “CSR†solution is kept as final result updating the “_init†solution as stated above. - -### Post-optimization process - -For the CSR triggered hours, if after quadratic optimization, area inside adequacy patch still experiences unsupplied energy: - -- ENS (node A) > 0 - -following adjustments will be performed. Available dispatchable margin “DTG MRG†will be used to compensate for the residual unsupplied energy ENS: - -- ENS (node A) = max[0.0, ENS (node A) - DTG.MRG (node A)] - -Remaining dispatchable margin after above-described post-optimisation calculation is stored inside new column “DTG MRG CSR†- -- DTG.MRG.CSR (node A) = max[0.0, DTG.MRG (node A) - ENS (node A)] - -Note that for all the hours for which curtailment sharing rule was not triggered, as well as for the hours for which curtailment sharing rule was triggered but after quadratic optimization ENS (node A) is equal to zero, DTG.MRG.CSR (node A) will be equal to DTG.MRG (node A). For the curtailment sharing rule triggered hours, if after quadratic optimization and above-described post calculation process, area inside adequacy patch still experiences unsupplied energy, marginal price “MRG.PRICE†will be aligned with the price cap in the model (set to Unsupplied Energy Cost in the results). - -- MRG.PRICE (node A) = Unsupplied Energy Cost (node A) - -_**Notes**_ - -- _SPIL. ENRG. CSR and DTG MRG CSR outputs of Antares, for all selected areas, are available in the General values tab, as year-by-year and synthetic results. All the statistic values for it are calculated as well (min, max, mean, standard deviation). For the areas not part of the patch, the default output is set to 0._ -- _LMR VIOL. outputs of Antares, for all selected areas, are available in the General values tab, as year-by-year and synthetic results. For the areas not part of the patch, the default output is set to 0. -LMR violation check is performed for all hours (CSR triggered or not) after LMR linear optimization (prior to CSR quadratic optimization). Hourly value of LMR violation is set to value one if all following conditions are met:_ - - - _ENS_init (node A) > 0;_ - - _net_position_init (node A) + $\sum$ flows (node 1 -> node A) < 0;_ - - _Abs[net_position_init (node A) + $\sum$ flows (node 1 -> node A)] > ENS_init (node A) + GUI_defined_threshold._ - - _Second equation is satisfied if the area is exporting power. Depending on the GUI option member ($\sum$ flows (node 1 -> node A)) is optional._ - - diff --git a/docs/reference-guide/15-executable_kirchhoffs_constraint_generator.md b/docs/reference-guide/15-executable_kirchhoffs_constraint_generator.md deleted file mode 100644 index 6d39d5ea76..0000000000 --- a/docs/reference-guide/15-executable_kirchhoffs_constraint_generator.md +++ /dev/null @@ -1,33 +0,0 @@ -# Executable Kirchhoff's Constraint Generator - -The kirchhoff constraint generator is a standalone tool used to automatically create kirchhoff constraints. For more details about this process read: - -[7-kirchhoffs_constraint_generator.md](https://github.com/AntaresSimulatorTeam/Antares_Simulator/blob/develop/docs/reference-guide/07-kirchhoffs_constraint_generator.md) - -The binary is located in Antares_Simulator/bin/ - ---- - -## Usage - -**./antares-8.3-kirchhoff-constraints-builder** [study_path] [option_file_path] - -## Options - -**study_path**: the path of the study, mandatory - -**option_file_path**: Optional. The path of the **constraintbuilder.ini** file. It's normally located in *study_path/settings/*. If not provided the constraint builder will take the default values, which are defined at the end of cbuilder.h. - -Those values were used to fill the GUI default values, and then the GUI created the file. That's why it's optional since only the default values are guaranteed to work. - -## Results - -New constraints generated this way will be stored in *input/bindingconstraints/* with the name uto_0001.txt, with incrementing numbers. The file *bindingconstraints.ini* located in the same directory will be updated accordingly. - -## Study components needed - -The study only needs to include the following components to generate kirchhoff constraints: - -- Areas (contains links) -- Binding Constraints -- version number \ No newline at end of file diff --git a/docs/reference-guide/15-output-variables.md b/docs/reference-guide/15-output-variables.md deleted file mode 100644 index e482646fa8..0000000000 --- a/docs/reference-guide/15-output-variables.md +++ /dev/null @@ -1,15 +0,0 @@ -# New output variables - -| Version | Variable(s) introduced | Files | Enabled by default | -|---|---|---|---| -| 8.0 | none | | | -| 8.1 | WIND OFFSHORE, WIND ONSHORE, SOLAR CONCRT., SOLAR PV, SOLAR ROOFT, RENW. 1, RENW. 2, RENW. 3, RENW. 4 | values-*.txt | yes | -| 8.1 | MISC. DTG 2, MISC. DTG 3, MISC. DTG 4 | values-*.txt | yes | -| 8.2 | none | | | -| 8.3 | DENS | values-*.txt | no | -| 8.3 | Profit by plant | details-*.txt | yes | -| 8.4 | BC. MARG. COST | binding-constraints-*.txt | no | -| 8.5 | LMR VIOL., SPIL. ENRG. CSR, DTG MRG CSR | values-*.txt | no | -| 8.6 | PSP_open_injection, PSP_open_withdrawal, PSP_open_level, PSP_closed_injection, PSP_closed_withdrawal, PSP_closed_level, Pondage_injection, Pondage_withdrawal, Pondage_level, Battery_injection, Battery_withdrawal, Battery_level, Other1_injection, Other1_withdrawal, Other1_level, Other2_injection, Other2_withdrawal, Other2_level, Other3_injection, Other3_withdrawal, Other3_level, Other4_injection, Other4_withdrawal, Other4_level, Other5_injection, Other5_withdrawal, Other5_level | values-*.txt | yes | -| 8.6 | STS inj by plant, STS withdrawal by plant, STS lvl by plant | details-STstorage-*.txt | yes | -| 8.6 | CO2 EMIS., NH3 EMIS., SO2 EMIS., NOX EMIS., PM2_5 EMIS., PM5 EMIS., PM10 EMIS., NMVOC EMIS., OP1 EMIS., OP2 EMIS., OP3 EMIS., OP4 EMIS., OP5 EMIS. | values-*.txt | yes | diff --git a/docs/reference-guide/16-xpress.md b/docs/reference-guide/16-xpress.md deleted file mode 100644 index 591e086fbe..0000000000 --- a/docs/reference-guide/16-xpress.md +++ /dev/null @@ -1,47 +0,0 @@ -# Usage with FICO® Xpress Optimization - -## Introduction -The FICO Xpress optimizer is a commercial optimization solver for linear programming (LP), mixed integer linear programming (MILP), convex quadratic programming (QP), convex quadratically constrained quadratic programming (QCQP), second-order cone programming (SOCP) and their mixed integer counterparts. - -Antares Solver only uses LP, with plans to use MILP at some point in the future. Various benchmarks have revealed that Xpress allows faster simulations than Sirius on large studies. - -## Using Xpress in the command-line -``` -antares-x.y-solver --use-ortools --ortools-solver xpress [options] -``` - -## Setup -The `XPRESSDIR` env variable must point to the Xpress install directory. The author strongly suggest placing this in your .bashrc if you use Bash -``` -export XPRESSDIR=path/to/xpress/install/dir -``` - -An Xpress install directory looks like this. Actually, only these files are required, the rest are unnecessary -``` -xpress814 <= XPRESSDIR -└── lib - ├── libxprs.so -> libxprs.so.40 - ├── libxprs.so.40 <= The Xpress shared library - └── xpauth.xpr <= A valid licence -``` - -## Checking that Xpress works -After setting up Xpress, the following command line should display a line if Xpress is installed and a valid licence is found. -``` -antares-x.y-solver --list-solvers | grep xpress -``` - -## Compatibility -Antares Simulator 8.x has been shown to work with Xpress 8.13.0. Trying to use other versions may work, but can lead to crashes. - -## Known issues -### Performance issues with Xpress 9.x -The following Xpress versions suffer a performance regression that makes them unsuitable for use with Antares Simulator -- 9.0.x -- 9.1.x -- 9.2.x - -As of Q3 2023, it is best to stick to Xpress 8.13.0 for best performance - -### Community license is very restrictive -FICO offers a Community License for testing purposes. It should be noted however that it is extremely restrictive. You may experience issues when trying to run Antares Solver with this license, even on small test-cases. diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css index f778681ac1..a4abde6c67 100644 --- a/docs/stylesheets/extra.css +++ b/docs/stylesheets/extra.css @@ -9,3 +9,14 @@ --md-hue: 213; /* [0, 360] */ --md-accent-fg-color: #ff9800; } +/* Use this class for images with transparent background, it will add padding and a white background in dark mode */ +.add-padding-and-white-bg { + padding: 20px; +} +[data-md-color-scheme="slate"] .add-padding-and-white-bg { + background-color: whitesmoke; +} +/* De-activate mkdocs' default h5 styling, which puts the h5 header in upper case */ +.md-typeset h5 { + text-transform: none; +} \ No newline at end of file diff --git a/docs/user-guide/00-index.md b/docs/user-guide/00-index.md new file mode 100644 index 0000000000..892cf400b5 --- /dev/null +++ b/docs/user-guide/00-index.md @@ -0,0 +1,13 @@ +[//]: # (Index used by Sphinx to generate correct PDF tree) + +```{toctree} +:hidden: +01-overview.md +02-install.md +03-getting_started.md +solver/00-index.md +ts-analyzer-generator/00-index.md +other-features/00-index.md +04-migration-guides.md +05-attribution-notices.md +``` \ No newline at end of file diff --git a/docs/user-guide/01-overview.md b/docs/user-guide/01-overview.md new file mode 100644 index 0000000000..ddc3b03c60 --- /dev/null +++ b/docs/user-guide/01-overview.md @@ -0,0 +1,76 @@ +# Overview + +This user guide describes all the main features of the *Antares Simulator*[^1] package. +[^1]: For simplicity's sake, the *Antares Simulator* application will be simply denoted *Antares*. + +It gives useful general information regarding the way data are handled and processed. +Since the *Antares* GUI support has been dropped (in favor of [Antares Web](https://antares-web.readthedocs.io)), +all its documentation has been removed. If you are still using an old version of *Antares* GUI, you can still find +its documentation in the assets of the release, or by browsing older versions of the documentation website. + +Real-life use of the software involves a learning curve process that cannot be supported by a +simple user guide. In order to be able to address this basic issue, two kinds of resources may be used: + +- The ["examples"](https://github.com/AntaresSimulatorTeam/Antares_Simulator_Examples) library, which is meant + as a self-teaching way to learn how to use the software. It is regularly enriched with the software's new features. + The contents of this library depend on the installation package it comes from (public version vs. users' club version). +- The [https://antares-simulator.org](https://antares-simulator.org/) website + +If you notice an issue in the documentation, please report it on [github.com](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/new/choose). + +## Applications + +In terms of power studies, the fields of application *Antares* has been designed for are: + +- **Generation adequacy problems** +- **Transmission project profitability** + +### Generation adequacy problems +**Adequacy** problems aim to study the need for new generating plants to keep the security of +supply above a given critical threshold. + +What is most important in these studies is to survey a great number of scenarios that represent well enough +the random factors that may affect the balance between load and generation. Economic parameters do not play +as much a critical role as they do in the other kinds of studies since the stakes are mainly to know if and +when supply security is likely to be jeopardized (detailed costs incurred in more ordinary conditions are of +comparatively lower importance). In these studies, the default *Antares* option to use is the +[`adequacy`](18-parameters.md#mode) simulation mode. + +### Transmission project profitability +[//]: # (TODO: explain what "fair and perfect market" means) +**Transmission project profitability** studies the savings brought by a specific reinforcement of the grid, +in terms of decrease of the overall system generation cost (using an assumption of a fair and perfect market) +and/or improvement of the security of supply (reduction of the loss-of-load expectation). + +In these studies, economic parameters and the physical modeling of the dynamic constraints bearing on +the generating units are of paramount importance. Though a thorough survey of many "Monte-Carlo years" +is still required, the number of scenarios to simulate is not as large as in generation adequacy studies. +In these studies, the default *Antares* option to use is the [`economy`](18-parameters.md#mode) simulation mode. + +## Performance considerations +Typically, *Antares* has to solve a least-cost hydro-thermal power schedule and unit commitment problem, with an hourly +resolution and throughout a week, over a large interconnected system. +The large number and the size of the individual problems to solve often make optimization sessions computer-intensive. + +Depending on user-defined results accuracy requirements, various practical options[^2] allow to simplify either +the formulation of the problems, or their resolution. +[^2]: See [hydro-pricing-mode](solver/04-parameters.md#hydro-pricing-mode), [unit-commitment-mode](solver/04-parameters.md#unit-commitment-mode) + +[//]: # (TODO: list in [^2] the other parameters that have impact on performance) + +*Antares* has been designed to handle [adequacy and profitability problems](#applications). + +The common rationale of the modeling used in all of these studies is, whenever it is possible, +to divide the overall problem (representation of the system behavior throughout many years, +with a time step of one hour) into a series of standardized, smaller problems. + +In *Antares*, the "elementary" optimization problem resulting from this approach is that of the minimization of +the **whole power system**'s operational cost over **one week**, taking into account all proportional and +non-proportional generation costs, as well as transmission charges and "external" costs such as +that of the un-supplied energy (generation shortage) or, conversely, that of the spilled energy (generation excess). +In other words, adequacy and profitability studies are carried out by solving a series of a large number of week-long +operation problems (one for each week of each Monte-Carlo year), assumed to be independent to some extent. +Note that, however, dependency issues such as the management of hydro stock (or any other kind of energy storage +facility) may bring a significant coupling between the successive problems, which needs to be addressed properly[^3]. + +[^3]: See how *Antares* addresses stock dependency between successive problems [here](solver/06-hydro-heuristics.md#seasonal-hydro-pre-allocation). diff --git a/docs/user-guide/02-install.md b/docs/user-guide/02-install.md new file mode 100644 index 0000000000..ffa1c75c37 --- /dev/null +++ b/docs/user-guide/02-install.md @@ -0,0 +1,53 @@ +# Installation + +## System requirements + +### Operating system +*Antares* code is cross-platform. Our releases target a few specific operating systems: + +- Windows 10/11 +- CentOS 7.9 +- Ubuntu 20.04 +- OracleServer 8.9 +- OracleLinux 8 + +If you use any other Windows/Linux/Unix OS, you can still use *Antares*, although you will have to build it from sources +(see next section). + +### Hard drive disk + +Installed alone, the Antares simulator does not require a lot of HDD space (less than 1 GB). Installation packages including companion tools (study manager, graph editor) are however significantly heavier. The proper storage of data (i.e. both Input and Output folders of Antares studies) may require a large amount of space. The disk footprint of any individual study mainly depends on: + +- The size of the power system model (number of Areas, Links, Thermal clusters, etc.) +- The number of ready-made Time-Series and the number of Time-Series to be generated at runtime and stored afterward + (see [these parameters](18-parameters.md#time-series-parameters)). +- The activation of output filters + (see [thematic-trimming](18-parameters.md#thematic-trimming) and [geographic-trimming](18-parameters.md#geographic-trimming) parameters). +- The number of Monte-Carlo years involved in the simulation session, if the storage of detailed + [year-by-year results](18-parameters.md#year-by-year) is activated +- Whether [MPS export](18-parameters.md#include-exportmps) is activated + +If you encounter space issues, consider tweaking the aforementioned parameters or reducing your study size. + +### Memory + +The amount of RAM required for a simulation depends on: + +- The size of the power system model (number of Areas, Links, Thermal clusters, etc.) +- The number of ready-made Time-Series and that of Time-Series to be generated at runtime +- The simulation [mode](18-parameters.md#mode) +- The [unit commitment resolution mode](18-parameters.md#unit-commitment-mode) +- If the [multi-threading](solver/optional-features/multi-threading.md) option is used + +If you encounter memory issues, consider tweaking the aforementioned parameters or reducing your study size. + +## Instructions + +- **Windows 10/11**: download & run installation packages, or executables, available at + [*https://antares-simulator.org*](https://antares-simulator.org/) + or on [GitHub](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases). +- **CentOS 7.9**: download & run installation packages, or executables, available on [GitHub](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases). +- **Ubuntu 20.04**: download & run executables, available on [GitHub](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases). +- **OracleServer 8.9**: download & run installation packages, or executables, available on [GitHub](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases). +- **OracleLinux 8**: download & run executables, available on [GitHub](https://github.com/AntaresSimulatorTeam/Antares_Simulator/releases). +- Any other Windows/Linux/Unix OS: refer to our website to see how to [build *Antares* from sources](../developer-guide/3-Build.md) \ No newline at end of file diff --git a/docs/user-guide/03-getting_started.md b/docs/user-guide/03-getting_started.md new file mode 100644 index 0000000000..ba4ca923a8 --- /dev/null +++ b/docs/user-guide/03-getting_started.md @@ -0,0 +1,77 @@ +# Getting started + +## Organizing your data + +### General information + +In Antares, all input and output data of a given study are located within a folder named after the study +and which should preferably be stored within a dedicated library of studies +(for instance: `C/.../A_name_for_an_Antares_lib/Study-number-one`). + +Note that most of the *Antares* input and output files are either in ".txt" or ".csv" format. Although you may very well +modify them in your favorite text editor, you are not advised to do so, since handling data this way may result in fatal +data corruption (e.g. as a consequence of accidental insertion of special characters). Only manipulate raw input and +output data directly if you are an experienced *Antares* user. +Instead, we advise you to use [Antares Web](https://antares-web.readthedocs.io) or [Antares Extensions](#using-extensions). + +The input data contained in the study folder describe the whole state of development of the interconnected power system +(namely: grid, load and generating plants of every kind) for a given future year. + +Once the input data is ready for calculation purposes, an Antares session may start and involve any or all of +the following steps: historical time-series analysis, stochastic times-series generation, +(full) adequacy simulation and economic simulation. + +The results of the session are stored within the **input or the output** section of the study folder (depending on the session +type, refer to the documentation of the different features for more information). +The results obtained in the different sessions are stored side by side and tagged. +The identification tag has two components: a user-defined session name and the time at which the session was launched. + +Particular cases: +- Some specific input data may be located outside the study folder (this is the case for some inputs of + the [time-series analyzer](other-features/analyzer.md), for example). +- If the study folder contains a specific subfolder named "user", then this folder will have a special status: *Antares* + will consider it as a "private" user space, and avoid deleting any files in it (but files may be updated if the user requires it). + As a consequence, the user is free to store any kind of information in this directory without the risk of it being + modified by *Antares*. + +### Using extensions + +The Antares simulator may be delivered with or without functional extensions that provide additional +ways to handle input and output data. +Many various extensions (programs written in R language) are available: + +- [AntaresEditObject](https://cran.r-project.org/web/packages/antaresEditObject) +- [AntaresRead](https://cran.r-project.org/web/packages/antaresRead) +- [AntaresViz](https://cran.r-project.org/web/packages/antaresViz) + +These extensions take the form of companion applications that are independent of the main simulator. +For information regarding these tools, please refer to the relevant documents. + +## Usual workflow of an *Antares* session + +A typical *Antares* session involves different steps that are usually run in sequence, +either automatically or with some degree of man-in-the-loop control, depending on the kind of study to perform. + +These steps most often involve: + +1. Initializing or updating the input data (time-series, grid topology, fleet description, etc.). + *In this step, the user is expected to provide all the input data they have, except the time-series that are + supposed to be [automatically generated](18-parameters.md#generate) by *Antares* (see step (3)).* + *As stated above, it is highly recommended to use robust tools to produce input data, such as [Antares Web](https://antares-web.readthedocs.io) + or [Antares Extensions](#using-extensions).* +2. Defining the simulation contexts (definition of the "Monte-Carlo years" to simulate) +3. *(Optional)* If some time-series are supposed to be [automatically generated](18-parameters.md#generate), + running a simulation to produce actual numeric scenarios, following the directives defined in (2). + *In this step, the [ts-generator](ts-generator/01-overview-tsgenerator.md) tool should be used.* +4. Running the optimization, to solve all the optimization problems associated with each of the scenarios produced in (3). + *In this step, the main [solver](solver/01-overview-solver.md) tool should be used.* +5. Exploiting the detailed [results](solver/03-outputs.md) yielded by (4). + *In this step, we recommend using [Antares Web](https://antares-web.readthedocs.io) + or [Antares Extensions](#using-extensions).* + +The scope of this user guide is to give a detailed description of the *Antares Simulator* software involved in +steps (1) to (5) mostly based on a functional approach, leaving thereby aside a significant +part of the mathematical content involved in several of these steps. +The following picture gives a functional view of all that is involved in steps (1) to (5). + +![Antares_Process](img/Antares_Process.jpg) diff --git a/docs/user-guide/04-migration-guides.md b/docs/user-guide/04-migration-guides.md new file mode 100644 index 0000000000..c423bc5346 --- /dev/null +++ b/docs/user-guide/04-migration-guides.md @@ -0,0 +1,349 @@ +# Migration guides +This is a list of all recent changes that came with new Antares Simulator features. The main goal of this document is to lower the costs of changing existing interfaces, both GUI and scripts. + +## v9.2.0 +### (TS-generator only) TS generation for link capacities +In files input/links//properties.ini, add the following properties +- tsgen_direct_XXX, +- tsgen_indirect_XXX +with XXX in +- unitcount (unsigned int, default 1) +- nominalcapacity (float) +- law.planned (string "uniform"/"geometric") +- law.forced (same) +- volatility.planned (double in [0,1]) +- volatility.forced (same) + +- "prepro" timeseries => input/links//prepro/_{direct, indirect}.txt, 365x6 values, respectively "forced outage duration", "planned outage duration", "forced outage rate", "planned outage rate", "minimum of groups in maintenance", "maximum of groups in maintenance". +- "modulation" timeseries => input/links//prepro/_mod_{direct, indirect}.txt, 8760x1 values each in [0, 1] +- number of TS to generate => generaldata.ini/General/nbtimeserieslinks (unsigned int, default value 1) + + + +## v9.1.0 +### Input +#### Hydro Maximum Generation/Pumping Power +* For time series ![Migration diagram](img/migration.png "Migration diagram"), for more details, see [this Python script](img/migration.py) + +Regarding Hydro time-series, the scenario builder allows the user to choose, for a given year and area, a different time series whether we consider : +- inflows, ROR and minimum generation, max pumping & generation (prefix "h") +- initial level (prefix "hl") +This implies that, inside one of the previous categories, the number of available time series is the same + +![Logic changes](img/logic-hydro-maxP.png "Logic changes") + +#### Short term storage groups +STS groups in input are now "dynamic" : group names are no longer fixed by code, user is free to define these groups. + +In the "thematic trimming" section, the new dynamic variable `STS by group` is now used to enable/disable all variables (level/injection/withdrawal) for all groups. The following variables are obsolete and must not be provided + +``` +PSP_open_injection +PSP_open_withdrawal +PSP_open_level +... + +Other1_injection +Other1_withdral +Other1_level +... +Other5_injection +Other5_withdral +Other5_level +``` +(3*9=27 variables in total) + +The default value for group is "OTHER1". + +### Output +#### ST Storage + +- Output columns for ST storage are capitalized. For any STS group name my_group, 3 output columns are created : `MY_GROUP_INJECTION`, `MY_GROUP_WITHDRAWAL`, `MY_GROUP_LEVEL`. +- If a group is empty, no column is produced. +- There is now a variable number of columns in files values-XXX.txt, depending on the groups of ST storages provided by the user. Note that groups are case-insensitive, for example `battery`, `Battery` and `BATTERY` all represent the same group. If no ST storage exist for a given area, no variables associated to ST storages will be produced. + +## v9.0.0 +### Input +#### Study version +Breaking change in the study format, file **study.antares** +``` +version = 900 +``` +becomes +``` +version = 9.0 +``` +Compatibility is kept with versions up to 8.8.0. Starting from version 9.0.0, the new format must be used. + + +## v8.8.0 +### Input +#### Short-term storage +If no value is specified for `initiallevel`, then a default value of 50% is used. Note that this value is used only if `initialleveloptim=false`, and that `false` is the default value for `initialleveloptim`. + +Add property `enabled` (bool, default=`true`). If a ST storage object is not enabled, it is ignored by Antares Simulator. + +#### Solver logs (expert option) +Save solver logs by setting `solver-logs = true` (default : `false`) under the `optimization` section. + +#### Experimental "MILP" mode +New value `milp` for existing property `other preferences/unit-commitment-mode` in file **settings/generaldata.ini**. + +Using this property requires OR-Tools and a MILP solver (XPRESS, COIN) + +``` +antares-8.8-solver --use-ortools --ortools-solver coin|xpress ... +``` + +### Output +### Cashflow by short-term storage +In existing file **details-STstorage-<period>.txt** (mc-all & mc-ind), add a new column for each ST storage object, named "STS Cashflow By Cluster", in EURO. + +## v8.7.0 +### Input +#### Scenarized RHS for binding constraints +- For each binding constraint, file **input/bindingconstraints/<id>.txt** is split into 3 files: + - **input/bindingconstraints/<id>_lt.txt** + - **input/bindingconstraints/<id>_gt.txt** + - **input/bindingconstraints/<id>_eq.txt** + + Each of these files can be either empty or have N column of 8674 rows + +- In file **input/bindingconstraints/bindingconstraints.ini**, add property `group` to every section +- Binding constraints in the same group must have the same number of RHS columns (3 files described above for their respective types). Exception: a constraint in a group can have empty RHS or only one RHS column +- In file **settings/scenariobuilder.dat**, add prefix `bc` for every group of binding constraints. The syntax is the following +``` +bc,, = +``` +This line is not mandatory for every group & MC year. If absent, the TS number will be drawn randomly (usual behavior). + +- 0 <= MC Year < generaldata.ini/general.nbyears +- 1 <=TS number <= number of columns for the group + +#### Thermal cluster new properties +For each thermal cluster, in existing file **input/thermal/clusters/<area>/list.ini**, under existing sections **<cluster>**, following properties added: + +* `costgeneration` [string] can take values `useCostTimeseries` or be excluded from the section if `SetManually` is selected (default behavior). +* `efficiency` [float] between 0-100 (default = 100). Unit is "percentage". +* `variableomcost` [float] excluded from the section if default value 0 is selected (default behavior). Unit is Euro / MWh + +For each thermal cluster, new files added **input/thermal/series/<area>/<cluster>/CO2Cost.txt** and **input/thermal/series/<area>/<cluster>/fuelCost.txt**. **fuelCost.txt** and **CO2Cost.txt** must either have one column, or the same number of columns as existing file **series.txt** (availability). The number of rows for these new matrices is 8760. + +#### Hydro Final Reservoir Level +In the existing file **settings/scenariobuilder.dat**, under **<ruleset>** section following properties added (if final reservoir level specified, different from `init`): +* **hfl,<area>,<year> = <hfl-value>** + +### Output +#### Scenarized RHS for binding constraints +Add directory **bindingconstraints** to output directory **ts-numbers**. For every binding constraint group, add a file **ts-numbers/bindingconstraints/<group>.txt** containing the TS numbers used for that group. + +## v8.6.0 +### Input +#### Short-term storage +* Add directories **input/st-storage/clusters** and **input/st-storage/series** +* For each area, add directory **input/st-storage/clusters/<area id>/list.ini** +* This file contains the multiple sections whose name is ignored. Each section contains these properties: + * `name` [str] + * `group` [str]. Possible values: "PSP_open", "PSP_closed", "Pondage", "Battery", "Other1", ... , "Other5". Default Other1 + * `efficiency` [double] in range 0-1 + * `reservoircapacity` [double] > 0 + * `initiallevel` [double] in range 0-1 + * `withdrawalnominalcapacity` [double] > 0 + * `injectionnominalcapacity` [double] > 0 + * `initialleveloptim` [bool] + +* For each short-term-storage object, add the corresponding time-series in directory **input/st-storage/series/<area id>/<STS id>**. All of these files contain 8760 rows and 1 column. + * **PMAX-injection.txt** All entries must be in range 0-1 + * **PMAX-withdrawal.txt** All entries must be in range 0-1 + * **inflows.txt** All entries must be > 0 + * **lower-rule-curve.txt** All entries must be in range 0-1 + * **upper-rule-curve.txt** All entries must be in range 0-1 + +#### Pollutant emission factors +In files **input/thermal/cluster/area/list.ini** add properties `nh3`, `nox`, `pm2_5`, `pm5`, `pm10`, `nmvoc`, `so2`, `op1`, `op2`, `op3`, `op4`, `op5` [double]. These properties are emission factors similar to the existing one for CO2. + +#### Adequacy patch +In file **settings/generaldata.ini**, in section `adequacy patch` add property `enable-first-step` [bool]. Default value = `true` Enable or disable DENS column + +#### Hydro Pmin +For each area, new file added **input/hydro/series/<area>/mingen.txt**. This file has one or more columns, and 8760 rows. The number of columns may be 1, or identical to the number of columns in existing file **mod.txt**. + +### Output +#### Short-term storage +* For every short-term storage group, add 3 columns in files **values-<period>.txt** (mc-all & mc-ind) + * `ST--withdrawal` + * `ST--injection` + * `ST--level` +* For every area, add file **details-STstorage-<period>.txt** (mc-all & mc-ind) containing the same columns, but this time for every short-term storage object. + +#### Pollutant emission factors +In files **economy/mc-all/areas/** add column: CO2 EMIS. One colum for every pollutant: CO2, NH3, NOX, PM2\_5, PM5, PM10, NMVOC, OP1, OP2, OP3, OP4, OP5 + +## v8.5.2 +### Input +In file **settings/generaldata.ini**, in section `optimization`, link-type is now deprecated + +## v8.5.0 +### Input +In file **settings/generaldata.ini**, in section `adequacy patch`, add properties + +* `price-taking-order` [string] can take values `DENS` (default value) and `Load`. +* `include-hurdle-cost-csr` [bool]. Default value = `false` +* `check-csr-cost-function` [bool]. Default value = `false` +* `recompute-dtg-mrg` [bool]. Default value = `false` +* `threshold-initiate-curtailment-sharing-rule` [double]. Default value = `0.0` +* `threshold-display-local-matching-rule-violations` [double]. Default value = `0.0` +* `threshold-csr-variable-bounds-relaxation` [int]. Default value = `3` + +### Output +* If `include-adq-patch` is set to `true`, add column `LMR VIOL.` in files **values-<period>.txt** (mc-all & mc-ind) +* If `include-adq-patch` is set to `true`, add column `SPIL. ENRG. CSR` in files **values-<period>.txt** (mc-all & mc-ind) +* If `include-adq-patch` is set to `true`, add column `DTG MRG CSR` in files **values-<period>.txt** (mc-all & mc-ind) + +## v8.4.0 +### Input +#### Zero/infinite capacity for physical links only +In file **settings/generaldata.ini**, in section `optimization`, change admissible values for key `transmission-capacities` [str]: + +* `local-values` (formerly `true`, default) uses the local capacity of all links +* `null-for-all-links` (formerly `false`) sets the capacity of all links to 0 +* `infinite-for-all-links` (formerly `infinite`) sets the capacity of all links to +infinity +* `null-for-physical-links` sets the capacity of physical links to 0, uses the local capacity for virtual links +* `infinite-for-physical-links` sets the capacity of physical links to +infinity, uses the local capacity for virtual links + +Previous values (`true`, `false` and `infinite`) are still admissible for compatibility. + +### Remove "Split MPS" +In existing section `optimization`, remove property `include-split-exported-mps` [bool]. This property will be ignored (no error) for compatibility. + +#### Result format +In file **settings/generaldata.ini**, in existing section `output`, add property `result-format` [str]. Default value = `txt-files`. If this property is set to `zip`, all results are written into a single zip archive, instead of multiple files. + +### Output +#### Result format +If property `output/result-format` is set to `zip`, all results are stored in a single archive. The hierarchy within this archive remains identical, for example **economy/mc-all/areas/**. Otherwise, txt files are created like in previous versions. + +## v8.3.2 +### Writing MPS files +MPS files of first optimization used to be overwritten by MPS files of second optimization. Not anymore. +Now user can choose to print : +* no MPS file, +* MPS files related to the first optimization (named **problem-<week>-<year>--optim-nb-1.txt**), +* MPS files related to the second optimization (named **problem-<week>-<year>--optim-nb-2.txt**), +* MPS files related to the both optimizations. + +In the **generaldata.ini** input file, corresponding values for **include-exportmps** are : **none**, **optim-1**, **optim-2**, **both-optims**. + +Compatibility with existing values is maintained (**true** = **both-optims**, **false**=**none**). + +### Marginal price of a binding constraint +#### Input +In the context of the addition of a new output variable (marginal price associated to a binding constraint), file **input/bindingconstraints/bindingconstraints.ini** get 2 new parameters for each binding constraint. +They control which marginal price time granularity is printed, either regarding year by year or synthesis results. + +* `filter-year-by-year`. Default value = hourly, daily, weekly, monthly, annual +* `filter-synthesis`. Default value = hourly, daily, weekly, monthly, annual + +#### Marginal cost for binding constraints +Still on the binding constraints marginal price results, 2 new folders **binding_constraints** are created inside any simulation output folder, more precisely under **mc-ind** and **mc-all**. + +Examples : +* **output/yyyymmdd-hhmmeco/economy/mc-ind/00001/binding_constraints** +* **output/yyyymmdd-hhmmeco/economy/mc-all/binding_constraints** + +These folders are meant to contain results of any kind regarding binding constraints marginal price (year by year or synthesis). + +Examples of output files inside these folders : +* **binding-constraints-hourly.txt** +* **binding-constraints-weekly.txt** + +## v8.3.1 +### Output +Add file **execution_info.ini**, containing information about the execution time for the various steps of a study, as well as study related information that affects performance. + +```ini +[durations_ms] +hydro_ventilation = 7 +mc_years = 693 +post_processing = 0 +study_loading = 51 +synthesis_export = 731 +total = 1526 +yby_export = 114 + +[number_of_calls] +hydro_ventilation = 1 +mc_years = 1 +post_processing = 1 +study_loading = 1 +synthesis_export = 1 +total = 1 +yby_export = 1 + +[optimization problem] +constraints = 1008 +non-zero coefficients = 15894 +variables = 1512 + +[study] +antares version = 831 +areas = 3 +enabled bc = 0 +enabled daily bc = 0 +enabled hourly bc = 0 +enabled thermal clusters = 1 +enabled weekly bc = 0 +links = 2 +max parallel years = 1 +ortools solver = xpress +ortools used = true +performed years = 1 +unit commitment = fast +``` + +## v8.3.0 +### Input +In file **settings/generaldata.ini**, add section `adequacy patch`, with properties + +* `include-adq-patch` [bool]. Default value = `false` +* `set-to-null-ntc-from-physical-out-to-physical-in-for-first-step` [bool]. Default value = `true` +* `set-to-null-ntc-between-physical-out-for-first-step` [bool]. Default value = `true` + +In existing section `optimization`, add property `include-split-exported-mps` [bool]. Default value = `false` + +Add variables `DENS` and `Profit by plant`, which may be used for thematic trimming, see file **settings/generaldata.ini**, section `variables selection`. + +For each area, add a new file **input/areas/<area>/adequacy_patch.ini** containing a single section `adequacy-patch`. This section contains a single property `adequacy-patch-mode`, that can take values + +* `outside` +* `inside` +* `virtual` + +Example +``` +[adequacy-patch] +adequacy-patch-mode = outside +``` + +### Output +* If `include-adq-patch` is set to `true`, add column `DENS` in files **values-<period>.txt** (mc-all & mc-ind) +* Add `Profit by plant` column in files **details-<period>.txt** (mc-all & mc-ind) +* If `include-split-exported-mps` is set to `true`, create split MPS files in the output folder +* Add file **time_measurement.txt**, containing performance data + +NOTE: **period** can be any of the following + +* `hourly` +* `daily` +* `weekly` +* `monthly` +* `annual` + +## v8.2.0 +### Input +* For each link, the first two columns of file **input/links/<area 1>/<area 2>.txt** have been moved to **input/links/<area 1>/capacities/<area 2>_direct.txt** and **input/links/<area 1>/capacities/<area 2>_indirect.txt** respectively. Note that these two files may contain more than one column, but must contain the same number of columns. The 6 remaining columns have been moved to area **input/links/<area 1>/<area 2>_parameters.txt**. + +* In file **settings/generaldata.ini**, add `hydro-debug` [bool] key to existing section `output`. Default value is `false`. + +### Output +If parameter `hydro-debug` is enabled, a **debug** directory is created in the output folder. diff --git a/docs/user-guide/05-attribution_notices.md b/docs/user-guide/05-attribution_notices.md new file mode 100644 index 0000000000..082f56c490 --- /dev/null +++ b/docs/user-guide/05-attribution_notices.md @@ -0,0 +1,44 @@ +# APPENDIX : ATTRIBUTION NOTICES + +**Antares\_Simulator** + +**Copyright 2007-2024, RTE (https://www.rte-france.com) - Authors: The Antares\_Simulator Team** + +This user guide is part of *Antares\_Simulator: Adequacy and Performance assessment for interconnected energy networks*. + +Antares\_Simulator is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public +Licence 2.0 as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. + +There are special exceptions to the terms and conditions of the license as they are applied to this software. +View the full text of the exceptions in file COPYING.txt in the directory of a distribution of the software in source form. + +Antares\_Simulator 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 Mozilla Public Licence 2.0 for more details. + +You should have received a copy of the Mozilla Public Licence 2.0 along with Antares\_Simulator. +If not, see [https://opensource.org/license/mpl-2-0/](https://opensource.org/license/mpl-2-0/). + +**Antares\_Simulator 8.3 uses external libraries and makes extensive use of the following persons' or companies code. +Source and binary forms of these programs are distributed along with Antares\_Simulator with NO WARRANTY:** + +- Wxwidgets 3.1.3 Copyright (c) 1998-2017 The wxWidget Team + [https://github.com/wxWidgets/wxWidgets.git](https://github.com/wxWidgets/wxWidgets.git) + license: wxWindows Library License,V3.1 [https://spdx.org/licenses/wxWindows.html](https://spdx.org/licenses/wxWindows.html) + +- libYuni 1.1.0 [https://github.com/libyuni](https://github.com/libyuni) + license: Mozilla Public License 2.0 [https://spdx.org/licenses/MPL-2.0.html](https://spdx.org/licenses/MPL-2.0.html) + +- Mersenne Twister Copyright (c) 1997-2002 M.Matsumoto and T.Nishimura + license: 3-clause BSD [https://spdx.org/licenses/BSD-3-Clause.html](https://spdx.org/licenses/BSD-3-Clause.html) + +- strtod library Copyright (c) 1988-1993 The Regents of the University of California + Copyright (c) 1994 Sun Microsystems, Inc + license: ISC license [https://spdx.org/licenses/ISC.html](https://spdx.org/licenses/ISC.html) + +- Sirius\_Solver Copyright (c) 2007-2018 RTE + [https://github.com/rte-france/sirius-solver.git](https://github.com/rte-france/sirius-solver.git) + license: Apache 2.0 [https://spdx.org/licenses/Apache-2.0.html](https://spdx.org/licenses/Apache-2.0.html) + +- OR-Tools Copyright (c) 2010-2020 Google LLC + [https://github.com/rte-france/or-tools.git](https://github.com/rte-france/or-tools.git) + license: Apache 2.0 [https://spdx.org/licenses/Apache-2.0.html](https://spdx.org/licenses/Apache-2.0.html) diff --git a/docs/user-guide/99_to_be_classified.md b/docs/user-guide/99_to_be_classified.md new file mode 100644 index 0000000000..88e9456a08 --- /dev/null +++ b/docs/user-guide/99_to_be_classified.md @@ -0,0 +1,41 @@ +# Active windows + +[//]: # (TODO: fetch important content & remove this page) + +## Simulation + +The main simulation window is divided up in two parts. On the left side are the general parameters while the right side is devoted to the time-series management. + +These two parts are detailed hereafter. + + +### RIGHT PART: Time-series management + +For the different kinds of time-series that Antares manages in a non-deterministic way (load, thermal generation, +hydro power, hydro max power, wind power, solar power or renewable depending on the option chosen): + +1. **Choice of the kind of time-series to use** +Either « ready-made » or «stochastic » (i.e. Antares-generated), defined by setting the value to either "on" or "off". +2. Exception is hydro max power that can only be « ready-made ». Note that for Thermal time-series, the cluster-wise +3. parameter may overrule this global parameter (see Thermal window description below). + +2. **For stochastic TS only**: + + - **Seasonal correlation** ("monthly" or "annual") Indicates whether the spatial correlation matrices to use are + defined month by month or if a single annual matrix for the whole year should rather be used (see [Time-series analysis and generation](06-time_series_analysis_and_generation.md)) + + - **Store in output** + - **Yes**: the generated times-series will be stored as part of the simulation results + - **No**: no storage of the generated time-series in the results directories + +3. **General rules for building up the MC years** + - **Intra-modal**: + - **Yes** For each mode, the same number should be used for all locations (or 1 where there is only one TS), + but this number may differ from one mode to another. For instance, solar power TS = 12 for all areas, while wind power TS number = 7 for all areas. + - **No** Independent draws + - **Inter-modal**: + - **Yes** For all modes, the same number should be used but may depend on the location (for instance, solar + and wind power TS = 3 for area 1, 8 for area 2, 4 for area 3, etc.) + - **No** Independent draws + + diff --git a/docs/user-guide/img/Antares_Process.jpg b/docs/user-guide/img/Antares_Process.jpg new file mode 100644 index 0000000000..8aca6a99d3 Binary files /dev/null and b/docs/user-guide/img/Antares_Process.jpg differ diff --git a/docs/user-guide/img/logic-hydro-maxP.drawio b/docs/user-guide/img/logic-hydro-maxP.drawio new file mode 100644 index 0000000000..9615612e79 --- /dev/null +++ b/docs/user-guide/img/logic-hydro-maxP.drawio @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/user-guide/img/logic-hydro-maxP.png b/docs/user-guide/img/logic-hydro-maxP.png new file mode 100644 index 0000000000..db0a134be7 Binary files /dev/null and b/docs/user-guide/img/logic-hydro-maxP.png differ diff --git a/docs/user-guide/img/logic-hydro-maxP.svg b/docs/user-guide/img/logic-hydro-maxP.svg new file mode 100644 index 0000000000..a8c5e1a544 --- /dev/null +++ b/docs/user-guide/img/logic-hydro-maxP.svg @@ -0,0 +1,4 @@ + + + +
    Before 9.1
    Before 9.1
    maxPowerDaily
    maxPowerDaily
    maxEnergyDaily
    maxEnergyDaily
    hourly pumping/generation
    hourly pumping/gener...
    weekly MaxHydroPower
    weekly MaxHydroPower
    Daily pre-allocation
    Daily pre-allocation
    After 9.1
    After 9.1
    maxPowerDaily
    maxPowerDaily
    maxEnergyDaily
    maxEnergyDaily
    hourly pumping/generation
    hourly pumping/gener...
    weekly MaxHydroPower
    weekly MaxHydroPower
    Daily pre-allocation
    Daily pre-allocation
    maxPowerHourly
    maxPowerHourly
    <= in memory
    <= in memory
    Text is not SVG - cannot display
    \ No newline at end of file diff --git a/docs/user-guide/img/migration.drawio b/docs/user-guide/img/migration.drawio new file mode 100644 index 0000000000..7ed39ca1c4 --- /dev/null +++ b/docs/user-guide/img/migration.drawio @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/user-guide/img/migration.png b/docs/user-guide/img/migration.png new file mode 100644 index 0000000000..78dfbcb65e Binary files /dev/null and b/docs/user-guide/img/migration.png differ diff --git a/docs/user-guide/img/migration.py b/docs/user-guide/img/migration.py new file mode 100644 index 0000000000..26c54cdd74 --- /dev/null +++ b/docs/user-guide/img/migration.py @@ -0,0 +1,31 @@ +import numpy as np + +NB_DAYS=365 +NB_HOURS=8760 +NB_HOURS_PER_DAY=24 + +class Legacy: + GEN_POWER=0 + GEN_ENERGY=1 + PUMP_POWER=2 + PUMP_ENERGY=3 + def __init__(self): + self.dailyAll = np.zeros((NB_DAYS, 4)) + +class New: + def __init__(self, NbScenarios=1): + self.dailyPumpEnergy = np.zeros(NB_DAYS) + self.dailyGenEnergy = np.zeros(NB_DAYS) + self.hourlyGenPower = np.zeros((NB_HOURS, NbScenarios)) + self.hourlyPumpPower = np.zeros((NB_HOURS, NbScenarios)) + +def Migration(legacy): + new = New() + new.dailyGenEnergy = legacy.dailyAll[:, Legacy.GEN_ENERGY] + new.dailyPumpEnergy = legacy.dailyAll[:, Legacy.PUMP_ENERGY] + for day in range(NB_DAYS): + for hour in range(NB_HOURS_PER_DAY): + new.hourlyGenPower[NB_HOURS_PER_DAY * day + hour] = (legacy.dailyAll[day, Legacy.GEN_ENERGY] / NB_HOURS_PER_DAY) * legacy.dailyAll[day, Legacy.GEN_POWER] + new.hourlyPumpPower[NB_HOURS_PER_DAY * day + hour] = (legacy.dailyAll[day, Legacy.PUMP_ENERGY] / NB_HOURS_PER_DAY) * legacy.dailyAll[day, Legacy.PUMP_POWER] + return new + diff --git a/docs/user-guide/img/migration.svg b/docs/user-guide/img/migration.svg new file mode 100644 index 0000000000..d312ca64de --- /dev/null +++ b/docs/user-guide/img/migration.svg @@ -0,0 +1,4 @@ + + + +
    maxpower
    input/hydro/common/capacity/maxpower_<area>.txt

    4 columns
    365 rows
    GEN POWER
    GEN ENERGY
    PUMP POWER
    PUMP ENERGY
    maxHourlyPumpPower
    input/hydro/series/<area>/maxHourlyPumpPower.txt
    N columns
    8760 rows
    Copy data as is
    Duplicate coefficients 24 times, multiply by DailyEnergy / 24
    Legend
    9.0 and before
    9.1 and after
    maxDailyGenEnergy
    input/hydro/common/capacity/maxDailyGenEnergy_<area>.txt
    1 column
    365 rows
    maxDailyPumpEnergy
    input/hydro/common/capacity/maxDailyPumpEnergy_<area>.txt
    1 column
    365 rows
    maxHourlyGenPower
    input/hydro/series/<area>/maxHourlyGenPower.txt
    N columns
    8760 rows
    \ No newline at end of file diff --git a/docs/user-guide/other-features/00-index.md b/docs/user-guide/other-features/00-index.md new file mode 100644 index 0000000000..6ed7aeb500 --- /dev/null +++ b/docs/user-guide/other-features/00-index.md @@ -0,0 +1,15 @@ +[//]: # (Index used by Sphinx to generate correct PDF tree) +# Other features + +```{toctree} +:hidden: +analyzer.md +batchrun.md +config.md +kirchhoff-constraints-builder.md +study-cleaner.md +study-finder.md +study-updater.md +vacuum.md +ybyaggregator.md +``` \ No newline at end of file diff --git a/docs/user-guide/other-features/analyzer.md b/docs/user-guide/other-features/analyzer.md new file mode 100644 index 0000000000..89f79928c7 --- /dev/null +++ b/docs/user-guide/other-features/analyzer.md @@ -0,0 +1,16 @@ +--- +hide: + - toc +--- + +# Time-Series Analyzer + + +**Executable**: antares-analyzer (currently released for Windows & Ubuntu only) + + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + + + diff --git a/docs/user-guide/other-features/batchrun.md b/docs/user-guide/other-features/batchrun.md new file mode 100644 index 0000000000..97e973501c --- /dev/null +++ b/docs/user-guide/other-features/batchrun.md @@ -0,0 +1,53 @@ +--- +hide: + - toc +--- + +# Batch Runner + + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + + +**Executable**: antares-batchrun (currently released for Windows & Ubuntu only) + +- Studies + +| command | meaning | +|:------------------|:------------------------------------------------------------------------| +| -i, --input=VALUE | The input folder, where to look for studies on which to run simulations | + +- Simulation mode + +| command | meaning | +|:------------|:------------------------------------------| +| --expansion | Force the simulation(s) in expansion mode | +| --economy | Force the simulation(s) in economy mode | +| --adequacy | Force the simulation(s) in adequacy mode | + +- Parameters + +| command | meaning | +|:-----------------|:-----------------------------------------------------| +| -n, --name=VALUE | Set the name of the new simulation outputs | +| -y, --year=VALUE | Override the number of MC years | +| -f, --force | Ignore all warnings at loading | +| --no-output | Do not write the results in the output folder | +| --year-by-year | Force the writing of the result output for each year | + +- Optimization + +| command | meaning | +|:-----------------|:------------------------------------------------| +| --no-ts-import | Do not import timeseries into the input folder. | +| --no-constraints | Ignore all binding constraints | + +- Extras + +| command | meaning | +|:-----------------------|:---------------------------------------------------------| +| --solver=VALUE | Specify the antares-solver location | +| --parallel | Enable the parallel computation of MC years | +| --force-parallel=VALUE | Override the max number of years computed simultaneously | +| --verbose | Display detailed logs for each simulation to run | \ No newline at end of file diff --git a/docs/user-guide/other-features/config.md b/docs/user-guide/other-features/config.md new file mode 100644 index 0000000000..6d06b1bea4 --- /dev/null +++ b/docs/user-guide/other-features/config.md @@ -0,0 +1,17 @@ +--- +hide: + - toc +--- + +# Config Checker + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-config (currently released for Windows & Ubuntu only) + +| command | meaning | +|:--------------|:--------------------------------| +| -p, --print | Print the current configuration | +| -v, --version | Print the version and exit | +| -h, --help | Display this help and exit | \ No newline at end of file diff --git a/docs/user-guide/other-features/kirchhoff-constraints-builder.md b/docs/user-guide/other-features/kirchhoff-constraints-builder.md new file mode 100644 index 0000000000..5aecd43e30 --- /dev/null +++ b/docs/user-guide/other-features/kirchhoff-constraints-builder.md @@ -0,0 +1,96 @@ +# Kirchhoff's constraint generator + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-kirchhoff-constraints-builder (currently released for Windows & Ubuntu only) + +## Principles + +Binding Constraints can take many forms (hourly, daily, weekly), involve flows or thermal generated power, etc. Sets of binding constraints of special interest are those which can be used to model and enforce Kirchhoff's second law on the AC flows. + +In other words, it is possible to make Antares work as a genuine DC OPF, provided that consistent binding constraints are written down for each cycle belonging to any cycle basis of the graph made out from all AC components of the power system (V vertices, E edges). + +The declaration of binding constraints can be made manually through the regular GUI. However, it is preferable not to carry out this task that way because there are many different possible formulations, among which some are better than others: + +- In a fully connected graph (V, E), there are as many binding constraints to write down as there are cycles in any cycle basis of the graph, which amounts to (E+1-V). The number of different possible basis is equal to that of spanning trees, which can be assessed by the Kirchhoff's theorem [^15] + +- Among all cycle basis, some should be preferred to others because they lead to a sparser constraint matrix. + +To get around this issue, the KCG is an autonomous Antares module (much like the time-series analyzer) which automatically instantiates a set of adequate binding constraints that will enforce Kirchhoff's law on the AC subgraph of the power system. The graph cycle basis associated with the generated constraints is optimal, in that sense that it leads to a constraint matrix as sparse as possible. +To achieve that, the KCG implements an efficient algorithm yielding a minimal cycle basis [^16] and, for all cycles of the chosen basis, generates constraints of the form: + +$$c= 1, ..., C : \sum_{l \in C}{sign(l,c)F_lZ_l} = 0$$ + +Where $Z_l$ are the impedances (parameters) and $F_l$ are the flows (variables). + +Beyond this basic purpose, the KCG is meant to provide additional modeling capacities, so as to allow the representation of two important phenomena: + +- As a rule, the power system graph represented in Antares in not fully detailed, it is usually more a "backbone" approximation, in which "vertices" are not equivalent to individual bus-bars. More likely, vertices of the graph stand for whole regions, or even countries: as a consequence, it is highly possible that when all Areas/Vertices have a zero-balance (neither import, nor export), there are real physical flows between them, so-called "loop flows". If assessments of the level of these loop flows are available (and filled out as link input data), the KCG may include them (on user's request) in the binding constraints formulation, which becomes: + +$$c= 1, ..., C : \sum_{l \in C}{sign(l,c)F_lZ_l} = \sum_{l \in C}{sign(l,c)\varphi_lZ_l}$$ + +- To mitigate the effects of actual loop flows, or more generally to allow the transmission assets to give the maximum of their potential, the power system may include components such as phase-shifting transformers, whose function can be modeled by changing the formulation of the binding constraints. Provided that estimates of the shifting capacities ($Y_l^-$, $Y_l^+$) of the installed PST are known and filled out in the link data section, the KCG will (on user's request) automatically reformulate the binding constraints as: + +$$c= 1, ..., C : Y_c^- + \sum_{l \in C}{sign(l,c)\varphi_lZ_l} \leq \sum_{l \in C}{sign(l,c)F_lZ_l} \leq Y_c^+ + \sum_{l \in C}{sign(l,c)\varphi_lZ_l}$$ + +with: + +$$Y_c^- = \sum_{l \in C}{Min(sign(l,c)Y_l^-, sign(l,c)Y_l^+)}$$ + +$$Y_c^+ = \sum_{l \in C}{Max(sign(l,c)Y_l^-, sign(l,c)Y_l^+)}$$ + +Besides, the KCG takes into account the fact that the "best estimates" of all critical data (loop flows, phase-shifting ratings, or even impedances) may vary in time: In such cases, the KCG formulates as many different binding constraints as necessary to model this operating context diversity, and relax them when appropriate (by setting the right hand sides of the equation to +/- infinite) + +From a practical standpoint, assessments of $Y^-, Y^+$ should be derived from knowledge about the actual components installed on the grid, while $Z_l$ and $ \varphi_l $ can be estimated by various methods. + +In addition to the previous functionalities, the KCG's GUI also includes the following options: + +- Choice of a specific period of time for which the constraints should be applied, while completely relaxed at other moments +- Before actual generation of binding constraints, preview of the "minimal length" spanning tree used as starting point for the optimal basis algorithm (left column of the table – links displayed with "0" do not belong to the tree) +- Before actual generation of binding constraints, preview of the "optimal cycle basis" used as starting point for constraints generation (right column of the table – links displayed with "n" appear in n different cycles of the basis) + + +[^15]: The number of spanning trees is equal to the absolute value of any cofactor of the graph incidence matrix + +[^16]: Mehlhorn K., Michail D. (2005) _Implementing Minimum Cycle Basis Algorithms_. In: Experimental and Efficient Algorithms. WEA 2005. Lecture Notes in Computer Science, vol 3503. + +## Command-line instructions + +The kirchhoff constraint generator is a standalone tool used to automatically create kirchhoff constraints. For more details about this process read: + +[7-kirchhoffs_constraint_generator.md](https://github.com/AntaresSimulatorTeam/Antares_Simulator/blob/develop/docs/reference-guide/07-kirchhoffs_constraint_generator.md) + +The binary is located in Antares_Simulator/bin/ + +--- + +### Usage + +```bash +./antares-kirchhoff-constraints-builder [study_path] [option_file_path] +``` + +### Options + +**study_path**: the path of the study, mandatory + +**option_file_path**: Optional. The path of the **constraintbuilder.ini** file. It's normally located in *study_path/settings/*. If not provided the constraint builder will take the default values, which are defined at the end of cbuilder.h. + +Those values were used to fill the GUI default values, and then the GUI created the file. That's why it's optional since only the default values are guaranteed to work. + +### Results + +New constraints generated this way will be stored in *input/bindingconstraints/* with the name uto_0001.txt, +with incrementing numbers. The file *bindingconstraints.ini* located in the same directory will be updated accordingly. +> *Note*: the outputs of the Kirchhoff's constraints generator are not printed in the general output files +> but kept within the input files structure, the reason being that they are input data for the proper Antares simulation. +> The associated data, the so-called binding constraints, bear in their name the prefix "@UTO-". + +### Study components needed + +The study only needs to include the following components to generate kirchhoff constraints: + +- Areas (contains links) +- Binding Constraints +- version number \ No newline at end of file diff --git a/docs/user-guide/other-features/study-cleaner.md b/docs/user-guide/other-features/study-cleaner.md new file mode 100644 index 0000000000..ff67c59f24 --- /dev/null +++ b/docs/user-guide/other-features/study-cleaner.md @@ -0,0 +1,25 @@ +--- +hide: + - toc +--- + +# Study Cleaner + + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-study-cleaner (currently released for Windows & Ubuntu only) + +| command | meaning | +|:------------------|:------------------------------------------| +| -i, --input=VALUE | An input folder where to look for studies | +| --dry | List the folder only and do nothing | +| --mrproper | Suppress the outputs and logs files | +| -v, --version | Print the version and exit | +| -h, --help | Display this help and exit | + + +#### Note about the "user" subdirectory +*Antares* is not allowed to delete any files from the "user" subdirectory of the study directory. +As a consequence, the "user" subdirectory is unaffected by the Study Cleaner. \ No newline at end of file diff --git a/docs/user-guide/other-features/study-finder.md b/docs/user-guide/other-features/study-finder.md new file mode 100644 index 0000000000..d681ff07a1 --- /dev/null +++ b/docs/user-guide/other-features/study-finder.md @@ -0,0 +1,19 @@ +--- +hide: + - toc +--- + +# Study Finder + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-study-finder (currently released for Windows & Ubuntu only) + +| command | meaning | +|:------------------|:---------------------------------------------------------------------------------------------------------------------| +| -i, --input=VALUE | Add an input folder where to look for studies.
    When no input folder is given, the current working dir is used. | +| -e, --extra | Print the version of the study | +| --csv | Print in a CSV format (semicolon) | +| -v, --version | Print the version and exit | +| -h, --help | Display this help and exit | \ No newline at end of file diff --git a/docs/user-guide/other-features/study-updater.md b/docs/user-guide/other-features/study-updater.md new file mode 100644 index 0000000000..70b51873c3 --- /dev/null +++ b/docs/user-guide/other-features/study-updater.md @@ -0,0 +1,22 @@ +--- +hide: + - toc +--- + +# Study Updater + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-study-updater (currently released for Windows & Ubuntu only) + + +| command | meaning | +|:------------------------------|:---------------------------------------------------------------------------| +| -i, --input=VALUE | Add an input folder where to look for studies. This argument is mandatory. | +| -c, --clean | Clean all studies found | +| --remove-generated-timeseries | Remove time-series which will be regenerated by the ts-generators | +| -d, --dry | List the study folders which may be upgraded and do nothing else | +| --force-readonly | Force read-only mode for all studies found | +| -v, --version | Print the version and exit | +| -h, --help | Display this help and exit | \ No newline at end of file diff --git a/docs/user-guide/other-features/ui-simulator.md b/docs/user-guide/other-features/ui-simulator.md new file mode 100644 index 0000000000..2987c7f095 --- /dev/null +++ b/docs/user-guide/other-features/ui-simulator.md @@ -0,0 +1,15 @@ +--- +hide: + - toc +--- + +# GUI + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-study-ui-simulator (currently released for Windows & Ubuntu only) + +#### Deprecation notice +The old *Antares* GUI has been deprecated in favor of [Antares Web](https://antares-web.readthedocs.io). +We strongly advise you to use *Antares Web*, and report to their development team any missing feature. diff --git a/docs/user-guide/other-features/vacuum.md b/docs/user-guide/other-features/vacuum.md new file mode 100644 index 0000000000..25db8dacb4 --- /dev/null +++ b/docs/user-guide/other-features/vacuum.md @@ -0,0 +1,11 @@ +--- +hide: + - toc +--- + +# Vacuum + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-vacuum (currently released for Windows & Ubuntu only) diff --git a/docs/user-guide/other-features/ybyaggregator.md b/docs/user-guide/other-features/ybyaggregator.md new file mode 100644 index 0000000000..aa885301d5 --- /dev/null +++ b/docs/user-guide/other-features/ybyaggregator.md @@ -0,0 +1,11 @@ +--- +hide: + - toc +--- + +# Year-by-Year Aggregator + +> _**WARNING:**_ this feature is deprecated and will be removed in a future release. If you are still using it, +> please [get in touch](https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues) with us. + +**Executable**: antares-ybyaggregator (currently released for Windows & Ubuntu only) diff --git a/docs/user-guide/solver/00-index.md b/docs/user-guide/solver/00-index.md new file mode 100644 index 0000000000..4ef21bd614 --- /dev/null +++ b/docs/user-guide/solver/00-index.md @@ -0,0 +1,17 @@ +[//]: # (Index used by Sphinx to generate correct PDF tree) +# Solver + +```{toctree} +:hidden: + +01-overview-solver.md +02-inputs.md +03-outputs.md +04-parameters.md +05-model.md +06-hydro-heuristics.md +07-thermal-heuristic.md +08-command-line.md +optional-features/00-index.md +09-appendix.md +``` diff --git a/docs/user-guide/solver/01-overview-solver.md b/docs/user-guide/solver/01-overview-solver.md new file mode 100644 index 0000000000..d620960a25 --- /dev/null +++ b/docs/user-guide/solver/01-overview-solver.md @@ -0,0 +1,64 @@ +# Overview + +_**This section is under construction**_ + +The *Solver* is *Antares Simulator*'s main feature. + +**Monte Carlo Simulation** Runs either an economy simulation or an adequacy simulation +depending on the values of the [parameters](04-parameters.md). +If hardware resources and simulation settings allow it, simulations can benefit from [multi-threading](optional-features/multi-threading.md). + + +## Antares at one glance + +This section gives a summary of the whole simulation process followed by Antares in Economy simulations (Adequacy being simplified variant of it): + +1. Load or Generate [stochastic generators] Time-series of every kind for all system areas + +2. For each Monte-Carlo year, pick up at random or not [scenario builder] one time-series of each kind for each area/link + +3. For each area and each reservoir: + + 1. Split up the annual overall hydro storage inflows into monthly hydro storage generation, taking into account reservoir constraints, hydro management policy and operation conditions (demand, must-run generation, etc.) [heuristic + optimizer] + + 2. For every day of each month, break down the monthly hydro energy into daily blocks, taking into account hydro management policy and operation conditions (demand, must-run generation, etc.) [heuristic + optimizer]. Aggregate daily blocks back into weekly hydro storage energy credits (used if the final optimization is run with full weekly 168-hour span) + + 3. For each week of the year (daily/weekly hydro energy credits are now known in every area), run a three-stage 168-hour optimization cycle (or seven 24-hour optimizations, if the optimization preference is set to "daily"). This aim of this cycle is to minimize the sum of all costs throughout the optimization period. This sum may include regular proportional fuel costs, start-up and no-load heat costs, unsupplied and spilled energy costs, and hurdle costs on interconnection. The solution has to respect minimum and maximum limits on the power output of each plant, minimum up and down durations, as well as interconnection capacity limits and "binding constraints" at large (which may be technical – e.g. DC flow rules – or commercial – e.g. contracts). Note that an accurate resolution of this problem requires mixed integer linear programming (because of dynamic constraints on thermal units). A simplified implementation of this approach is used when the advanced parameter "Unit commitment" is set on "accurate". This high quality option may imply long calculation times. This is why, when "Unit commitment" is set on "fast", Antares makes further simplifications that save a lot of time (starting costs are not taken into account within the optimization step but are simply added afterwards, units within a thermal cluster are subject to starting up/shutting down constraints more stringent than the minimum up/down durations). In both cases, the general optimization sequence is as follows: + + i. Minimization of the overall system cost throughout the week in a continuous relaxed linear optimization. Prior to the optimization, an 8760-hourly vector of operating reserve R3 (see next section) may be added to the load vector (this will lead in step (ii) to identify plants that would not be called if there were no reserve requirements. Their actual output will be that found in step (iii), wherein the load used in the computations takes back its original value) + + ii. So as to accommodate the schedule resulting from (i), search for integer values of the on/off variables that satisfy the dynamic constraints with the smallest possible cost increase. + + iii. Take into account the integer variables found in (ii) and solve again the optimal schedule problem for the week. + +## Operating reserves modeling + +Many definitions may be encountered regarding the different operating reserves (spinning / non-spinning, fast / delayed, primary-secondary-tertiary, frequency containment reserve – frequency restoration reserve – replacement reserve, etc.). + +Besides, all of them need not be modeled with the same level of accuracy in a simulator such as Antares. Furthermore, the best way to use the concept is not always quite the same in pure Adequacy studies and in Economy studies. + +Several classes of reserves may therefore be used in Antares; how to use them at best depend on the kind and quality of operational data at hand, and on the aim of the studies to carry out; though all kinds of reserves may always be defined in the INPUT dataset, the set of reserves that will effectively be used depends on the kind of simulations to run. Note that any or all classes of reserves may be ignored in a given simulation (without being removed from the INPUT dataset) by setting the matching "optimization preference" to "ignore reserve X": + +- **Pre-allocated reserve on dispatchable thermal plants (R0)**
    + This reserve (which corresponds to the parameter "spinning" attached to the thermal plants) is expressed as a percentage of the nominal capacity of the plants. It is simply used as a derating parameter: for instance, a 1000 MW plant with a 2.5% spinning parameter will not be able to generate more than 975 MW. It is important to notice that, if the plant is not scheduled on, it will NOT contribute to the spinning reserve (to be effectively available, the 25 MW of reserve would need the plant to be started). This first class of reserve is available for **Adequacy** as well as for **Economy**. + +- **Day-ahead reserve (R3):**
    + This reserve is available in **Adequacy** and **Economy** simulations, with the following meaning: + "For any day D, to be able to accommodate last-minute random variations of the expected demand and/or generation (as they were seen from day D -1), a certain amount of power (R3) should be ready to be available at short notice". +
    + In actual operating terms, R3 is a complex (spinning/non-spinning) mix as well as (hydro/thermal) mix. It may involve or not part of the primary and secondary power/frequency regulation reserves. R3 may represent as much as the overall amount of frequency containment reserve, frequency restoration reserve and replacement reserve required for operation on day D, as seen from day D-1. +
    + In the simulations, R3 is construed as a "virtual" increase of the load to serve, which influences the optimal unit commitment and dispatch (because of minimum stable power levels and minimum On / Down times). + +**IMPORTANT:** + +The optimization makes sure that, should the need arise, reserve R3 will actually be available where it is needed **BUT** there is no commitment regarding whether this service should be provided by an increase of local generation, a decrease of exports or even an increase of imports: the optimizer will choose the mix leading to the minimal cost for the system. + +Note that this "standard" feature of Antares makes it possible to assess the potential value of keeping some headroom in interconnections for the purpose of transferring operating reserves, when "remote" reserves are less expensive than domestic ones. + +The table below gives an overview of the different reserves available in Antares + +| | _Economy_ | _Adequacy_ | +|------|-----------|------------| +| _R0_ | _Yes_ | _Yes_ | +| _R3_ | _Yes_ | _Yes_ | \ No newline at end of file diff --git a/docs/user-guide/solver/02-inputs.md b/docs/user-guide/solver/02-inputs.md new file mode 100644 index 0000000000..287be4b797 --- /dev/null +++ b/docs/user-guide/solver/02-inputs.md @@ -0,0 +1,829 @@ +# Input files + +[//]: # (TODO: update this page, list all input files) +_**This section is under construction**_ + +- **System Maps** +- **Simulation** +- **User's Notes** +- **Load** +- **Solar** +- **Wind** +- **Renewable** +- **Hydro** +- **Thermal** +- **Misc. Gen.** +- **Reserves/DSM** +- **Links** +- **Binding constraints** +- **Economic opt.** + +## Conventions regarding names + +- Names for areas, thermal plants, etc. + Name length should not exceed 256 characters. + Characters must belong to: + { A-Z , a-z , 0-9 , - , \_ , ( , ) , & , comma , space } + +- Abbreviations : + - Fields requiring to be filled out with "YES" or "NO" can alternatively accept "Y" , "1" or "N" , "0" + - Fields requiring to be filled out with "ON" or " OFF" can alternatively accept "true", "1" or "false", "0" + - Fields requiring to be filled out with "annual" or "monthly" can alternatively accept "a" or "m" + - Fields requiring to be filled out with: "Raw" ,"Detrended"," Beta", "Normal", "Uniform", " Gamma", " Weibull" can alternatively accept: "R", "D", " B", "N", "U", "G", "W" + + +## Definition of regional districts + +Typical uses of the "district" feature are: + +1) On a large system, define an "all system" zone to get an overall synthesis on all the system nodes + +2) In a study involving different countries modeled by different regions, define "country" macro-nodes to aggregate regional results to the national level. + +3) In a study using some specific modeling such as PSP modeling with fake nodes, define a local cluster involving all the relevant real and fake nodes to simplify the edition of results. + +Hereafter is described the process to follow to bypass the GUI for the definition of districts.
    +It is based on the edition of a special "sets.ini" file. + +**IMPORTANT :** +- Make sure that the sets.ini file is ready for use before opening the Antares study. Attempts to update the sets.ini file while the study is opened will not be effective. +- Definition of meaningless districts (references to nodes that do not exist,…) will generate warnings in the GUI log files. + +**HOW TO UPDATE / CREATE the file** : using any text editor, or, better yet, [using Antares extensions](../03-getting_started.md#using-extensions). + +**WHERE TO FIND / STORE THE FILE** : INPUT/areas/sets.ini + +**PRINCIPLE:** + +The file is divided in consecutive sections, one for each district to define. + +A section contains: + +a) A header line that gives its name to the district. The header syntax is: `[district_name]` +To avoid confusion with the real area names, the results regarding this macro-area will later be found in the OUTPUT files under a name bearing the prefix "@", i.e. `@district_name` + +b) A list of parametrized building rules to be processed in their apparition order. +The different elementary rules are: ++= area\_name : add the area "area\_name" to the district
    +-= area\_name : remove the area "area\_name" from the district
    +apply-filter = add-all : add all areas to the district
    +apply-filter = remove-all : remove all areas (clear the district) + +c) A special "output" parameter that defines whether the results for the district will actually be computed or not +(this latter option allows inactivating parts of the sets.ini without altering the file). +The syntax is: `output=false` or `output= true`. + +**EXAMPLES OF SETS.INI FILES** + +a) File defining a single district named "set1" involving three areas named "area1, area3, area42": + +```ini +[set1] ++ = area1 ++ = area3
    ++ = area42 +output = true +``` + +b) File defining a district gathering all areas but five: + +```ini +[most of the system] +apply-filter = add-al +- = country +- = neighbour +- = fake antenna 1 +- = region +- = region 3 +output = true +``` +c) File defining two districts, the current simulation will ignore the second one: + +```ini +[All countries] +apply-filter= add-all +output=true + + +[All but one] +apply-filter = add-all +-= special region 12 +output=false +``` + +## Load + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/02-load/)_ + +This window is used to handle all input data regarding load. In Antares load should include transmission losses. It should preferably not include the power absorbed by pumped storage power plants. If it does, the user should neither use the "PSP" array (see window "Misc. Gen") nor the explicit modeling of PSP plants + +The user may pick any area appearing in the list and is then given access to different tabs: + +- The "time-series" tab display the "ready-made" 8760-hour time-series available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on the user's request. Different ways to update data are : + + - direct typing + + - copy/paste a selected field to/from the clipboard + + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values + (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + + - Handle the whole (unfiltered) existing dataset to either + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + Versatile "Filter" functions allow quick access to user-specified sections of data + (e.g. display only the load expected in the Wednesdays of January, at 09:00, for time-series #12 to #19). Hourly load is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (size of thermal plants, interconnection capacities, etc.) + + - _Note that:_ + + - _If the "intra-modal correlated draw" option has not been selected in the_ **simulation** _window, + MC adequacy or economy simulations can take place even if the number of time-series is not the same + in all areas (e.g. 2 , 5 , 1 , 45 ,...)_ + - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, + every area should have either one single time-series or the same given number (e.g. 25 , 25 , 1 , 25...)_ + + - The "spatial correlation" tab gives access to the inter-area correlation matrices that will be used + by the stochastic generator if it is activated. Different sub-tabs are available for the definition of 12 monthly + correlation matrices and of an overall annual correlation matrix. + A matrix A must meet three conditions to be a valid correlation matrix: + + $$\forall i,\ \forall j,\ {A_{ii} = 100; -100 \le A_{ij} \le 100}; A\ symmetric; A\ positive\ semi\mbox{-}definite$$ + + When given invalid matrices, the TS generator emits an infeasibility diagnosis + + - The "local data" tab is used to set the parameters of the stochastic generator. + These parameters are presented in four sub-tabs whose content is presented in + [Time-series analysis and generation](../ts-generator/01-overview-tsgenerator.md). + + - The "digest" tab displays for all areas a short account of the local data + +## Thermal + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/03-thermals/)_ + +This window is used to handle all input data regarding thermal dispatchable power. + +The user may pick any area appearing in the area list and is then given access to the list of thermal plants +clusters defined for the area (e.g. "CCG 300 MW", "coal 600", etc.). Once a given cluster has been selected, +a choice can be made between different tabs: + +- The "time-series" tab displays the "ready-made" 8760-hour time-series available for simulation purposes. + These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series + stochastic generator, stored as input data on the user's request. Different ways to update data are : + + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a + 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only + the generation expected on Sundays at midnight, for all time-series). + + Hourly thermal generation is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (Wind generation, interconnection capacities, load, hydro generation, solar, etc.) + + - _Note that:_ + + - _If the "intra-modal correlated draws" option has not been selected in the_ **simulation** _window, + MC adequacy or economy simulations can take place even if the number of time-series is not the same in all + areas (e.g. 2, 5, 1, 45,etc.)_ + + - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, + every area should have either one single time-series or the same given number (e.g. 25, 25, 1, 25, etc.). + Note that, unlike the other time-series (load, hydro, etc.), which depend on meteorological conditions and + are therefore inter-area-correlated, the thermal plants time-series should usually be considered as uncorrelated. + Using the "correlated draws" feature makes sense only in the event of having to play predefined scenarios + (outside regular MC scope)_ + + +- The "TS generator" tab is used to set the parameters of the stochastic generator. + These parameters are defined at the daily scale and are namely, for each day: the average duration of + forced outages (beginning on that day), the forced outage rate, the duration of planned outages (beginning on that day), + the planned outage rate, planned outages minimum and maximum numbers. + Durations are expressed in days and rates belong to [0 , 1]. + + +- The "Common" tab is used to define the cluster's techno-economic characteristics : + + - Name + - Fuel used + - Location (Area) + - Activity status + - false: not yet commissioned, moth-balled, etc. + - true : the plant may generate + - Number of units + - Nominal capacity + - Full Must-run status + - false: above a partial "must-run level" (that may exist or not, see infra) plants + will be dispatched on the basis of their market bids. + - true: plants will generate at their maximum capacity, regardless of market conditions + - Minimum stable power (MW) + - Minimum Up time (hours) + - Minimum Down time (hours) + - Default contribution to the spinning reserve (% of nominal capacity) + - tons of different pollutant types (CO2, SO2, etc.) emitted per electric MWh + - Fuel efficiency (%) + - Cost generation [Set manually / Use cost timeseries] + - Marginal operating cost (€/MWh) + - Volatility (forced): a parameter between 0 and 1, see section [Time-series generation (thermal)](../ts-generator/05-algorithm.md#time-series-generation-thermal) + - Volatility (planned): a parameter between 0 and 1, see section [Time-series generation (thermal)](../ts-generator/05-algorithm.md#time-series-generation-thermal) + - Law (forced): Probabilistic law used for the generation of the forced outage time-series, can be set to either uniform or geometric + - Law (planned): Probabilistic law used for the generation of the planned outage time-series, can be set to either uniform or geometric + - Generate TS: Parameter to specify the behavior of this cluster for TS generation. **This cluster-wise parameter takes priority over the study-wide one.** It can hold three values: + - Force generation: TS for this cluster will be generated + - Force no generation: TS for this cluster will not be generated + - Use global parameter: Will use the parameter for the study (the one in the [Simulation Window](#simulation)). + - Fixed cost (No-Load heat cost) (€ / hour of operation ) + - Start-up cost (€/start-up) + - Market bid (€/MWh) + - Random spread on the market bid (€/MWh) + - Variable Operation&Maintenance cost (€/MWh, only used if **Cost generation** is set to **use cost timeseries**) + - Seasonal marginal cost variations (gas more expensive in winter, ...) + - Seasonal market bid modulations (assets costs charging strategy ) + - Nominal capacity modulations (seasonal thermodynamic efficiencies, special over-generation allowances, etc.). These modulations are taken into account during the generation of available power time-series + - Minimal generation commitment (partial must-run level) set for the cluster + + - _Note that:_ + + - _The **optimal dispatch plan** as well as **locational marginal prices** are based on **market bids**, + while the assessment of the **operating costs** associated with this optimum are based on **cost parameters**. + (In standard "perfect" market modeling, there is no difference of approaches because market + bids are equal to marginal costs)_ + + - _Note that:_ + + - _If `Cost generation` is set to `Set manually` Marginal and Market bid costs (€/MWh) are specified directly in `Common` tab and have the same value for all time-series and hours._ + - _If `Cost generation` is set to `Use cost timeseries` Marginal and Market bid costs (€/MWh) are calculated separately for all the time-series and hours using the following equation:_ + _Marginal_Cost[€/MWh] = Market_Bid_Cost[€/MWh] = (Fuel_Cost[€/GJ] * 3.6 * 100 / Efficiency[%]) + CO2_emission_factor[tons/MWh] * C02_cost[€/tons] + Variable_O&M_cost[€/MWh]_ + _where Efficiency[%], CO2_emission_factor[tons/MWh] and Variable_O&M_cost[€/MWh] are specified in the `Common` tab under operating costs and parameters, while Fuel_Cost[€/GJ] and C02_cost[€/tons] are provided as time-series in separate tabs._ + + +## Storages + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/08-st-storages/)_ + +This window is used to create and edit short-term storage objects. An individual short-term storage component is defined as an object with the following characteristics: + +- Storage managed with a filling level which is identical at the start and end of each Antares optimization window; +- Rule curves that frame permissible storage levels hour by hour - the admissible range is a coefficient comprised between 0 and 1; +- Time-series of hourly modulation of the maximum injection and withdrawal power; +- Time-series of natural inflows (case of an open-cycle PSP). + +The user may pick any area appearing in the area list and is then given access to the list of short-term storages defined for the area. Once a given storage has been selected, the following characteristics can be set: + +- General characteristics of the storage: + - Name + - Group: the type of storage, based on a predefined list of storages ("PSP_open", "PSP_closed", "Pondage", "Battery", "Other1", "Other2", ..., "Other5") + - Withdrawal (MW): the maximum withdrawal power for the storage - withdrawal refers to the flow from the storage to the power system + - Injection (MW): the maximum injection power for the storage - withdrawal refers to the flow from the power system to the storage + - Stock (MWh): the capacity of the storage in MWh + - Efficiency (%): the energy efficiency of the storage, i.e. the ratio for a given volume between the energy taken from the system to be injected into the storage and the energy returned to the system during its withdrawal. This efficiency factor is applied when injecting energy into the storage. + - Initial level (%): the imposed initial filling rate of the storage at the beginning of each optimisation period. + - Initial level optimal: if the parameter is activated, the "Initial level" parameter is ignored and the initial storage level is optimized by Antares for each optimization period to minimize its objective function. + _Note: setting this parameter to "True" implies that there is no guarantee that the initial storage level of week N is the same as the final storage level of week N-1. However, the final level of week N is always equal to the initial level of the same week N plus/minus the injections/withdrawals occuring at the last hour of week N._ + +- "Injections/withdrawal capacities": a hourly time-series of modulation factors of the injection and withdrawal capacity for each hour (between 0 and 1), reflecting a lower availability of the structures during certain periods. At a given hour, the overall injection/withdrawal capacities of the storage are the product of this modulation factor by the "Withdrawal" and "Injection" parameters in the General data. + +- "Rule curves": a hourly time-series of rule curves (between 0 and 1), which are the lower and upper limits of the storage level imposed at each hour. + +- "Inflows": a hourly time-series of inflows filling the storage (in MWh). The values can be negative, corresponding to withdrawals imposed on the storage for other uses. + +## Hydro + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/05-hydro/)_ + +This section of the AntaresWeb interface for this section is meant to handle all input data regarding hydro power, +as well as any other kind of energy storage system of any size (from a small battery to a large +conventional hydro-storage reservoir with or without pumping facilities, etc.): Hydro power being +historically the first and largest form of power storage, it stood to reason that it should play in +Antares the role of a "generic template" for all forms of storable power. This versatility, however, +comes at the price of a comparatively more complex data organization than for other objects, +which explains the comparatively long length of this chapter. + +In the main Window, the user may pick any area appearing in the list and is then given access to different tabs: + +- The "time-series" tab displays the "ready-made" time-series already available for simulation purposes. There are five categories of time-series (displayed in five different subtabs): the Run of River (ROR) time-series, the Storage power (SP) time-series, the Minimum Generation power, the Maximum Generation power and the Maximum Pumping Power. + + ROR time-series are defined at the hourly scale; each of the 8760 values represents the ROR power expected at a given hour, expressed in round number and in MW. The SP time-series are defined at the daily scale; each of the 365 values represents an overall SP energy expected in the day, expressed in round number and in MWh. These natural inflows are considered to be storable into a reservoir for later use. The Minimum Generation time-series are defined at the hourly scale; each of the 8760 values represents the Minimum Generation power expected at a given hour expressed in round number and in MW. The Maximum Generation time-series are defined at the hourly scale; each of the 8760 values represents the Maximum Generation power expected at a given hour expressed in round number and in MW. The Maximum Pumping time-series are defined at the hourly scale; each of the 8760 values represents the Maximum Pumping power expected at a given hour expressed in round number and in MW. + + ROR time-series and SP time-series may come from any origin outside Antares, or may have been formerly generated by the Antares time-series stochastic generator and stored as input data on the user's request. Minimum Generation, Maximum Generation and Maximum Pumping may come from any origin outside Antares, but they can not be generated by the Antares time-series stochastic generator. Different ways to update data are: + + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values + (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + - _Note that:_ + + - _For a given area, the number of ROR time-series, SP times-series and Minimum Generation **must** be identical_ + - _For a given area, the number of Maximum Generation and Maximum Pumping **must** be identical_ + - _If the "intra-modal correlated draws" option was not selected in the_ **simulation** _window, + MC adequacy or economy simulations can take place even if the number of hydro time-series is not the same + in all areas (e.g. 2 , 5 , 1 , 45 ,...)_ + - _If the "intra-modal correlated draws" option was selected in the_ **simulation** _window, every + area should have either one single time-series or the same given number (e.g. 25 , 25 , 1 , 25...)_ + + +- The "spatial correlation" tab gives access to an annual inter-area correlation matrix that will be used by the stochastic generator if it is activated. Correlations are expressed in percentages, hence to be valid this matrix must be symmetric, p.s.d, with a main diagonal of 100s and all terms lying between (-100 ,+100) + + +- The "Allocation" tab gives access to an annual inter-area allocation matrix A(i,j) that may be used during a heuristic hydro pre-allocation process, regardless of whether the stochastic time-series generator is used or not. This matrix describes the weights that are given to the loads of areas (i) in the definition of the monthly and weekly hydro storage generation profiles of areas (j). The way this is done in detailed in [Heuristics](06-hydro-heuristics.md#seasonal-hydro-pre-allocation). + + +- The "local data" tab is used to set up the parameters of the stochastic generator_ **AND** _to define techno-economic characteristics of the hydro system that are used in Economy and Adequacy optimizations. For the purpose of versatility (use of the hydro section to model storage facilities quite different in size and nature), this "local tab" is itself divided up into four different subtabs whose list follows and which are further described: + + - Inflow Structure + - Reservoir Levels and water value + - Daily Power and Energy Credits + - Management options + +**Inflow Structure** + +This tab contains all the local parameters used for the stochastic generation of hydro time-series. These are namely: + +- The expectations, standard deviations, minimum and maximum values of monthly energies (expressed in MWh), monthly shares of Run of River within the overall hydro monthly inflow. +- The average correlation between the energy of a month and that of the next month (inter-monthly correlation). +- The average daily pattern of inflows within each month. Each day is given a relative "weight" in the month. If all days are given the same weight, daily energy time-series will be obtained by dividing the monthly energy in equal days. If not, the ratio between two daily energies will be equal to that of the daily weights in the pattern array. + +Overall hydro energy is broken down into two parts: Run of River- ROR and storage -STOR + +ROR energy has to be used on the spot, as it belongs to the general "must-run" energy category. + +STOR energy can be stored for use at a later time. The way how stored energy may actually be used depends +on the options chosen in the "management options" Tab and of the values of the parameters defined in the other Tabs. + +**Reservoir Levels and Water Values** + +Reservoir levels (left side) + +On the left side are defined 365 values for the minimum, average and maximum levels set for the reservoir +at the beginning of each day, expressed in percentage of the overall reservoir volume. The lower and upper level +time-series form a pair of so-called lower and upper "reservoir rule curves" + +Depending on the set of parameters chosen in the "management options" Tab, these rule curves may be used in +different ways in the course of both heuristic seasonal hydro pre-allocation process and subsequent weekly +optimal hydro-thermal unit-commitment and dispatch process. + +Water values (right side) + +On the right side is a table of marginal values for the stored energy, which depends on the date (365 days) and +of the reservoir level (101 round percentage values ranging from 0% to 100%). These values may have different origins; +they theoretically should be obtained by a comprehensive (dual) stochastic dynamic programming study carried out over +the whole dataset and dealing simultaneously with all reservoirs. + +Depending on the set options chosen in the "management options" Tab, these values may be used or not in the course of +the weekly optimal hydro-thermal unit-commitment and dispatch process. + +**Daily Power and Energy Credits** + +Standard credits (Bottom part) + +The bottom part displays two daily time-series (365 values) defined for energy generation/storage +(hydro turbines or hydro pumps). Both arrays represents the maximum daily energy (either generated or stored). + +For the sake of clarity, maximum daily energies are expressed as a number of hours at maximum power and these values +are used along with the Maximum Generation and Maximum Pumping TS's to calculate daily mean energy. + +Credit modulation (Upper part) + +The upper part displays two level-dependent (101 round percentage values ranging from 0% to 100%) time-series +of modulation coefficients defined for either generating or storing (pumping). + +These modulations, which can take any positive value, may (depending on the options chosen in the management +options Tab) be used to increase (value >1) or to decrease (value <1) the standard credits defined previously +for the maximum daily power and energies. + +**Management Options** + +This Tab is a general dashboard for the definition of how storage units, whatever their size or nature, should be managed. +It includes 15 parameters (out of which 7 are booleans) presented hereafter: + +- "Follow load" (y|n): defines whether an "ideal" seasonal generation profile should somehow follow the load OR an + "ideal" seasonal generation profile should remain as close as possible to the natural inflows + (i.e. instant generation whenever possible) + +- "Inter-daily breakdown" and "Inter-monthly breakdown" : parameters used in the assessment, through a + heuristic process, of an "ideal" seasonal generation profile, if the use of such a profile is required + (the heuristic itself is presented in [Heuristics](06-hydro-heuristics.md#seasonal-hydro-pre-allocation)) + +- "Intra-daily modulation": parameter which represents, for the storage power, the maximum authorized value for + the ratio of the daily peak to the average power generated throughout the day. This parameter is meant to allow + simulating different hydro management strategies. Extreme cases are : 1 : generated power should be constant throughout + the day 24 : use of the whole daily energy in one single hour is allowed + +- "Reservoir management" `y|n`: defines whether the storage should be explicitly modeled or not. + + Choosing "No" implies that available data allow or require that, regardless of the reservoir characteristics: + + - The whole amount of STOR energy of each month MUST be used during this month (no long-term storage) + + - The actual daily generation should follow, during the month, an "ideal" profile defined by the heuristic defined in [Heuristics](06-hydro-heuristics.md#seasonal-hydro-pre-allocation) + + Choosing "Yes" implies that available data allow or require explicit modeling of the storage facility, + regardless of whether a pre-allocation heuristic is used or not. + +- "Reservoir capacity": size of the storage facility, in MWh + +- "Initialize reservoir level on the 1st of": date at which the reservoir level should be initialized by a random draw. The "initial level" is assumed to follow a "beta" variable with expectation "average level", upper bound U=max level, lower bound L= min level, standard deviation = (1/3) (U-L) + +- "Use Heuristic Target" (y|n): defines whether an "ideal" seasonal generation profile should be heuristically determined or not. + + Choosing "No" implies that available data allow or require that full confidence should be put in water values determined upstream (through [dual] stochastic dynamic programming) OR that there are no "natural inflows" to the storage facility (battery or PSP, etc.) + + Choosing "Yes" implies that available data allow or require the definition of an "ideal" generation profile, that can be used to complement –or replace– the economic signal given by water values AND that there are "natural inflows" on which a generation heuristic can be based. + +- "Power-to-Level modulations (y|n)": defines whether the standard maximum daily energy and power credit should be or not multiplied by level-dependent modulation coefficients. + +- "Hard bounds on rule curves (y|n)": states whether, beyond the preliminary heuristic stage (if any), lower and upper reservoir rule curves should still be taken into account as constraints in the hydro-thermal unit commitment and dispatch problems. + +- "Use leeway (y|n)", lower bound L, upper bound U: states whether the heuristic hydro ideal target (**HIT**) should be followed exactly or not. + + Choosing "No" implies that, in optimization problems, the hydro energy generated throughout the time interval will be subject to an equality constraint, which may include short-term pumping cycles independent of water value: sum{ 1,t,T} (hydro(t)) – sum{1,t,T} (r. pump(t))= **HIT* + + Choosing "Yes", with bounds L and U, implies that, in optimization problems, the hydro energy generated throughout the time span will be subject to inequality constraints: L_*__HIT__ _<=sum{1,t,T} (hydro(t)) <= U\*_**HIT* + + Independently, short- or long-term pumping may also take place if deemed profitable in the light of water values. + + - "Use Water Value (y|n)": states whether the energy taken from / stored into the reservoir should be given the reference value defined in the ad hoc table OR should be given a zero value. + + - "Pumping Efficiency Ratio": setting the value to r means that, for the purpose of storing 1 gravitational MWh, pumps will have to use (1/r) electrical MWh. + +## Wind + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/06-wind/)_ + +This window is used to handle all input data regarding Wind power. +This window is only accessible when the advanced parameter Renewable Generation modeling is set to "Aggregated". + +The user may pick any area appearing in the list and is then given access to different tabs: + +- The "time-series" tab display the "ready-made" 8760-hour time-series already available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on user's request. Different ways to update data are : + + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the wind generation expected between 17:00 and 21:00 in February, for time-series 1 to 100). + + Hourly wind generation is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (size of thermal plants, interconnection capacities, load, etc.) + + - _Note that:_ + + - _If the "intra-modal correlated draws" option has not been selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series is not the same in all areas (e.g. 2, 5, 1,45, ...)_ + + - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, every area should have either one single time-series or the same given number (e.g. 25, 25, 1, 25, ...)_ + +- The "spatial correlation" tab gives access to the inter-area correlation matrices that will be used by the stochastic generator if it is activated. Different sub-tabs are available for the definition of 12 monthly correlation matrices and an overall annual correlation matrix. + + A matrix A must meet three conditions to be a valid correlation matrix: + + $$\forall i,\ \forall j,\ {A_{ii} = 100; -100 \le A_{ij} \le 100}; A\ symmetric; A\ positive\ semi\mbox{-}definite$$ + + When given invalid matrices, the TS generator emits an infeasibility diagnosis + +- The "local data" tab is used to set the parameters of the stochastic generator. These parameters are presented in four subtabs whose content is presented in [Time-series analysis and generation](../ts-generator/04-parameters.md). + +- The "digest" tab displays for all areas a short account of the local data + + +## Solar + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/07-solar/)_ + +This window is used to handle all input data regarding Solar power. Both thermal solar generation and PV solar generation are assumed to be bundled in this data section. +_This window is only accessible when the advanced parameter Renewable Generation modeling is set to "aggregatedâ€._ + +The user may pick any area appearing in the list and is then given access to different tabs: + +- The "time-series" tab display the "ready-made" 8760-hour time-series available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on the user's request. Different ways to update data are : + + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the solar power expected in August at noon, for all time-series). + + Hourly solar power is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (size of thermal plants, interconnection capacities, etc.) + + - _Note that:_ + + - _If the "intra-modal correlated draws" option was not selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series is not the same in all areas (e.g. 2 , 5 , 1 , 45 ,...)_ + + - _If the "intra-modal correlated draws" option was selected in the_ **simulation** _window, every area should have either one single time-series or the same given number (e.g. 25 , 25 , 1 , 25...)_ + +- The "spatial correlation" tab gives access to the inter-area correlation matrices that will be used by the stochastic generator if it is activated. Different sub-tabs are available for the definition of 12 monthly correlation matrices and of an overall annual correlation matrix. + + A matrix A must meet three conditions to be a valid correlation matrix: + + $$\forall i,\ \forall j,\ {A_{ii} = 100; -100 \le A_{ij} \le 100}; A\ symmetric; A\ positive\ semi\mbox{-}definite$$ + + When given invalid matrices, the TS generator emits an infeasibility diagnosis + +- The "local data" tab is used to set the parameters of the stochastic generator. These parameters are presented in four subtabs whose content is presented in [Time-series analysis and generation](../ts-generator/04-parameters.md). + +- The "digest" tab displays for all areas a short account of the local data + + +## Renewable + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/04-renewables/)_ + +This window is used to handle all input data regarding renewable generation. +_This window is only accessible when the advanced parameter Renewable Generation modeling is set to "cluster†(default value)._ + +The user may pick any area appearing in the area list and is then given access to the list of renewable clusters defined for the area (e.g. "Onshore Wind Farm 200MW", "Solar Rooftop 50MW", etc.). Once a given cluster has been selected, a choice can be made between different tabs: + +- The "time-series" tab displays the "ready-made" 8760-hour time-series available for simulation purposes. These data may come from any origin outside Antares, or be data formerly generated by the Antares time-series stochastic generator, stored as input data on the user's request. Different ways to update data are : + + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the generation expected on Sundays at midnight, for all time-series). + + Hourly thermal generation is expressed in round numbers and in MW. If a smaller unit has to be used, the user should define accordingly ALL the data of the study (Wind generation, interconnection capacities, load, hydro generation, solar, etc.) + + - _Note that:_ + + - _If the "intra-modal correlated draws" option has not been selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series is not the same in all areas (e.g. 2, 5, 1, 45,etc.)_ + + - _If the "intra-modal correlated draws" option has been selected in the_ **simulation** _window, every area should have either one single time-series or the same given number (e.g. 25, 25, 1, 25, etc.). Note that, unlike the other time-series (load, hydro, etc.), which depend on meteorological conditions and are therefore inter-area-correlated, the thermal plants time-series should usually be considered as uncorrelated. Using the "correlated draws" feature makes sense only in the event of having to play predefined scenarios (outside regular MC scope)_ + + +- The "TS generator" tab is not accessible for this version. + + +- The "Common" tab is used to define the cluster's techno-economic characteristics : + + - Name + - Group: The group can be any one of the following: Wind Onshore, Wind Offshore, Solar Thermal, Solar PV, Solar Rooftop, Other RES 1, Other RES 2, Other RES 3, or Other RES 4. If not specified, the renewable cluster will be part of the group Other RES 1. + - Location (Area) + - Timeseries mode: + - Power generation means that the unit of the timeseries is in MW + - Production factor means that the unit of the timeseries is in p.u. (between 0 and 1, 1 meaning the full installed capacity) + - Activity status + - false: not yet commissioned, moth-balled, etc. + - true: the cluster may generate + - Number of units + - Nominal capacity (in MW per unit) + + +## Misc. Gen. + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/10-misc-gen/)_ + +This window is used to handle all input data regarding miscellaneous non dispatchable generation. + +On picking any area in the primary list, the user gets direct access to all data regarding the area, which amount to **8** ready-made 8760-hour time-series (expressed in MW): + +- CHP generation + +- Bio Mass generation + +- Bio-gas generation + +- Waste generation + +- Geothermal generation + +- Any other kind of non-dispatchable generation + +- A predefined time-series for the operation of Pumped Storage Power plants, if they are not explicitly modeled. A positive value is considered as an output (generating) to the grid, a negative value is an input (pumping) to the station. + + Note that the sum of the 8760 values must be negative, since the pumping to generating efficiency is lower than 1. The user may also use only the negative values (prescribed pumping), while transferring at the same time the matching generating credit on the regular hydro storage energy credit. + +- ROW balance: the balance with the rest of the world. A negative value is an export to ROW, a positive value is an import from ROW. These values acts as boundary conditions for the model. Different ways to update data are: + + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, \*, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + +## Reserves / DSM + +_[Documentation of the AntaresWeb interface for this section](https://antares-web.readthedocs.io/en/latest/user-guide/study/areas/09-reserves/)_ + +This window is used to handle all input data regarding reserves and the potential of "smart" load management (when not modeled using "fake" thermal dispatchable plants). On picking any area in the primary list, the user gets direct access to all data regarding the area, which amount to **four** ready-made 8760-hour time-series (expressed in MW). Those reserves are available in either "adequacy" or "economy" simulations: + +- Day-ahead reserve: power accounted for in setting up the optimal unit-commitment and schedule of the following day(s), which must consider possible forecasting errors or last-minute incidents. If the optimization range is of one day, the reserve will be actually seen as "day-ahead". If the optimization range is of one week, the need for reserve will be interpreted as "week-ahead". (Adequacy and Economy simulations) + +- DSM: power (decrease or increase) to add to the load. A negative value is a load decrease, a positive value is a load increase. Note that an efficient demand side management scheme may result in a negative overall sum (All simulation modes). + +## Links + +This window is used to handle all input data regarding the interconnections. On picking any interconnection in the primary list, the user gets direct access to all data regarding the link, which are five annual parameters, a set of six ready-made 8760-hour time-series, and a flexible number of ready-made 8760-hour time-series corresponding to the capacities of the links. + +- The five parameters, used in economy or adequacy simulations are displayed in the "Parameters" and in the "Transmission capacities" tab. They are namely: + + - "Hurdle cost": set by the user to state whether (linear) transmission fees should be taken into account or not in economy and adequacy simulations + - "Transmission capacities": set by the user to state whether the capacities to consider are those indicated in 8760-hour arrays or if zero or infinite values should be used instead (actual values / set to zero / set to infinite) + - "Asset type": set by the user to state whether the link is either an AC component (subject to Kirchhoff's laws), a DC component, or another type of asset + - "Account for loop flows": set by the KCG [^9] to include (or not) passive loop flows in the formulation of the constraints enforcing Kirchhoff's laws + - "Account for PST": set by the KCG to include (or not) the settings of phase-shifting transformers in the formulation of the constraints enforcing Kirchhoff's laws + +- The "Parameters" tab displays six 8760-hour times-series, which are: + + - Hurdle cost direct: an upstream-to-downstream transmission fee, in €/MWh + + - Hurdle cost indirect: a downstream-to-upstream transmission fee, in €/MWh + + - Impedance: used in economy simulations to give a physical meaning to raw outputs, when no binding constraints have been defined to enforce Kirchhoff's laws (see "Output" section, variable "Flow Quad") OR used by the Kirchhoff's constraint generator to build up proper flow constraints (AC flow computed with the classical "DC approximation"). Since voltage levels are not explicitly defined and handled within Antares, all impedances are assumed to be scaled to some reference $ U_{ref} $ + + - Loop flow: amount of power flowing circularly though the grid when all "nodes" are perfectly balanced (no import and no export). Such loop flows may be expected on any "simplified" grid in which large regions (or even countries) are modeled by a small number of "macro" nodes, and should accordingly be accounted for. + + - PST min (denoted $Y^-$ in [Kirchhoff Constraints Generator](../other-features/kirchhoff-constraints-builder.md)): lower bound of phase-shifting that can be reached by a PST installed on the link, if any (note : the effect of the active loop flow generated by the PST may be superimposed to that of the passive loop flow) + + - PST max (denoted $Y^+$ in [Kirchhoff Constraints Generator](../other-features/kirchhoff-constraints-builder.md)): upper bound of phase-shifting that can be reached by a PST installed on the link, if any (note : the effect of the active loop flow generated by the PST may be superimposed to that of the passive loop flow) + + For the sake of simplicity and homogeneity with the convention used for impedance, PST settings are assumed to be expressed in $ rad/U^2_{ref} $ + + +- The "Transmission capacities" tab displays "ready-made" 8760-hour time-series already available for simulation purposes. + In this tab, the table "Direct" describes the upstream-to-downstream capacity, in MW, and the table "Indirect" describes the downstream-to-upstream capacity, in MW. + _Please note that Time-Series analysis and generation is not available for capacity Time-Series._ + Different ways to update data are : + - direct typing + - copy/paste a selected field to/from the clipboard + - load/save all the time-series from/to a file (usually located in the "user" subfolder) + - Apply different functions (+,-, *, /,etc.) to the existing (possibly filtered) values (e.g. simulate a 2% growth rate by choosing "multiply-all-by-1.02") + - Handle the whole (unfiltered) existing dataset to either: + + - Change the number of columns (function name: resize) + - Adjust the values associated with the current first day of the year (function name: shift rows) + + Versatile "Filter" functions allow quick access to user-specified sections of data (e.g. display only the generation expected on Sundays at midnight, for all time-series). + +- _Note that:_ + + - _For a given link, the number of Time-Series for the direct and indirect capacity must be equal. Otherwise, an issue will be raised when launching a simulation_ + + - _If the "intra-modal correlated draws" option was not selected in the_ **simulation** _window, MC adequacy or economy simulations can take place even if the number of time-series for direct/indirect capacity is not the same for all links (e.g. 2 , 5 , 1 , 45 ,...)_ + + - _If the "intra-modal correlated draws" option was selected in the_ **simulation** _window, every link should have either one single time-series for both the direct and indirect capacity, or the same given number of time-series (e.g. 25 , 25 , 1 , 25...)_ + +## Binding constraints + +This section of the AntaresWeb interface for this section is used to handle all data regarding special constraints that one may wish to include in the formulation of the optimization problems to solve. + +The set of tabs described hereafter provides for that purpose all the means required to define arbitrary linear constraints on any subset of continuous variables involved in the modeling of the power system. + +Since no limitation is set on the number and content of the constraints that may be defined that way, it is the user's sole responsibility to make sure that these so-called "binding constraints" are realistic and meaningful, be it from a technical or economic standpoint. + +A typical situation in which this feature proves useful is, for instance, encountered when data at hand regarding the grid include an estimate of the impedances of the interconnections. + +In such cases, assuming that: + +- $Z_l$ denotes the impedance of interconnections $l=1, L$ +- A preliminary study of the graph modeling the grid has shown that it can be described by a set of independent meshes $c=1, C$(cycle basis of the graph) + +Then the DC flow approximation may be implemented, for each time-step of the simulation, by a set of C binding constraints between AC flows $F_l$: + +$$ c= 1, ..., C : \sum_{i \in C}{sign(l,c)F_lZ_l = 0}$$ + +_Note that such specific binding constraints can be automatically generated within Antares by using the auxiliary module "Kirchhoff's Constraints Generator" further described in [Kirchhoff Constraints Generator](../other-features/kirchhoff-constraints-builder.md)._ + +Aside from such sets of constraints, which may help to give realistic geographic patterns to the flows, completely different sets of constraints may be also defined, such as those set up by the market organization, which may define precise perimeters for valid commercial flows [^10]. + +More generally, Antares allows to define three categories of binding constraints between transmission flows and/or power generated from generating units: + +- "hourly" binding constraints, which are applied to instant power (transmitted and/or generated) + +- "daily" binding constraints, that are applied to daily energies. This class makes more sense for commercial modeling (say: imports and exports from/to such and such area should be comprised between such and such lower bound and upper bound). Daily binding constraints are also commonly used to model specific facilities, such as pumped storage units operated on a daily cycle + +- "weekly" binding constraints, that are applied to weekly energies. Like the previous ones, these constraints may be used to model commercial contracts or various phenomena, such as the operation of a pumped storage power plant operated on a weekly cycle. + +The Binding Constraints section of the AntaresWeb interface for this section involves six main tabs described hereafter: + +- **TAB "summary"** + Creation, edition or removal of a binding constraint. A binding constraint is here defined by four macroscopic attributes that can be set by the edit command: + + - Name (caption) + - Time-range (hourly, daily, weekly) + - Numerical type (equality, bounded above, below, on both sides) + - Status (active /enabled or inactive/disabled) + +- **TAB "weights"** + Definition of the coefficients given to each flow variable or generation variable in the formulation of the constraints. Two sub-tabs make it possible to handle the coefficients associated with transmission assets (links) and those associated with generation assets (thermal clusters). In both cases: + + - The lines of the tables show only the components (links or clusters) that are visible on the current map + - The columns of the tables show only the constraints that do not have non-zero weights attached to components that are nor visible on the current map + +- **TAB "offsets"** + Definition of the time-lag (in hours) assigned to each flow variable or generation variable in the formulation of the constraints. Two sub-tabs make it possible to handle the offsets associated with transmission assets (links) and those associated with generation assets (thermal clusters). In both cases: + + - The lines of the tables show only the components (links or clusters) that are visible on the current map + - The columns of the tables show only the constraints that do not have non-zero weights attached to components that are nor visible on the current map + +- **TAB "="** + Definition of the right-hand side of equality constraints. This RHS has either 8760 values (hourly constraints) or 365 values (daily or weekly constraints). Depending on the range actually chosen for the simplex optimization (see section **Configure** of the main menu), the weekly constraints RHS will either be represented by the sum of seven daily terms or by a set of seven daily terms (weekly constraint downgraded to daily status). + +- **TAB ">"** + Definition of the right-hand side of "bounded below" and "bounded on both sides" inequality constraints. This RHS has either 8760 values (hourly constraints) or 365 values (daily or weekly constraints). Depending on the range actually chosen for the simplex optimization (see section **Configure** of the main menu), the weekly constraints RHS will either be represented by the sum of seven daily terms or by a set of seven daily terms (weekly constraint downgraded to daily status). + +- **TAB "<"** + Definition of the right-hand side of "bounded above" and "bounded on both sides" inequality constraints. This RHS has either 8760 values (hourly constraints) or 365 values (daily or weekly constraints). Depending on the range actually chosen for the simplex optimization (see section **Configure** of the main menu), the weekly constraints RHS will either be represented by the sum of seven daily terms or by a set of seven daily terms (weekly constraint downgraded to daily status). + +_NOTE: The right-hand side of a binding constraint can be set to "inf" (for "bounded above" constraints) or "-inf" (for "bounded below" constraints) for any timestamp. In that case, the constraint will be ignored by the solver for this timestamp. Please note that it is the user's responsibility to ensure that these values are set in a consistent way._ + +**WARNING:** When some clusters are defined as being in must-run ("must-run" parameter set to "True"), these clusters are automatically removed from the binding constraints in order to avoid potential incompatibilities between these constraints and the power output imposed to the must-run clusters. The clusters which are removed from binding constraints are visible in the "Summary" tab, in which they are multiplied by N/As in the binding constraints. +In case a binding constraint only contains must-run clusters, it will be ignored in the simulation and subsequently identified as "Skipped" in the summary tab. +Please note that in the specific context of the adequacy simulation mode (in which all thermal clusters are considered as being fully must-run), **all thermal clusters will consequently be de-activated from the binding constraints**. This can lead to incorrect adequacy indicators in Antares studies containing binding constraints. + + +When defining binding constraints between (hourly) power, daily or weekly (energy) flows, special attention should be paid to potential conflicts between them or with the "basic" problem constraints. Lack of caution may result in situations for which the optimization has no solution. Consider for instance a case in which three variables X1, X2, X3 (whatever they physical meaning) are involved in the following binding constraints: + +$$X1 + X2 > 5$$ + +$$X2 < -3$$ + +$$X3 > 0$$ + +$$X1 + X3 < 7$$ + +These commitments are obviously impossible to meet and, if the economic simulator is run on a dataset including such a set of constraints, it will produce an infeasibility analysis that looks like the following. +``` +[solver][notic] Solver: Starting infeasibility analysis... +[solver][error] The following constraints are suspicious (first = most suspicious) +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 124 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 128 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 137 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 140 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 133 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 139 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 136 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 130 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 142 +[solver][error] Hydro reservoir constraint at area 'Germany' at hour 123 +``` + +This report should help you identify constraints that generate infeasible linear optimization problems such what is presented above. + +The advanced preference "Unfeasible Problems Behavior" gives to the user the ability to choose between four different strategies regarding these situations. + +## Economic Opt. + +This window is used to set the value of a number of area-related parameters that, aside from the costs of each generating plant, define the optimal solution that Antares has to find in economic simulations. These parameters are namely, for each area of the system: + +- The value of the unsupplied energy (also commonly denoted Value Of Lost Load,VOLL) , in €/MWh. This value should usually be set much higher than the cost of the most expensive generating plant of the area + +- The random spread within which the nominal unsupplied energy value is assumed to vary + +- The value of the spilled energy, in € /MWh. This value reflects the specific penalty that should be added to the economic function for each wasted MWh, if any. Note that even if this value is set to zero no energy will be shed needlessly + +- The random spread within which the nominal unsupplied energy value is assumed to vary + +- Three parameters named "shedding status" and related to different kinds of generation. If the system cannot be balanced without shedding some generation, these parameters give control on how each kind of generation ("Non dispatchable power","Dispatchable hydropower" and "Other dispatchable generating plants") should contribute to the shedding. Depending on the value chosen for the status, the generation can or cannot be shed to find a solution to the load/generation balance problem. Note that enforcing a negative status for all types of plants may lead to simulations scenarios for which there are no mathematical solutions. + +On running the economic simulator, such situations produce an infeasibility diagnosis. + +[^9]: KCG : Kirchhoff's constraints generator (see section 7) + +[^10]: A typical case is given by the "Flow-Based" framework today implemented in a large portion of the European electricity market. + +## System Maps + +This window is used to define the general structure of the system, i.e. the list of areas and that of the interconnections. +Only the area's names, location and the topology of the grid are defined at this stage. Different colors may be assigned +to different areas. These colors may later be used as sorting options in most windows. They are useful to edit data in a +fashion that has a geographic meaning (which the lexicographic order may not have). This window displays copy/paste/select +all icons equivalent to the relevant EDIT menu commands. + +The top left side of the window shows a "mouse status" field with three icons. These icons (one for nodes, one for links +and one for binding constraints) indicate whether a selection made on the map with the mouse will involve or not the +related elements. When a copy/paste action is considered, this allows for instance to copy any combination of nodes, +links and binding constraints. Status can be changed by toggling the icons. Default is "on" for the three icons. Two +other purely graphic icons/buttons (no action on data) allow respectively to center the map on a given set of (x , y) +coordinates, and to prune the "empty" space around the current map. Multiple additional maps may be defined by using +the cross-shaped button located top right. A detailed presentation of all system map editor features can be found in +the document "System Map Editor User guide". diff --git a/docs/user-guide/solver/03-outputs.md b/docs/user-guide/solver/03-outputs.md new file mode 100644 index 0000000000..cd79b2fdb4 --- /dev/null +++ b/docs/user-guide/solver/03-outputs.md @@ -0,0 +1,256 @@ +# Output files + +[//]: # (TODO: update this page, list all output files) +_**This section is under construction**_ + +The general file organization is the same for Economy and Adequacy simulations. +**\\** + +**Economy:** + +| OUTPUT/Simu id/economy/mc-all/ | | | | +|--------------------------------|----------------------|-----------------|------------------------------------------| +| | /grid/... | | contains a summary file "digest.txt" | +| | /areas/name/... | | contains area-related results | +| | /links / name/... | | contains interconnection-related results | +| | /mc-ind /year_number | | | +| | | /areas/name/... | contains area-related results | +| | | /links/name/... | contains interconnection-related results | + +_("mc-all" files contain synthetic results over all years, "year-number" files contain results for a single year)_ +_The variables present in each file are detailed in the following sections._ +_In "Economy" simulations, all variables have a techno-economic meaning._ + +**Adequacy:** + +| OUTPUT/Simu id/adequacy/mc-all/ | | | | +|---------------------------------|----------------------|-----------------|------------------------------------------| +| | /grid/... | | contains a summary file "digest.txt" | +| | /areas/name/... | | contains area-related results | +| | /links / name/... | | contains interconnection-related results | +| | /mc-ind /year_number | | | +| | | /areas/name/... | contains area-related results | +| | | /links/name/... | contains interconnection-related results | + +_("mc-all" files contain synthetic results over all years, "year-number" files contain results for a single year)_ +_The variables present in each file bear exactly the same name as in Economy simulations but do not have the same values._ +_The only variables that have a techno-economic meaning are the "Adequacy" indicators (unsupplied energy,LOLD,LOLP)_ + +**IMPORTANT** Adequacy and Economy files look the same but their content are specific + +In "Economy" and "Adequacy" simulations, the optimization ignores the "primary" and "strategic" reserves (however, it may include the [other] spinning and day-ahead reserves, depending on the settings made in "optimization preferences"). + +In "Adequacy" simulations, all dispatchable thermal units are given the "must-run" status (hence, they will generate at Pmax, regardless of the demand). As a consequence the only variables that are actually meaningful are the adequacy indicators (unsupplied energy, LOLD,LOLP), that may depend on assumptions made regarding the economic values of Unsupplied and spilled energies, and on hurdle costs on interconnections. +In the specific case where binding constraints are present in the study, **all thermal clusters will consequently be de-activated from the binding constraints**. This can lead to incorrect adequacy indicators in Antares studies containing binding constraints in "Adequacy" simulations. + +As a consequence, both "Adequacy" and "Economy" simulations yield the same values for the adequacy indicators under the following conditions: if hurdle costs on interconnections are higher than the difference between the maximum VOLL and the minimum VOLL assigned to the different areas of the system, and if no binding constraint is altered due to the fact that they contain clusters in must-run. + +The files and their content are hereafter described. + +## Economy and Adequacy, area results [^11] + +**25** files resulting from the combination of the following attributes: +**[values | id | details | details-res | details-STstorage] X [hourly | daily | weekly | monthly | annual]** + +- The second attribute defines the time span over which the results are assessed: hourly detail, daily bundle, weekly bundle, monthly bundle, annual bundle. + +- The first attribute defines the nature of the results presented in the file : + +**Values** Values of different variables (price, load, overall generation issued from coal, etc.), the list of which is common to all areas of the interconnected system. Files of type "values" have therefore the same size for all areas. +These results appear under the label "general values" in the output GUI. + +**details** Values regarding the different dispatchable thermal generating plants of each area (e.g. "older 300 MW coal from the south coast"). The sizes of these files differ from one area to another. +These results appear under the label "thermal plants" in the output GUI. + +**details-res** Values regarding the different renewable clusters of each area. The sizes of these files differ from one area to another. +These results appear under the label "Ren. clusters" in the output GUI. + +**details-STstorage** Values regarding the different short-term storages of each area. The sizes of these files differ from one area to another. +These results appear under the label "ST storages" in the output GUI. + +**id** Identifier (number) of the Monte-Carlo years for which were observed the extreme values of the different variables presented in the « values » files +These results appear under the label "record years" in the output GUI + +The area files that belong to the "values" class display fields corresponding to the expectation, standard deviation, minimal and maximal values of the variables whose list is given hereafter. + +| variables | description | +|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| OV.COST | Overall cost = operating cost + unsupplied cost+ spilled cost+ hydro cost | +| OP.COST | Operating cost = Proportional costs + Non- proportional costs | +| MRG. PRICE | LMP : overall economic effect of a local 1MW load increase | +| CO2, NH3, SO2, ... EMIS. | Amount emitted by all dispatchable thermal plants for the following types of pollutants: CO2, SO2, NH3, NOX, PM2\_5, PM5, PM10, NMVOC, OP1, OP2, OP3, OP4, OP5 EMIS. | +| BALANCE | Overall Import/export balance of the area (positive value : export) | +| ROW BAL | Import/export with areas outside the modeled system (positive value: import) [^12] | +| PSP | User-defined settings for pumping and subsequent generating | +| MISC. NDG | Miscellaneous non dispatchable generation | +| LOAD | Demand (including DSM potential if relevant) | +| H.ROR | Hydro generation, Run-of-river share | +| WIND | Wind generation (only when using aggregated _Renewable generation modeling_) | +| SOLAR | Solar generation (thermal and PV) (only when using aggregated _Renewable generation modeling_) | +| NUCLEAR | Overall generation of nuclear clusters | +| LIGNITE | Overall generation of dispatchable thermal clusters burning brown coal | +| COAL | Overall generation of dispatchable thermal clusters burning hard coal | +| GAS | Overall generation of dispatchable thermal clusters burning gas | +| OIL | Overall generation of dispatchable thermal clusters using petroleum products | +| MIX.FUEL | Overall gen. of disp. thermal clusters using a mix of the previous fuels | +| MISC.DTG | Overall gen. of disp. thermal clusters using other fuels | +| MISC.DTG 2 | Overall gen. of disp. thermal clusters using other fuels | +| MISC.DTG 3 | Overall gen. of disp. thermal clusters using other fuels | +| MISC.DTG 4 | Overall gen. of disp. thermal clusters using other fuels | +| WIND OFFSHORE | Wind Offshore generation (only when using clustered _Renewable generation modeling_) | +| WIND ONSHORE | Wind Onshore generation (only when using clustered _Renewable generation modeling_) | +| SOLAR CONCRT. | Concentrated Solar Thermal generation (only when using clustered _Renewable generation modeling_) | +| SOLAR PV | Solar Photovoltaic generation (only when using clustered _Renewable generation modeling_) | +| SOLAR ROOFT | Rooftop Solar generation (only when using clustered _Renewable generation modeling_) | +| RENW. 1 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | +| RENW. 2 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | +| RENW. 3 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | +| RENW. 4 | Overall generation of other Renewable clusters (only when using clustered _Renewable generation modeling_) | +| H.STOR | Power generated from energy storage units (typically: Hydro reservoir) | +| H.PUMP | Power absorbed by energy storage units (typically: PSP pumps consumption) | +| H.LEV | Energy level remaining in storage units (percentage of reservoir size) | +| H.INFL | External input to the energy storage units (typically: natural inflows) | +| H.OVFL | Wasted natural inflow overflowing from an already full energy storage unit | +| H.VAL | Marginal value of stored energy (typically: shadow water value) | +| H.COST | Expenses /Income brought by energy storage actions (H.STOR,H.PUMP) | +| UNSP. ENRG | Unsupplied energy: adequacy indicator (Expected Energy Not Served–EENS) | +| SPIL. ENRG | Spilled energy (energy produced that cannot be used and has to be wasted) | +| LOLD | Loss of load duration: adequacy indicator (length of shortfalls) | +| LOLP | Loss of Load probability: adequacy indicator (probability of at least one hour of shortfall within the considered period, without normalization by the duration of the considered period) | +| AVL. DTG | Available dispatchable thermal generation (sum of av. power over all plants) | +| DTG. MRG | Disp. Ther. Gen. (AVL DTG – sum of all dispatched thermal generation) | +| MAX. MRG | Maximum margin: operational margin obtained if the hydro storage energy of the week were used to maximise margins instead of minimizing costs | +| DENS | Domestic Energy Not Supplied: the difference between the local production capabilities of an area and its local load[^adqp] | +| LMR. VIOL | Local Matching Rule Violation after the Antares Simulation as defined by the adequacy patch[^adqp] | +| SPIL. ENRG. CSR | Spilled Energy after the Curtailment Sharing Rule step of the dequacy patch[^adqp] | +| _injection | Injection of energy from the area into each short-term storage group | +| _withdrawal | Withdrawal of energy from each short-term storage group into the area | +| _level | Average level of each short-term storage group | +| NP COST | Non-proportional costs of the dispatchable plants (start-up and fixed costs) | +| NODU | Number of Dispatched Units [^13] | +| Profit | Net profit of the cluster in euros ((MRG. PRICE - marginal cost of the cluster) * (dispatchable production of the cluster)[^15] | +| ,P-injection | Injection of energy from the area into the short-term storage | +| ,P-withdrawal | Withdrawal of energy the short-term storage into the area | +| ,Levels | Level of the short-term storage | + +_Note: The net profit is computed on full precision values for MRG. PRICE. The user may obtain slightly different results applying the given formula because MRG. PRICE values are rounded to 10^-2._ + +## Economy and Adequacy, interconnection results [^14] +**10** files resulting from the combination of the following attributes: +**[values | id] X [hourly | daily | weekly | monthly | annual]** + +- The second attribute defines the period of time over which the results are assessed: hourly detail, daily bundle, weekly bundle, monthly bundle, annual bundle. +- The first attribute defines the nature of the results presented in the file. + + +**values** values of different variables (flow, congestion rent) the list of which is common to all interconnections. The files of type "values" have therefore the same size everywhere +These results appear under the label "general values" in the output GUI. + +**id** identifier (number) of the Monte-Carlo years for which were observed the extreme values of the different variables presented in the « values » files. +These results appear under the label "record years" in the output GUI. + + +The area files that belong to the « values » class display **28** fields corresponding to the expectation, standard deviation, minimal and maximal values of the variables whose list is given hereafter. + +| variables | description | +|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| FLOW LIN. | Flow (signed + from upstream to downstream) assessed by the linear optimization. These flows follow Kirchhoff's law only if these laws have been explicitly enforced by the means of suitable binding constraints | +| UCAP | Used capacity: absolute value of FLOW LIN. This indicator may be of interest to differentiate the behavior of interconnectors showing low average flows: in some cases this may indicate that the line is little used, while in others this may be the outcome of high symmetric flows | +| LOOP FLOW | Flow circulating through the grid when all areas have a zero import/export balance. This flow, to be put down to the simplification of the real grid, is not subject to hurdle costs in the course of the optimization | +| FLOW QUAD. | Flow computed anew, starting from the linear optimum, by minimizing a quadratic function equivalent to an amount of Joule losses, while staying within the transmission capacity limits. This calculation uses for this purpose the impedances found in the "Links" Input data. If congestions occur on the grid, these results are not equivalent to those of a DC load flow | +| CONG. FEE ALG | Algebraic congestion rent = linear flow \* (downstream price – upstream price) | +| CONG. FEE ABS | Absolute congestion rent = linear flow\* abs(downstream price–upstream price) | +| MARG. COST | Decrease of the system's overall cost that would be brought by the optimal use of an additional 1 MW transmission capacity (in both directions) | +| CONG PROB + | Up>Dwn Congestion probability = (NC+) / (total number of MC years) with:
    NC+ = number of years during which the interconnection was congested in the Up>Dwn way for **any** length of time within the time frame relevant with the file | +| CONG PROB - | Dwn>Up Congestion probability = (NC-) / (total number of MC years) with:
    NC- = number of years during which the interconnection was congested in the Dwn>Up way for **any** length of time within the time frame relevant with the file | +| HURD. COST | Contribution of the flows to the overall economic function through the "hurdles costs" component. For each hour:
    `if (FLOW.LIN –LOOP FLOW) > 0 `
    `HURD. COST = (hourly direct hurdle cost) * (FLOW LIN.)`
    `else HURD.COST = (hourly indirect hurdle cost) * (-1) * (FLOW LIN.)` | + +## Economy and Adequacy, other results + +Depending on the options chosen in the main simulation window, the output folders may also include either, both or none of the following sections: + +| OUTPUT/Simu id/ts-numbers/ | | | +|----------------------------|-------------------|------------------| +| | /Load | /area names/... | +| | /Thermal | /area names/... | +| | /Hydro | /area names/... | +| | /Wind[^agg] | /area names/... | +| | /Solar[^agg] | /area names/... | +| | /Renewables[^ren] | /area names/... | +| | /NTC | /area names/... | + +These files contain, for each kind of time-series, the number drawn (randomly or not) in each Monte-Carlo year (files are present if "output profile / MC scenarios" was set to "true"). + +| OUTPUT/Simu id/ts-generator/ | | | +|------------------------------|--------------|------------------------------| +| | /Load | /batch number/area names/... | +| | /Hydro | /batch number/area names/... | +| | /Wind[^agg] | /batch number/area names/... | +| | /Solar[^agg] | /batch number/area names/... | + + +These files contain, for each kind of Antares-generated time-series, copies of the whole set of time-series generated. Batch numbers depend on the values set for the "refresh span" parameters of the stochastic generators (files are present if "store in output" was set to "true"). + +## Miscellaneous + +Alike Input data, output results can be filtered so as to include only items that are associated with Areas and Links defined as "visible" in the current map. In addition, the output filtering dialog box makes it possible to filter according to two special categories (**Districts** and **Unknown**) that are not related to standard maps: + +- **Districts** displays only results obtained for spatial aggregates +- **Unknown** displays only results attached to Areas or Links that no longer exist in the Input dataset (i.e. study has changed since the last simulation) + +[^11]: This description applies to both « MC synthesis » files and "Year-by-Year" files, with some simplifications in the latter case + +[^12]: Value identical to that defined under the same name in the "Misc Gen" input section. + +[^13]: NODU and NP Cost do not appear in "Adequacy" results since these variables are irrelevant in that context + +[^adqp]: Please note that this output variable is only available in the economy mode, when the adequacy patch is activated (see [Adequacy Patch](optional-features/adequacy-patch.md)) + +[^14]: This description applies to both « MC synthesis » files and "Year-by-Year" files, with some simplifications in the latter case + +[^agg]: This output is only available if the parameter "renewable generation modelling" is set to "cluster" in the input of the simulation + +[^ren]: This output is only available if the parameter "renewable generation modelling" is set to "aggregated" in the input of the simulation + +[^15]: dispatchable production = power generation above min gen = (power generation) - (min gen modulation)*units*capacity + +### The Annual System Cost Output file + +In addition to the general files introduced in [Output Files](03-outputs.md), the Output folder of each economic or adequacy simulation includes, at its root, a file "Annual\_System\_Cost.txt" It presents the metrics of a global Monte-Carlo variable further denoted ASC. + +The value of ASC for any given simulated year is defined as the sum, over all areas and links, of the annual values of the area-variable "OV.COST" and of the link-variable "HURD. COST". + +The metrics displayed in the "Annual system cost" file take the form of four values: + +- Expectation EASC + +- Standard deviation SASC + +- Minimum LASC + +- Maximum UASC + +As with all other random variables displayed in the Antares Output section, the computed standard deviation of the variable can be used to give a measure of the confidence interval attached to the estimate of the expectation. For a number of Monte-Carlo years N, the law of large numbers states for instance that there is a 95 % probability for the actual expectation of ASC to lie within the interval: + +
    **EASC +/- 1.96 (SASC / sqrt(N))**
    + +There is also a 99.8 % probability that it lies within the interval: + +
    **EASC +/- 3 (SASC / sqrt(N))**
    + +### Changelog +Here is a list of new output variables in recent versions: + +| Version | Variable(s) introduced | Files | Enabled by default | +|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------|--------------------| +| 8.0 | none | | | +| 8.1 | WIND OFFSHORE, WIND ONSHORE, SOLAR CONCRT., SOLAR PV, SOLAR ROOFT, RENW. 1, RENW. 2, RENW. 3, RENW. 4 | values-*.txt | yes | +| 8.1 | MISC. DTG 2, MISC. DTG 3, MISC. DTG 4 | values-*.txt | yes | +| 8.2 | none | | | +| 8.3 | DENS | values-*.txt | no | +| 8.3 | Profit by plant | details-*.txt | yes | +| 8.4 | BC. MARG. COST | binding-constraints-*.txt | no | +| 8.5 | LMR VIOL., SPIL. ENRG. CSR, DTG MRG CSR | values-*.txt | no | +| 8.6 | PSP_open_injection, PSP_open_withdrawal, PSP_open_level, PSP_closed_injection, PSP_closed_withdrawal, PSP_closed_level, Pondage_injection, Pondage_withdrawal, Pondage_level, Battery_injection, Battery_withdrawal, Battery_level, Other1_injection, Other1_withdrawal, Other1_level, Other2_injection, Other2_withdrawal, Other2_level, Other3_injection, Other3_withdrawal, Other3_level, Other4_injection, Other4_withdrawal, Other4_level, Other5_injection, Other5_withdrawal, Other5_level | values-*.txt | yes | +| 8.6 | STS inj by plant, STS withdrawal by plant, STS lvl by plant | details-STstorage-*.txt | yes | +| 8.6 | CO2 EMIS., NH3 EMIS., SO2 EMIS., NOX EMIS., PM2_5 EMIS., PM5 EMIS., PM10 EMIS., NMVOC EMIS., OP1 EMIS., OP2 EMIS., OP3 EMIS., OP4 EMIS., OP5 EMIS. | values-*.txt | yes | diff --git a/docs/user-guide/solver/04-parameters.md b/docs/user-guide/solver/04-parameters.md new file mode 100644 index 0000000000..fc8492a9e4 --- /dev/null +++ b/docs/user-guide/solver/04-parameters.md @@ -0,0 +1,845 @@ +# Parameters + +[//]: # (TODO: complete this page) +_**This section is under construction**_ + +An *Antares* study contains a global parameter file named `generaldata.ini`. + +--- +## General parameters +These parameters are listed under the `[general]` section in the `.ini` file. + +--- +### Study mode + + +#### mode +[//]: # (TODO: verify if required, remove default value) +[//]: # (TODO: add details 'expansion' behavior) +- **Expected value:** one of the following (case-insensitive): + - `economy` or `economic` + - `adequacy` + - `expansion` +- **Required:** **yes** +- **Default value:** `economy` +- **Usage:** this parameter sets the study mode for Antares + - `economy/economic`: Antares simulator will try to ensure balance between load and generation, while minimizing the + economical cost of the grid's operation (more on this [here](../01-overview.md#transmission-project-profitability)). "Economy" simulations make a full use of + *Antares* optimization capabilities. They require economic as well as technical input data and may demand a lot + of computer resources. + - `adequacy`: in this mode, all power plants' operational cost is considered zero. Antares' only objective is to ensure + balance between load and generation (more on this [here](../01-overview.md#generation-adequacy-problems)). "Adequacy" simulations are faster and require only + technical input data. Their results are limited to adequacy indicators. + - `expansion`: Antares simulator will optimize the investments on the grid, minimizing both investments and + operational costs. + +--- +### Study horizon + + +#### horizon +[//]: # (TODO: verify if required, remove default value) +- **Expected value:** year (string) +- **Required:** **yes** +- **Default value:** empty string +- **Usage:** the horizon of the study (static tag, not used in the calculations) + +--- + +### Calendar parameters + + +#### nbyears +[//]: # (TODO: verify if required, verify default value) +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Default value:** +- **Usage:** number of Monte-Carlo (MC) years that should be prepared for the simulation (not always the same as the + MC years actually simulated, which are defined by [user-playlist](#user-playlist) and [playlist parameters](#playlist-parameters)). + +--- +#### simulation.start +[//]: # (TODO: verify if required, verify default value) +[//]: # (TODO: verify if index 8 should be replaced by 7 in example -starts at 1 or at 0 ?-) +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Default value:** 0 +- **Usage:** index of first day to include in study (>= 0) (e.g. 8 for a simulation beginning on the + second week of the first month of the year) + +--- +#### simulation.end +[//]: # (TODO: verify if required, verify default value) +[//]: # (TODO: verify if index starts at 1 or at 0 for example) +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Default value:** 365 +- **Usage:** index of last day to include in study (<= 365) (e.g. 28 for a simulation ending on the fourth week + of the first month of the year) + +> _**Note:**_ +> In Economy an Adequacy [simulation modes](#mode), simulation start & end must be chosen to make the simulation span a +> round number of weeks. If not, the simulation span will be truncated: for instance, (1, 365) will be interpreted as +> (1, 364), i.e. 52 weeks (the last day of the last month will not be simulated). + +--- +#### january.1st +[//]: # (TODO: verify default value) +- **Expected value:** string carrying an integer between 0 and 6, or one of (case-insensitive): `monday`/`lundi`, + `tuesday`/`mardi`, `wednesday`/`mercredi`, `thursday`/`jeudi`, `friday`/`vendredi`, `saturday`/`samedi`, + `sunday`/`dimanche`. +- **Required:** no +- **Default value:** `monday` +- **Usage:** this parameter should indicate the day-of-week of january 1st of the given [year](#horizon). + +--- +#### first-month-in-year +[//]: # (TODO: verify if required, remove default value) +- **Expected value:** one of the following string (case-insensitive): `jan`/`january`, `feb`/`february`, `mar`/`march`, + `apr`/`april`, `may`, `jun`/`june`, `jul`/`july`, `aug`/`august`, `sep`/`september`, `oct`/`october`, + `nov`/`november`, `dec`/`december`. +- **Required:** **yes** +- **Default value:** +- **Usage:** this is the first month in the input time-series, of the studied [year](#horizon). + +--- +#### first.weekday +- **Expected value:** string carrying an integer between 0 and 6, or one of (case-insensitive): `monday`/`lundi`, + `tuesday`/`mardi`, `wednesday`/`mercredi`, `thursday`/`jeudi`, `friday`/`vendredi`, `saturday`/`samedi`, + `sunday`/`dimanche`. +- **Required:** no +- **Default value:** `monday` +- **Usage:** in economy or adequacy simulations, indicates the frame (Mon-Sun, Sat-Fri, etc.) to use for the edition + of weekly results. + +--- +#### leapyear +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** indicates if the studied [year](#horizon) is a leap-year. + +--- +### Additional parameters + + +#### year-by-year +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** + - `false`: no individual results will be printed out + - `true`: for each simulated year, detailed results will be printed out in an individual directory: + `Study_name/OUTPUT/simu_tag/Economy/mc-i-number + +--- +#### derated +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** if set to `true`, all time-series will be replaced by their general average and the number of MC years + set to 1. If the TS are ready-made or Antares-generated but are not to be stored in the INPUT folder, + no time-series will be written over the original ones (if any). If the time-series are built by Antares + and if it is specified that they should be stored in the INPUT, a single average-out time series will be stored + instead of the whole set. + +> _**WARNING:**_ this parameter cannot be used with parameter [custom-scenario](#custom-scenario) + +--- +#### custom-scenario +[//]: # (TODO: add specific link to "scenario builder") +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** + - `false`: for all years to simulate, all time-series will be drawn at random + - `true`: the simulation will be carried out on a mix of deterministic and probabilistic conditions, + with some time-series randomly drawn and others set to user-defined values. This option allows setting + up detailed "what if" simulations that may help to understand the phenomena at work and quantify various kinds + of risk indicators. To set up the simulation profile, use the [scenario builder](02-inputs.md). + +> _**WARNING:**_ this parameter cannot be used with parameter [derated](#derated) +> _**WARNING:**_ if set to `true`, parameter [active-rules-scenario](#active-rules-scenario) must be set + +--- +#### user-playlist +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** + - `false`: all prepared Monte-Carlo (MC) years will actually be simulated. + - `true`: the years to simulate are defined in a list. To set up this list, use the [playlist parameters](#playlist-parameters). + This feature allows, for instance, to refine a previous simulation by excluding a small number of "raw" MC years + whose detailed analysis may have shown that they were not physically realistic. A different typical use case consists + in replaying only a small number of years of specific interest (for instance, years in the course of which Min or Max + values of a given variable were encountered in a previous simulation). + In addition, each MC year i=1, …, N can be given a relative [weight](#playlistyearweight) + +> _**WARNING:**_ this parameter cannot be used with parameter [derated](#derated) + +--- +#### thematic-trimming +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** set to `true` in order to select a specific subset of the optimization variables to print in the [output files](03-outputs.md), + using a thematic filter. Use the [variables selection parameters](#variables-selection-parameters) to define the filter. + Thematic Trimming does not reduce computation time, but can bring some benefits on total runtime (smaller files to + write). It can save a lot of disk space in simulations where only a few variables are of interest. + +--- +#### geographic-trimming +[//]: # (TODO: verify usage) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** + Allows to select the results to store at the end of a simulation: choice of areas, interconnections, temporal + aggregations (hourly, daily, etc.). + Geographic Trimming does not reduce computation time, but can bring some benefits on total runtime (fewer files to + write). It can save a lot of disk space in simulations where only a few Areas and Links are of interest. + - **None** Storage of results for all areas, geographic districts, interconnections as well as all time spans + (hourly, daily, etc.) + - **Custom** Storage of the results selected with the "Geographic Trimming" command of the "Configure" + option available in the main menu. + Filters on areas, interconnections and time spans may also be defined as follows: + - On the map, select area(s) and/or interconnection(s) + - Open the inspector module (Main menu, Windows) + - Set adequate parameters in the "output print status" group + +--- +#### active-rules-scenario +[//]: # (TODO: add usage details) +- **Expected value:** undefined, or `default ruleset` (case-insensitive) +- **Required:** no, unless [custom-scenario](#custom-scenario) is set to `true` +- **Default value:** undefined +- **Usage:** defines how scenarios are built. Only one supported value for now: + - `default ruleset` + +--- +### Pre-processor parameters + + +#### readonly +[//]: # (TODO: add usage details) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** sets the study to read-only mode + +--- +## Output parameters +These parameters are listed under the `[output]` section in the `.ini` file. + +--- +#### synthesis +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** + - `true`: synthetic results will be stored in a directory: `Study_name/OUTPUT/simu_tag/Economy/mc-all` + - `false`: no general synthesis will be printed out + +--- +#### storenewset +[//]: # (TODO: verify usage) +[//]: # (TODO: link to specific output folder when it is documented in Outputs doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** + - `false`: no storage of the time-series numbers (either randomly drawn or user-defined) used to set up the simulation. + - `true`: a [specific output folder](03-outputs.md) will be created to store all the time-series numbers drawn + when preparing the Monte-Carlo years. + +--- +#### hydro-debug +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### result-format +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### archives +[//]: # (TODO: fill default value) +- **Expected value:** comma-seperated list of 0 to N elements among the following (case-insensitive): + `load`, `wind`, `hydro`, `thermal`, `solar`, `renewables`, `ntc`, `max-power` +- **Required:** no +- **Default value:** +- **Usage:** if [storenewset](#storenewset) is set to `true`, this parameter selects those of them that should be + written in the [output files](03-outputs.md). + +--- +## Optimization parameters +[//]: # (TODO: add link to "local parameter values" documentation) +Options related to the optimization core used in the simulations. +This set of parameters is study-specific; it can be changed at any time and saved along with study data. +The values set in this file take precedence over the local parameter values. For instance, if the LOCAL +parameter "set to infinite" is activated for some interconnections, and if the GLOBAL preference regarding transmission +capacities is "set to null", the simulation will be carried out as if there were no longer any grid BUT the local +values will remain untouched. If the preference is afterward set to "local values", the interconnections will be +given back their regular capacities (infinite for those being set on "set to infinite"). +These parameters are listed under the `[optimization]` section in the `.ini` file. + +--- +#### simplex-range +- **Expected value:** `day` or `week` +- **Required:** no +- **Default value:** `week` +- **Usage:** the simplex optimization range. + In the formulation of the optimal hydro-thermal unit-commitment and dispatch problem (see dedicated document), + the reference hydro energy $HIT$ used to set the right hand sides of hydro- constraints depends on the value + chosen for this parameter, and is defined as follows: + - `day`: for each day **d** of week $\omega$ : $HIT = W_d^2$ + - `week`: for week $\omega$: $HIT = \sum_{d\in \omega}{W_d^2}$ + Weekly optimization performs a more refined unit commitment, especially when [unit-commitment-mode](#unit-commitment-mode) + is set to `accurate`. + +> More information here: [The heuristic for seasonal hydro pre-allocation](06-hydro-heuristics.md#seasonal-hydro-pre-allocation) + +--- +#### transmission-capacities +- **Expected value:** one of the following (case-insensitive): + - `local-values` + - `null-for-all-links` + - `infinite-for-all-links` + - `infinite-for-physical-links` + - `null-for-physical-links` +- **Required:** no +- **Default value:** `local-values` +- **Usage:** allows the user to override the transmission capacities on links. + - `local-values`: use the local property for all links, including physical links (no override) + - `null-for-all-links`: override all transmission capacities with 0 + - `infinite-for-all-links`: override all transmission capacities with $\inf$ + - `infinite-for-physical-links`: override transmission capacities with $\inf$ on **physical links only** + - `null-for-physical-links`: override transmission capacities with 0 on **physical links only** + +--- +#### link-type +[//]: # (TODO: document this parameter, seems to belong to another category) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +> _**WARNING:**_ this parameter is ignored since version 8.5.2 + +--- +#### include-constraints +[//]: # (TODO: add link to binding constraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate binding constraints in the study. + +--- +#### include-hurdlecosts +[//]: # (TODO: document usage) +_**This section is under construction**_ + +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** + +--- +#### include-loopflowfee +[//]: # (TODO: document this parameter, seems to be deprecated) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### include-tc-minstablepower +[//]: # (TODO: add link to contraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate, for thermal units, the constraint of minimum stable power + +--- +#### include-tc-min-ud-time +[//]: # (TODO: add link to contraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate, for thermal units, the constraint of minimum start-up time + +--- +#### include-dayahead +[//]: # (TODO: add details + link to contraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate day-ahead reserve constraints + +--- +#### include-strategicreserve +[//]: # (TODO: add details + link to contraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate strategic reserve constraints + +--- +#### include-spinningreserve +[//]: # (TODO: add details + link to contraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate spinning reserve constraints + +--- +#### include-primaryreserve +[//]: # (TODO: add details + link to contraints doc) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** set this parameter to `true` if you want to activate primary reserve constraints + +--- +#### include-exportmps +[//]: # (TODO: in usage paragraph, add links to relevant doc of "first step" and "second step" of optimization) +- **Expected value:** one of the following (case-insensitive): + - `none` or `false` + - `optim-1` + - `optim-2` + - `both-optims` or `true` +- **Required:** no +- **Default value:** `none/false` +- **Usage:** use this parameter if you want to export the optimization problems in [MPS format](https://en.wikipedia.org/wiki/MPS_(format)): + - `none` or `false`: do not export any MPS + - `optim-1`: export MPS for firt step of the optimization + - `optim-2`: export MPS for second step of the optimization + - `both-optims` or `true`: export MPS for both steps of the optimization + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-include-exportmps-parameter). + +--- +#### include-split-exported-mps +[//]: # (TODO: document this parameter, seems to belong to another category) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +> _**WARNING:**_ this parameter is deprecated but is still needed for testing old studies + +--- +#### include-exportstructure +[//]: # (TODO: add link to AntaresXpansion) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** set to `true` to activate writing the [MPS](#include-exportmps) using the *AntaresXpansion* specific format + +--- +#### include-unfeasible-problem-behavior +- **Expected value:** one of the following (case-sensitive): + - `WARNING_DRY` + - `WARNING_MPS` + - `ERROR_DRY` + - `ERROR_MPS` +- **Required:** no +- **Default value:** `ERROR_MPS` +- **Usage:** defines the behavior of the simulator in case of an unfeasible problem. + - `WARNING_DRY`: continue simulation + - `WARNING_MPS`: continue simulation, but export the MPS of the unfeasible problem + - `ERROR_DRY`: stop simulation + - `ERROR_MPS`: stop simulation, and export the MPS of the unfeasible problem + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-include-unfeasible-problem-behavior-parameter). + +--- +#### solver-parameters +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +## Adequacy-patch parameters +Defines a set of options related to the [adequacy patch](optional-features/adequacy-patch.md). +The set of preferences is study-specific; it can be changed at any time and saved along with study data. +These parameters are listed under the `[adequacy patch]` section in the `.ini` file. + +--- +#### include-adq-patch +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `false` +- **Usage:** set this parameter to `true` if you want to enable the [Adequacy Patch](optional-features/adequacy-patch.md) algorithm. + +--- +#### set-to-null-ntc-from-physical-out-to-physical-in-for-first-step +[//]: # (TODO: usage is not clear) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** Transmission capacities from physical areas outside adequacy patch (area type 1) to physical areas + inside adequacy patch (area type 2). NTC is set to null (if true) only in the first step of adequacy patch local matching rule. + NTC from physical areas outside to physical areas inside adequacy patch (set to null / local values) + +--- +#### set-to-null-ntc-between-physical-out-for-first-step +[//]: # (TODO: usage is not clear) +- **Expected value:** `true` or `false` +- **Required:** no +- **Default value:** `true` +- **Usage:** Transmission capacities between physical areas outside adequacy patch (area type 1). + NTC is set to null (if true) only in the first step of adequacy patch local matching rule. + NTC between physical areas outside adequacy patch (set to null / local values) + +--- +#### price-taking-order +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** Price taking order (DENS / Load) + +--- +#### include-hurdle-cost-csr +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** Include hurdle cost in CSR optimization (false / true) + +--- +#### check-csr-cost-function +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** Check CSR cost function value prior and after CSR (false / true) + +--- +#### enable-first-step +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### threshold-initiate-curtailment-sharing-rule +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### threshold-display-local-matching-rule-violations +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### threshold-csr-variable-bounds-relaxation +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +## Other parameters +These parameters are listed under the `[other preferences]` section in the `.ini` file. + +--- +#### initial-reservoir-levels (DEPRECATED since 9.2: cold start is default behavior) +- **Expected value:** one of the following (case-insensitive): + - `cold start` + - `hot start` +- **Required:** no +- **Default value:** `cold start` +- **Usage:** initial reservoir levels: + - `cold start` + - `hot start` + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-initial-reservoir-levels-parameter). + +--- +#### hydro-heuristic-policy +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** one of the following (case-insensitive): + - `accommodate rule curves` + - `maximize generation` +- **Required:** no +- **Default value:** `accommodate rule curves` +- **Usage:** hydraulic heuristic policy: + - `accommodate rule curves` + - `maximize generation` + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-hydro-heuristic-policy-parameter). + +--- +#### hydro-pricing-mode +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** one of the following (case-insensitive): + - `fast` + - `accurate` +- **Required:** no +- **Default value:** `fast` +- **Usage:** + - `fast` + - `accurate`: Note that this mode is significantly slower than the `fast` mode. + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-hydro-pricing-mode-parameter). + +--- +#### power-fluctuations +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** one of the following (case-insensitive): + - `minimize ramping` + - `free modulations` + - `minimize excursions` +- **Required:** no +- **Default value:** `free modulations` +- **Usage:** + - `minimize ramping` + - `free modulations` + - `minimize excursions` + +--- +#### shedding-policy +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** one of the following (case-insensitive): + - `shave peaks` + - `minimize duration` +- **Required:** no +- **Default value:** `shave peaks` +- **Usage:** power shedding policy: + - `shave peaks`: + - `minimize duration`: + +--- +#### unit-commitment-mode +[//]: # (TODO: complete the usage paragraph by adding details & links to relevant UC doc) +- **Expected value:** one of the following (case-insensitive): + - `fast` + - `accurate` + - `milp` +- **Required:** no +- **Default value:** `fast` +- **Usage:** choose the mode in which Antares resolves the unit-commitment problem: + - `fast`: Heuristic in which 2 LP problems are solved. No explicit modelling for the number of ON/OFF units. + - `accurate`: Heuristic in which 2 LP problems are solved. Explicit modelling for the number of ON/OFF units. Slower than `fast`. + - `milp`: A single MILP problem is solved, with explicit modelling for the number of ON/OFF units. Slower than `accurate`. + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-unit-commitment-mode-parameter). + +--- +#### number-of-cores-mode +- **Expected value:** one of the following (case-insensitive): + - `minimum` + - `low` + - `medium` + - `high` + - `maximum` +- **Required:** no +- **Default value:** `medium` +- **Usage:** use this parameter to configure [multi-threading](optional-features/multi-threading.md). + +--- +#### renewable-generation-modelling +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** one of the following (case-insensitive): + - `aggregated` + - `clusters` +- **Required:** no +- **Default value:** `aggregated` +- **Usage:** + - `aggregated` + - `clusters` + +> _**Note:**_ You can find more information on this parameter [here](09-appendix.md#details-on-the-renewable-generation-modelling-parameter). + +--- +#### day-ahead-reserve-management +[//]: # (TODO: document this parameter, doesn't seem to belong to this category) +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +> _**WARNING:**_ this parameter is ignored since version 8.4 + +--- +## Advanced parameters +Advanced Parameters allow to adjust the simulation behavior regarding issues +that are more numerical than physical. The set of parameters is study-specific and can be updated at any time. +These parameters are listed under the `[advanced parameters]` section in the `.ini` file. + +--- +#### accuracy-on-correlation +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** comma-seperated list of 0 to N elements among the following (case-insensitive): + `load`, `wind`, `hydro`, `thermal`, `solar`, `renewables`, `ntc`, `max-power` +- **Required:** no +- **Default value:** empty +- **Usage:** + +--- +#### adequacy-block-size +[//]: # (TODO: document this parameter, seems to belong to another category) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +> _**WARNING:**_ this parameter is ignored since version 8.5 + +--- +## Seeds - Mersenne Twister parameters +These parameters are listed under the `[seeds - Mersenne Twister]` section in the `.ini` file. +They allow the user to set the seeds of random number generators, in order to ensure the results are repeatable. + +--- +#### seed-tsnumbers +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** fixes the seed for the random [Monte-Carlo years](#nbyears) selection. + +--- +#### seed-unsupplied-energy-costs +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** fixes the seed for the random noise generation on unsupplied energy costs. + +--- +#### seed-spilled-energy-costs +[//]: # (TODO: verify if required, if not, add default value) +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** fixes the seed for the random noise generation on spilled energy costs. + +--- +#### seed-thermal-costs +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** fixes the seed for the random noise generation on thermal plants' costs. + +--- +#### seed-hydro-costs +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** fixes the seed for the random noise generation on hydraulic plants' costs. + +--- +#### seed-initial-reservoir-levels +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** + +--- +## Playlist parameters +These parameters are listed under the `[playlist]` section in the `.ini` file. +They are **required** if [user-playlist](#user-playlist) is set to `true`. + +--- +#### playlist_reset +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** `true` or `false` +- **Required:** **yes**, if [user-playlist](#user-playlist) is set to `true`. +- **Usage:** + +--- +#### playlist_year +- **Expected value:** `+ =` or `- =`, followed by a positive integer (example: `playlist_year + = 5`) +- **Required:** **yes**, if [user-playlist](#user-playlist) is set to `true`, ignored otherwise. +- **Usage:** + - for every Monte-Carlo year that you want the Antares Simulator to **study**, add the parameter entry + `playlist_year + = i`, where `i` is the index of the year. + - for every Monte-Carlo year that you want the Antares Simulator to **skip**, add the parameter entry + `playlist_year - = i`, where `i` is the index of the year. + +_Please note that by convention, the first year has index 0._ + +--- +#### playlist_year_weight +[//]: # (TODO: document this parameter) +_**This section is under construction**_ + +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** +Each MC year i=1, …, N can be given a relative “weight†$W_i$ in the simulation (default value: 1). +The expectation and standard deviation of all random variables will then be computed as if the scenarios simulated were +sampled from a probability density function in which MC year i is given the probability +$$\frac{W_{i}}{\sum_{j=1,...,N}{W_{j}}}$$ + +--- +## Variables selection parameters +These parameters are listed under the `[variables selection]` section in the `.ini` file. +They are **required** if [thematic-trimming](#thematic-trimming) is set to `true`. + +--- +#### selected_vars_reset +[//]: # (TODO: complete the usage paragraph) +- **Expected value:** `true` or `false` +- **Required:** **yes**, if [thematic-trimming](#thematic-trimming) is set to `true`. +- **Usage:** + +--- +#### select_var +- **Expected value:** `+ =` or `- =`, followed by a string (example: `select_var + = LOAD`) +- **Required:** **yes**, if [thematic-trimming](#thematic-trimming) is set to `true`. +- **Usage:** + - for every optimization variable that you want the Antares Simulator to **export** in the outputs, add the + parameter entry `select_var + = VAR`, where `VAR` is the name of the variable. + - for every optimization variable that you want the Antares Simulator to **omit** from the outputs, add the + parameter entry `select_var - = VAR`, where `VAR` is the name of the variable. + +> _**WARNING:**_ this parameter is intended for use by expert users that know the name of the optimization variables created +> under-the-hood by Antares Simulator. + +--- +## Model-wise parameters +[//]: # (TODO: link to model-wise parameters documentation) +_**This section is under construction**_ diff --git a/docs/user-guide/solver/05-model.md b/docs/user-guide/solver/05-model.md new file mode 100644 index 0000000000..29816befd2 --- /dev/null +++ b/docs/user-guide/solver/05-model.md @@ -0,0 +1,559 @@ +# Optimization model + +[//]: # (TODO: update this page) +_**This section is under construction**_ + +**Document available on : [https://antares-simulator.org](https://antares-simulator.org/)** + +## Introduction + +The purpose of this document is to give every user of the **Antares\_Simulator** model (regardless of its version number), a detailed and comprehensive formulation of the main optimization problems solved by the application's inner optimization engine. + +The aim of the information presented hereafter is to provide a transparent access to the inner workings of the software from a **formal** standpoint. Note that, aside from this conceptual transparency, the software itself offers an option that makes it possible for the user to print, in a standardized format, any or all of the optimization problems actually solved in the course of an **Antares\_Simulator** session [^1]. + +Used together with the elements developed in the next pages, this **practical** access to the internal model implemented the tool allows fair and open benchmarking with comparable software. Besides, another important issue regarding transparency is addressed by the release of **Antares\_Simulator** as an Open Source Gnu GPL 3.0 application, now changed to MPL-2.0. + +So as to delimit the scope of the present document with as much clarity as possible, it is important to notice that a typical **Antares\_Simulator** session involves different steps that are usually run in sequence, either automatically or with some degree of man-in-the-loop control, depending on the kind of study to perform. + +These steps most often involve: + +1. GUI session dedicated to the initialization or to the updating of various input data sections (load time-series, grid topology, wind speed probability distribution, etc.) +2. GUI session dedicated to the definition of simulation contexts (definition of the number and consistency of the "Monte-Carlo years" to simulate) +3. Simulation session producing actual numeric scenarios following the directives defined in (2) +4. Optimization session aiming at solving all of the optimization problems associated with each of the scenarios produced in (3). +5. GUI session dedicated to the exploitation of the detailed results yielded by (4) + +The scope of this document is exclusively devoted to step (4). Note that equivalent information regarding the other steps may be found in other documents made available either: + +- Within the application itself, in the "?" menu +- On the **Antares\_Simulator** [^2] website (download section) : [https://antares-simulator.org](https://antares-simulator.org/) +- In technical publications referenced in the bibliography section of the website + +The following picture gives a functional view of all that is involved in steps (1) to (5). In this illustration, Step (4), whose goal is to solve the problems introduced in this document, is materialized by the red box. + +![Antares_Process](../img/Antares_Process.jpg) + +The number and the size of the individual problems to solve (a least-cost hydro-thermal unit-commitment and power schedule, with an hourly resolution and throughout a week, over a large interconnected system) make optimization sessions often computer-intensive. Note that the content of the blue "hydro energy manager" box appearing on the previous figure, whose purpose is to deal with energy storage issues at the seasonal scale, is not detailed in the present document but in the ["Miscellaneous"](../reference-guide/08-miscellaneous.md#the-heuristic-for-seasonal-hydro-pre-allocation) section. + +Depending on user-defined results accuracy requirements, various practical options allow to simplify either the formulation of the weekly UC & dispatch problems (e.g. do not account for constraints associated with operational reserves) or their resolution (i.e. find, for the native MILP, an approximate solution based on two successive LPs). For the sake of simplicity and clarity, the way these options are used to revise the primary problem formulation is not detailed hereafter. Likewise, many simplifications are introduced to keep notations as light as possible. This is why, for instance, the overall sum of load, wind power generation, solar power generation, run of the river generation, and all other kinds of so-called "must-run" generation is simply denoted "load" in the present document. + +## Typology of the problems solved + +In terms of power studies, the different fields of application Antares has been designed for are the following: + +- **Generation adequacy problems :** assessment of the need for new generating plants so as to keep the security of supply above a given critical threshold + +What is most important in these studies is to survey a great number of scenarios that represent well enough the random factors that may affect the balance between load and generation. Economic parameters do not play as much a critical role as they do in the other kinds of studies, since the stakes are mainly to know if and when supply security is likely to be jeopardized (detailed costs incurred in more ordinary conditions are of comparatively lower importance). In these studies, the default Antares option to use is the "Adequacy" simulation mode. + +- **Transmission project profitability :** assessment of the savings brought by a specific reinforcement of the grid, in terms of decrease of the overall system generation cost (using an assumption of fair and perfect market) and/or improvement of the security of supply (reduction of the loss-of-load expectation). + +In these studies, economic parameters and the physical modeling of the dynamic constraints bearing on the generating units are of paramount importance. Though a thorough survey of many "Monte-Carlo years" is still required, the number of scenarios to simulate is not as large as in generation adequacy studies. In these studies, the default Antares option to use is the "Economy" simulation mode. + +- **Generation and/or Transmission expansion planning:** rough assessment of the location and consistency of profitable reinforcements of the generating fleet and/or of the grid at a given horizon, on the basis of relevant reference costs and taking into account feasibility local constraints (bounds on the capacity of realistic reinforcements). + +These long term studies clearly differ from the previous ones in the sense that the generation and transmission assets that define the consistency of the power system are no longer passive parameters but are given the status of active problem variables. In the light of both the nature and the magnitude of the economic stakes, there is comparatively a lesser need than before for an accurate physical modeling of fine operational constraints or for an intensive exploration of a great many random scenarios. The computer intensiveness of expansion studies is, however, much higher than that of the other types because the generic optimization problem to address happens to be much larger. + +The common rationale of the modeling used in all of these studies is, whenever it is possible, to decompose the general issue (representation of the system behavior throughout many years, with a time step of one hour) into a series of standardized smaller problems. + +In **Antares\_Simulator**, the "elementary" optimization problem resulting from this approach is that of the minimization of the overall system operation cost over a week, taking into account all proportional and non-proportional generation costs, as well as transmission charges and "external" costs such as that of the unsupplied energy (generation shortage) or, conversely, that of the spilled energy (generation excess). + +In this light, carrying out generation adequacy studies or transmission projects studies means formulating and solving a series of a great many week-long operation problems (one for each week of each Monte-Carlo year ), assumed to be independent. This generic optimization problem will be further denoted $\mathcal{P}^k$, where $k$ is an index encompassing all weeks of all Monte-Carlo years. + +Note that this independency assumption may sometimes be too lax, because in many contexts weekly problems are actually coupled to some degree, as a result of energy constraints (management of reservoir-type hydro resources, refueling of nuclear power plants, etc.). When appropriate, these effects are therefore dealt with before the actual decomposition in weekly problems takes place, this being done[^3] either of the following way (depending on simulation options): + +1. Use of an economic signal (typically, a shadow "water value") yielded by an external preliminary stochastic dynamic programming optimization of the use of energy-constrained resources. +2. Use of heuristics that provide an assessment of the relevant energy credits that should be used for each period, fitted so as to accommodate with sufficient versatility different operational rules. + +Quite different is the situation that prevails in expansion studies, in which weekly problems cannot at all be separated from a formal standpoint, because new assets should be paid for all year-long, regardless of the fact that they are used or not during such or such week : the generic expansion problem encompasses therefore all the weeks of all the Monte-Carlo years at the same time. It will be further denoted $\mathcal{P}$. + +The next sections of this document develop the following subjects: + +- Notations used for $\mathcal{P}^k$ + +- Formulation of $\mathcal{P}^k$ + +- Complements to the standard problems (how to make **Antares\_Simulator** work as a SCOPF ) + +- Miscellaneous complements to the standard problems + +## Notations + +### General notations + +| Notation | Explanation | +|-----------------------|---------------------------------------------------------------------------------------------------------------------| +| $k \in K$ | optimization periods (weeks) over which $P$ and $P^k$ are defined (omitted for simplicity) | +| $t \in T$ | individual time steps of any optimization period $ k\in K$ (hours of the week) | +| $G(N,L)$ | undirected graph of the power system (connected) | +| $n \in N$ | vertices of $G$, $N$ is an ordered set | +| $l \in L$ | edges of $G$ | +| $A$ | incidence matrix of $G$, dimension $N\times L$ | +| $g$ | spanning tree of $G$ | +| $C_g$ | cycle basis associated with $g$, dimension $L\times (L+1-N)$ | +| $L_n^+\subset L$ | set of edges for which $n$ is the upstream vertex | +| $L_n^-\subset L$ | set of edges for which $n$ is the downstream vertex | +| $u_l \in N$ | vertex upstream from $l$ | +| $d_l \in N$ | vertex downstream from $l$ | +| $u \cdot v$ | inner product of vectors $u$ and $v$ | +| $u_\uparrow^p$ | vector resulting from the permutation on $u \in \mathbb{R}^s$ : $ u\_\uparrow^p(i)=u(i+p\, \mathrm{mod}\,s)$ | + +Problems $P^k$ and $P$ call for the definition of many parameters and variables further described. + +The power system is supposed to be operated so as to be able to face some amount of unexpected demand increase with redispatching actions only (no change in the unit commitment). Two operating states are therefore modelled: + +- **nominal**: Actual conditions match exactly all standard forecast. Demand is supplied by optimal generation dispatch (variable notation: _Var_). + +- **uplifted**: Additional demand increases are applied to the nominal state and call for redispatch (activation of security reserves; variable notation: _$Var^s$_). + +Note: Almost all variables of the system are defined twice (one value per state). For clarity's sake, only the definition of the nominal variables (_Var_) are given hereafter, the definition of variables _$Var^s$_ are implicit. + +### Grid + +| Notation | Explanation | +|------------------------------------------------|---------------------------------------------------------------------------------------------------------| +| $C_l^+ \in \mathbb{R}^T_+$ | initial transmission capacity from $u_l$ to $d_l$ (variable of $P$ and $P^k$) | +| $ \overline{C}\_l^+ \in \mathbb{R}^T\_+ $ | maximum transmission capacity from $u_l$ to $d_l$ (variable of $P$, not used in $P^k$) | +| $C_l^- \in \mathbb{R}^T_+$ | initial transmission capacity from $d_l$ to $u_l$ (variable of $P$ and $P^k$) | +| $ \overline{C}^{-}\_l\in \mathbb{R}^T\_{+} $ | maximum transmission capacity from $d_l$ to $u_l$ (variable of $P$, not used in $P^k$) | +| $\Psi_l \in \mathbb{R}_+$ | weekly cost of a maximum capacity investment | +| $x_l \in [0,1]$ | transmission capacity investment level | +| $F_l^+ \in \mathbb{R}^T_+$ | power flow through $l$, from $u_l$ to $d_l$ | +| $F_l^- \in \mathbb{R}^T_+$ | power flow through $l$, from $d_l$ to $u_l$ | +| $F_l\in \mathbb{R}^T$ | total power flow through $l$, $F_l=F_l^+-F_l^-$ | +| $\tilde{F}_t \in \mathbb{R}^T$ | system flow snapshot at time $t$ | +| $\gamma_l^+\in \mathbb{R}^T$ | transmission cost through $l$, from $u_l$ to $d_l$. Proportional to the power flow | +| $\gamma_l^-\in \mathbb{R}^T$ | transmission cost through $l$, from $d_l$ to $u_l$. Proportional to the power flow | +| $Z_l \in \mathbb{R}\_+$ | overall impedance of $l$ | + +### Thermal units + +| Notation | Explanation | +|----------------------------------------------------------------|-----------------------------------------------------------------------------------------| +| $\theta \in \Theta_n$ | thermal clusters (sets of identical units) installed in node $n$ | +| $\Theta$ | set of all thermal clusters of the power system $\Theta = \cup_{n\in N} \Theta_n$ | +| $\overline{P}\_\theta \in \mathbb{R}^T_+$ | maximum power output from cluster $\theta$, depends on units availability | +| $\underline{P}\_\theta \in \mathbb{R}^T_+$ | mimimum power output from cluster $\theta$, units availability allowing | +| $P_\theta \in \mathbb{R}^T_+$ | power output from cluster $\theta$ | +| $\chi_\theta \in \mathbb{R}^T$ | power output from cluster $\theta$ | +| $\sigma_\theta^+ \in \mathbb{R}^T$ | startup cost of a single unit in cluster $\theta$ | +| $\tau_\theta \in \mathbb{R}^T$ | running unit in $\theta$ : cost independent from output level (aka NoLoadHeatCost) | +| $l_\theta \in \mathbb{R}_+$ | unit in $\theta$ : minimum stable power output when running | +| $u_\theta \in \mathbb{R}_+$ | unit in $\theta$ : maximum net power output when running | +| $\Delta_\theta^+ \in \lbrace 1,\dots, \|T\|\rbrace$ | unit in $\theta$ : minumum on time when running | +| $\Delta_\theta^- \in \lbrace 1,\dots, \|T\|\rbrace$ | unit in $\theta$ : minumum off time when not running | +| $\Delta_\theta = \max(\Delta_\theta^-, \Delta_\theta^+) $ | duration above which both state changes are allowed | +| $M_\theta \in \mathbb{N}^T$ | number of running units in cluster $\theta$ | +| $\overline{M}_\theta \in \mathbb{N}^T$ | maximum number of running units in cluster $\theta$ | +| $\underline{M}_\theta \in \mathbb{N}^T$ | minimum number of running units in cluster $\theta$ | +| $M_\theta^+ \in \mathbb{N}^T$ | number of units in cluster changing from state off to state on in cluster $\theta$ | +| $M_\theta^- \in \mathbb{N}^T$ | number of units in cluster changing from state on to state off in cluster $\theta$ | +| $M_\theta^{--} \in \mathbb{N}^T$ | number of units in cluster changing from state on to state outage cluster $\theta$ | + +### Reservoir-type hydropower units (or other power storage facilities) + +| Notation | Explanation | +|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| $\lambda \in \Lambda_n$ | reservoirs connected to node $n$ | +| $\Sigma_\lambda \in \mathbb{R}_+$ | size of reservoir $\lambda$ : amount of energy that can be stored in $\lambda$ | +| $Q\in \mathbb{N}$ | number of discrete levels defined in reservoir | +| $\overline{W}\_\lambda \in \mathbb{R}_+$ | maximum energy output from $\lambda$ throughout the optimization period | +| $\underline{W}\_\lambda \in \mathbb{R}_+$ | minimum energy output from $\lambda$ throughout the optimization period | +| $\overline{H}\_\lambda \in \mathbb{R}_+^T$ | maximum power output from reservoir $\lambda$. Note : $\sum_{t\in T} \overline{H}\_{\lambda\_t} \geq \underline{W}\_\lambda$ | +| $\underline{H}\_\lambda \in \mathbb{R}_+^T$ | minimum power output from reservoir $\lambda$. Note : $\sum_{t\in T} \underline{H}\_{\lambda\_t} \leq \overline{W}\_\lambda$ | +| $H\_\lambda \in \mathbb{R}_+^T$ | power output from reservoir $\lambda$ | +| $r\_\lambda \in \mathbb{R}_+$ | maximum ratio between output power daily peak and daily average ($1 \leq r\_\lambda \leq 24$) | +| $\varepsilon\_\lambda \in \mathbb{R}$ | reference water value associated with the reservoir's initial state (date, level) | $\eta\_\lambda \in \mathbb{R}^Q$ | reference water value associated with the reservoir's final state (date)
    if _hydro pricing option := fast_ then : $\eta\_\lambda \leftarrow 0$
    if _hydro pricing option := accurate_ then : $v_\lambda \leftarrow 0$ | +| $\epsilon\_\lambda^1 \in \mathbb{R}$ | penalty fee on hydro generation variations (dispatch smoothing effect)
    if _hydro power fluctuations option := free modulations_ then $\epsilon_\lambda^1 \leftarrow O $ | +| $\epsilon\_\lambda^2 \in \mathbb{R}$ | penalty fee on hydro generation maximum varition (dispatch smoothing effect)
    if _hydro power fluctuations option := free modulations_ then $\epsilon_\lambda^2 \leftarrow O $ | +| $\omega\_\lambda \in \mathbb{R}$ | overflow value (value of energy impossible to store in reservoir $\lambda$ | | +| $\varepsilon^*\_\lambda \in \mathbb{R}$ | random component added to the water value (dispatch smoothing effect) | +| $\eta\_\lambda \in \mathbb{R}^Q$ | reference water value associated with the reservoir's final state (date) | +| $\rho\_\lambda \in \mathbb{R}_+$ | efficiency ratio of pumping units (or equivalent devices) available in reservoir $\lambda$ | +| $\overline{\Pi}\_\lambda \in \mathbb{R}_+^T$ | maximum power absorbed by pumps of reservoir $\lambda$ | +| $\Pi\_\lambda \in \mathbb{R}_+^T$ | power absorbed by pumps of reservoir $\lambda$ | +| $I\_\lambda \in \mathbb{R}^T_+$ | natural power inflow to reservoir $\lambda$ | +| $O\_\lambda \in \mathbb{R}_+^T$ | power overflowing from reservoir $\lambda$ : part of inflow that cannot be stored | +| $\overline{R}\_\lambda \in \mathbb{R}_+^T$ | upper bound of the admissible level in reservoir $\lambda$ | +| $\underline{R}\_\lambda \in \mathbb{R}_+^T$ | lower bound of the admissible level in reservoir $\lambda$ | +| $R\_\lambda \in \mathbb{R}^T_+$ | stored energy level in reservoir $\lambda$ | +| $\mathfrak{R}\_{\lambda_q} \in \mathbb{R}_+$ | filling level of reservoir layer $q$ at time $T$ (end of the week) | + +### Binding constraints + +In problems $\mathcal{P}^k$, the need for a versatile modelling of the power system calls for the introduction of an arbitrary number of linear binding constraints between system's variables throughout the grid, expressed either in terms of hourly power, daily energies or weekly energies. +These constraints may bind together synchronous flows as well as thermal units power outputs. They may be related to synchronous values or bear on different times. +Herebelow, the generic notation size is used for the relevant dimension of the set to which parameters belong. + +These dimensions stand as follow + +$\mathrm{size}=T=168$ : applicable to lower and upper bounds of constraints between hourly powers +$\mathrm{size}=\frac{T}{7}=24$ : applicable to lower and upper bounds of constraints between daily energies +$\mathrm{size}=\frac{T}{168}=1$ : applicable to lower and upper bounds of constraints between weekly energies + +Generic notations for binding constraints : + +| Notation | Explanation | +|-------------------------------------------|--------------------------------------------------------------------------------------------------------------| +| $e \in E$ | set of all grid interconnections and thermal clusters. $E = L \cup \Theta$ | +| $b \in B$ | binding constraints | +| $B_h \subset B$ | subset of $B$ containing the binding constraints between hourly powers | +| $B_d \subset B$ | subset of $B$ containing the binding constraints between daily energies | +| $B_w \subset B$ | subset of $B$ containing the binding constraints between weekly energies | +| $\alpha_e^b \in \mathbb{R}$ | weight of $e$ (flow within $e$ or output from $e$) in the expression of constraint $b$ | +| $o_e^b \in \mathbb{N}$ | time offset of $e$ (flow within $e$ or output from $e$) in the expression of constraint $b$ | +| $u^b \in \mathbb{R}^{\mathrm{size}}$ | upper bound of binding constraint $b$ | +| $l^b \in \mathbb{R}^{\mathrm{size}}$ | lower bound of binding constraint $b$ | + +### Demand, security uplift, unsupplied and spilled energies + +| Notation | Explanation | +|-------------------------------|------------------------------------------------------------------------------------| +| $D_n \in \mathbb{R}^T$ | net power demand expressed in node $n$, including must-run generation | +| $S_n \in \mathbb{R}^T_+$ | demand security uplift to be faced in node $n$, by activation of security reserves | +| $\delta_n^+ \in \mathbb{R}^T$ | normative unsupplied energy value in node $n$. Value of lost load - VOLL | +| $G_n^+ \in \mathbb{R}^T_+$ | unsupplied power in the nominal state | +| $\delta_n^- \in \mathbb{R}^T$ | normative spilled energy value in node $n$ (value of wasted energy) | +| $G_n^- \in \mathbb{R}^T_+$ | spilled power in the nominal state | + +## Formulation of problem $\mathcal{P}^k$ + +Superscript k is implicit in all subsequent notations of this section (omitted for simplicity's sake) + +## Objective +$$ +\min\_{M\_\theta \in \mathrm{Argmin} \Omega\_{\mathrm{unit com}}}(\Omega\_{\mathrm{dispatch}}) +$$ + + +with + + +$$ +\Omega\_{\mathrm{dispatch}} = \Omega\_{\mathrm{transmission}}+\Omega\_{\mathrm{hydro}}+\Omega\_{\mathrm{thermal}}+\Omega\_{\mathrm{unsupplied}}+\Omega\_{\mathrm{spillage}} +$$ + + +$$ +\Omega\_{\mathrm{transmission}}=\sum_{l \in L} \gamma_l^+ \cdot F_l^+ + \gamma_l^- \cdot F_l^- +$$ + + +$$ +\Omega\_{\mathrm{hydro}} = \sum\_{n \in N} \sum\_{\lambda in \Lambda\_n} (\varepsilon\_\lambda + \varepsilon^*\_\lambda)\cdot(H\_\lambda - \rho\_\lambda \Pi\_\lambda + O\_\lambda) - \sum\_{n \in N} \sum\_{\lambda \in \Lambda\_n}\sum\_{q=1}^Q \eta\_{\lambda\_q} \mathfrak{R}\_{\lambda_q} +$$ + + +$$ +\Omega\_{\mathrm{thermal}}=\sum\_{n \in N} \sum\_{\theta \in \Theta\_n} \chi\_\theta \cdot P\_\theta + \sigma\_\theta^+ \cdot M\_\theta^+ + \tau\_\theta \cdot M\_\theta +$$ + + +$$ +\Omega\_{\mathrm{unsupplied}}=\sum\_{n \in N} \delta_n^+ \cdot G_n^+ +$$ + + +$$ +\Omega\_{\mathrm{spillage}}=\sum\_{n \in N} \delta_n^- \cdot G_n^- +$$ + +$\Omega\_{\mathrm{unit com}}$ is the expression derived from $\Omega\_{\mathrm{dispatch}}$ by replacing all variables that depend on the system's state by their equivalent in the uplifted state. + +## Constraints related to the nominal system state + +### Balance between load and generation: + +First Kirchhoff's law: + +$$ +\forall n \in N, \sum\_{l \in L\_n^+} F_l - \sum\_{l \in L\_n^-} F_l = \left( G\_n^+ + \sum\_{\lambda \in \Lambda\_n}(H\_\lambda - \Pi\_\lambda) + \sum\_{\theta \ \in \Theta\_n} P\_\theta\right)-(G\_n^-+D\_n) +$$ + + +On each node, the unsupplied power is bounded by the net positive demand: + +$$ +\forall n \in N, 0 \leq G\_n^+ \leq \max(0, D_n) +$$ + +On each node, the spilled power is bounded by the overall generation of the node (must-run + dispatchable power): + +$$ +\forall n \in N, 0 \leq G_n^- \leq -\min(0, D_n) + \sum\_{\lambda \in \Lambda\_n}H\_\lambda + \sum\_{\theta \ \in \Theta\_n} P\_\theta +$$ + +Flows on the grid: + +$$ +\forall l \in L, 0 \leq F\_l^+ \leq C\_l^+ +(\overline{C}^{+}\_l - C\_l^+)x\_l +$$ + +$$ +\forall l \in L, 0 \leq F\_l^- \leq C\_l^- +(\overline{C}^{-}\_l - C\_l^-)x\_l +$$ + +$$ +\forall l \in L, F\_l = F\_l^+ - F\_l^- +$$ + +Flows are bounded by the sum of an initial capacity and of a complement brought by investment + +Binding constraints : + +$$ +\forall b \in B\_h, l^b \leq \sum\_{e \in E} \alpha\_e^b (F\_e)\_{\uparrow}^{o\_e^b} \leq u^b +$$ + +$$ +\forall b \in B\_d, \forall k \in \lbrace 0,\dots,6\rbrace, l^b \leq \sum\_{e \in E} \alpha\_e^b \sum\_{t \in \lbrace 1,\dots,24\rbrace} (F\_e)\_{\uparrow {24k+t}}^{o\_e^b} \leq u^b +$$ + +$$ +\forall b \in B\_w, l^b \leq \sum\_{e \in E} \alpha\_e^b \sum\_{t \in T} F\_{e\_t} \leq u^b +$$ + +### Binding constraints: + +$$ +\forall n \in N, \forall \lambda \in \Lambda\_n, \underline{W}\_{\lambda} \ leq \sum\_{t\in T} H\_{\lambda\_t} \leq \overline{W}\_{\lambda} +$$ + +FIXME : RHS +$$ +\forall n \in N, \forall \lambda \in \Lambda\_n, \sum\_{t\in T} H\_{\lambda\_t} - \sum\_{t\in T} \rho\_t \Pi\_{\lambda\_t} = \overline{W}\_{\lambda} +$$ + +Instantaneous generating power is bounded + +$$ +\forall n \in N, \forall \lambda \in \Lambda\_n, \underline{H}\_{\lambda} \leq H\_{\lambda} \leq \overline{H}\_{\lambda} +$$ + +Intra-daily power modulations are bounded and power fluctuations may be subject to penalty fees [^12] + +$$ +\forall n \in N, \forall \lambda \in \Lambda\_n, \forall k \in \lbrace 1, \ldots, 6 \rbrace, \frac{\max\_{t \in \lbrace 24k+1,\ldots, 24k+24 \rbrace} H\_{\lambda\_t}}{\sum\_{t \in \lbrace 24k+1,\ldots, 24k+24 \rbrace} H\_{\lambda\_t}} \leq r\_{\lambda} +$$ + +Instantaneous pumping power is bounded + +$$ +\forall n \in N, \forall \lambda \in \Lambda\_n, 0 \leq \Pi\_{\lambda} \leq \overline{\Pi}\_{\lambda} +$$ + +Reservoir level evolution depends on generating power, pumping power, pumping efficiency, natural inflows and overflows + +$$ +(14)(a) \forall n \in N, \forall \lambda \in \Lambda\_n, \forall t \in T, R_{\lambda_t} - R_{\lambda_{t-1}} = \rho_\lambda \Pi_{\lambda_t} - H_{\lambda_t} + I_{\lambda_t} - O_{\lambda_t} +$$ + +$$ +(14)(b) \forall n \in N, \forall \lambda \in \Lambda\_n, R_{\lambda T} = \sum_{q=1,Q} \mathfrak{R}_{\lambda_q} +$$ + +$$ +(14)(c) \forall n \in N, \forall \lambda \in \Lambda\_n, q=1,Q, \mathfrak{R}\_{\lambda_q} \leq \sum\_{\lambda} \frac{1}{Q} +$$ + +Reservoir level is bounded by admissible lower and upper bounds (rule curves) + +$$ +(15) \forall n \in N, \forall \lambda \in \Lambda\_n, \underline{R}\_\lambda \leq R_\lambda \leq \overline{R}_\lambda +$$ + +### Thermal units : [^8] + +Power output is bounded by must-run commitments and power availability + +$$ +(16) \forall n \in N, \forall \theta \in \Theta\_n, \underline{P_\theta} \leq P_\theta \leq \overline{P_\theta} +$$ + +The number of running units is bounded + +$$ +(17) \forall n \in N, \forall \theta \in \Theta\_n, \underline{M_\theta} \leq M_\theta \leq \overline{M_\theta} +$$ + +Power output remains within limits set by minimum stable power and maximum capacity thresholds + +$$ +(18) \forall n \in N, \forall \theta \in \Theta\_n, l_\theta M_\theta \leq M_\theta \leq u_\theta M_\theta +$$ + + +Minimum running and not-running durations contribute to the unit-commitment plan. Note that this modeling requires[^9] that one at least of the following conditions is met: $\Delta_\theta^- \leq \Delta_\theta^+$ or $\overline{M}_\theta \leq 1_T$ + +$$ +(19) \forall n \in N, \forall \theta \in \Theta\_n, \forall t \in T, M_{\theta_t} = M_{\theta_{t-1}} + M_{\theta_t}^+ - M_{\theta_t}^- +$$ + +$$ +(20) \forall n \in N, \forall \theta \in \Theta\_n, \forall t \in T, {M_\theta^{- -}}_t \leq {M _ \theta^{-}}_t +$$ + +$$ +(21) \forall n \in N, \forall \theta \in \Theta\_n, \forall t \in T, {M_\theta^{- -}}\_t \leq \max(0, \overline{M}\_{\theta_{t-1}} - \overline{M}\_{\theta_t}) +$$ + +$$ +(22) \forall n \in N, \forall \theta \in \Theta\_n, \forall t \in T, M_{\theta_ t} \geq \sum_{k=t+1-\Delta_\theta^+}^{k=t}(M_{\theta_k}^+ - {M_\theta^{- -}}_k) +$$ + +$$ +(23) \forall n \in N, \forall \theta \in \Theta\_n, \forall t \in T, M_{\theta_t} \leq \overline{M}\_{\theta_{t - \Delta_\theta^-}} + \sum_{k=t+1-\Delta_\theta^+}^{k=t} \max(0, \overline{M}\_{\theta_k} - \overline{M}\_{\theta_{k-1}}) - \sum_{k=t+1-\Delta_\theta^+}^{k=t}(M_{\theta_k}^-) +$$ + +### Constraints related to the uplifted system state (activation of security reserves) + +All constraints (1) to (23) previously defined for regular operation conditions are repeated with replacement of all variables _Var_ by their twins _$Var^s$_ when they exist. + +Besides, in the expression of constraints , all occurrences of are replaced by $D_n + S_n$ + +## Antares as a SCOPF ("flow-based model") + +When problems $\mathcal{P}^k$ do not include any instance of so-called "binding constraints" and if no market pools are defined, the flows within the grid are only committed to meet the bounds set on the initial transmission capacities, potentially reinforced by investments (problem ).In other words, there are no electrical laws enforcing any particular pattern on the flows, even though hurdles costs and may influence flow directions through an economic signal. + +In the general case, such a raw backbone model is a very simplified representation of a real power system whose topology and consistency are much more complex. While the full detailed modeling of the system within Antares is most often out of the question, it may happen that additional data and/or observations can be incorporated in the problems solved by the software. + +In a particularly favorable case, various upstream studies, taking account the detailed system characteristics in different operation conditions (generating units outages and/or grid components outages N, N-1 , N-k,…) may prove able to provide a translation of all relevant system limits as a set of additional linear constraints on the power flowing on the graph $G(N,L)$ handled by Antares. + +These can therefore be readily translated as "hourly binding constraints", without any loss of information. This kind of model will be further referred to as a "flow-based model"[^FB]. Its potential downside is the fact that data may prove to be volatile in short-term studies and difficult to assess in long-term studies. + +## Antares as a SCOPF ("KL model") + +When a full flow-based model cannot be set up (lack of robust data for the relevant horizon), it remains possible that classical power system studies carried on the detailed system yield sufficient information to enrich the raw backbone model. An occurrence of particular interest is when these studies show that the physics of the active power flow within the real system can be valuably approached by considering that the edges $l$ of $G(N,L)$ behave as simple impedances $Z_l$.This model can be further improved if a residual (passive) loop flow is to be expected on the real system when all nodes have a zero net import and export balance (situation typically encountered when individual nodes actually represent large regions of the real system). This passive loop flow should therefore be added to the classical flow dictated by Kirchhoff's rules on the basis of impedances $Z_l$. This model will be further referred to as a "KL model"[^KL]. Different categories of binding constraints, presented hereafter, make it possible to implement this feature in $\mathcal{P}^k$ and $\mathcal{P}$. + +### Implementation of Kirchhoff's second law + +The implementation ofKirchhoff's second law for the reference state calls for the following additional hourly binding $L+1-N$ constraints: + +$$ +\forall t \in T, C\_{g}^t Diag(Z\_{l}) \tilde{F}\_{t} = 0 +$$ + +### Implementation of a passive loop flow + +In cases where a residual passive loop flow $\tilde{\phi}\_{t}$ should be incorporated in the model to complete the enforcement of regular Kirchhoff's rules, the binding constraints mentioned in 7.1 should be replaced by: + +$$ +\forall t \in T, C\_{g}^t Diag(Z\_{l}) \tilde{F}\_{t} = C\_{g}^t Diag(Z\_{l}) \tilde{\phi}\_{t} +$$ + +### Modelling of phase-shifting transformers + +In cases where the power system is equipped with phase-shifting transformers whose ratings are known, ad hoc classical power studies can be carried out to identify the minimum and maximum flow deviations and phase-shift that each component may induce on the grid. The following additional notations are in order: + +| Notation | Explanation | +|-----------------------------------------|-------------------------------------------------------------------------------------------------| +| $\Pi\_{l}^{+shift} \in \mathbb{R}\_{+}$ | Maximum positive shifting ability of a device equipping link $l$ | +| $\Pi^{+shift} \in \mathbb{R}^{L}$ | Snapshots formed by all positive synchronous deviations $\Pi\_{l}^{+shift} \in \mathbb{R}\_{+}$ | +| $\Pi\_{l}^{+shift} \in \mathbb{R}\_{-}$ | Maximum negative shifting ability of a device equipping link $l$ | +| $\Pi^{-shift} \in \mathbb{R}^{L}$ | Snapshots formed by all negative synchronous deviations $\Pi\_{l}^{-shift} \in \mathbb{R}\_{-}$ | + +The enhancement of the model with a representation of the phase-shifting components of the real system then requires to re-formulate as follows the binding constraints defined in 7.2: + +$$ +\forall t \in T, C\_{g}^t Diag(Z\_{l}) \tilde{\phi}\_{t} - \Pi^{-shift} \leq C\_{g}^t Diag(Z\_{l}) \tilde{F}\_{t} \leq C\_{g}^t Diag(Z\_{l}) \tilde{\phi}\_{t} + \Pi^{+shift} +$$ + +### Modelling of DC components + +When the power system graph contains edges that represent DC components, additional notations need be defined: + +| Notation | Explanation | +|-----------------------|---------------------------------------------------------------------------------------------------------------------| +| $L^* \subset L$ | subset of edges representing AC components | +| $G^*(N,L^*)$ | subgraph of $G(N,L)$ | +| $g^*$ | spanning tree of $G^*(N,L^*)$ | +| $C^*_{g^*}$ | cycle matric of $G^*(N,L^*)$ associated with $g^*$ | + +The proper modeling of the system then requires that all "load flow" constraints defined previously be formulated using notations $(L^*, G^*(N,L^*), C^*\_{g^*})$ instead of $(L, G(N,L), C_{g})$. + +### Implementation of security rules N-1,..., N-k + +It is assumed here that upstream power system classical calculations on the detailed system are assumed to have provided appropriate estimates for line outage distribution factors (LODFs) for all components involved in the contingency situations to consider. The following additional notations can therefore be introduced: + +| Notation | Explanation | +|--------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| $O \subset PL$ | set of situations (single or multiple outages) considered in the contingency analysis | +| $Q \in O$ | situation (incident) considered in the contingency analysis | +| ${}^Qp_l^m \in [-1,1]$ | LODFs from component $m$ (involved in $Q$) on component $l$ if $Q$ occurs | +| $\underline{F}_l^Q \in \mathbb{R}^T$ | lower bound of the power flow through $l$ if $Q$ occurs | +| $\overline{F}_l^Q \in \mathbb{R}^T$ | upper bound of the power flow through $l$ if $Q$ occurs | + +The implementation of security rules for the chosen situations requires the following $|L||O|$ additional binding constraints: + +$$ +\forall Q \in O, \forall l \in L, \underline{F}\_l^Q \leq F_l + \sum_{m \in Q} {}^Qp_l^m F_m \leq \overline{F}_l^Q +$$ + +## Random and Epsilon parameters in Antares + +The description given beforehand of the standard optimization problem solved each week within an Antares simulation session does not address some numeric issues that are of great importance in the operational value of simulation outputs. This paragraph gives therefore some details about the role played in Antares by several kinds of parameters that represent neither regular costs nor physical limits of the power system components. + +The first general category of such numbers is a â€low-level†one, which is not actually dealt with by Antares, since it involves only parameters defined and used by the software called by Antares to solve the problems once they are completely defined. These numbers, out of reach of the Antares user[^user], mainly include numeric accuracy requirements (various deterministic tolerance thresholds) and perturbations which aim either at +speeding up the walk toward an optimal solution (counter-measures against degeneracy) or at discovering more than one optimal solution, when such multiple optima do exist. + +Within this set of parameters, random numbers are normally generated by an appropriate algorithm using deterministic seeds that do not depend on the state of the machine at runtime. As a result, successive resolutions of the same problem on different machines, by the same solver, should yield exactly the same +solutions[^solutions]. Unfortunately, this does not imply at all that successive resolutions of the same problem with different solvers would produce the same solutions. + +Even more importantly, there is absolutely no guarantee that different weekly problems that look very much alike[^alike] will not lead to optimal solutions that are unrealistically close though they are mathematically valid. The risk exists indeed that the solver’s outputs show repetitive patterns that may be wrongly taken for meaningful economic invariants. + +To address both the issues of stability (no dependency to either the solver or the machine used) and diversity (variables that play identical roles should contribute with equal shares to the long-run simulation statistics), sets of “high level†random epsilons are incorporated by Antares to the description of the optimization problem defined by the raw power system input data. + +These numbers take the form of numeric noises on thermal generation costs, hydro generation costs, unsupplied energy costs and spilled energy costs[^costs]. They are generated by several instances of the “Mersenne Twister†algorithm (MT19937), whose seeds are made accessible through the standard user interface. + +Aside from these random epsilons, there is in Antares a need for a large set of other random numbers that are required to define in detail the consistency of each Monte-Carlo scenarios. This includes the setting up of the initial (hydro) reservoir levels, the automatic generation of several kinds of time-series (if the built-in timeseries generators are activated), the draws of time-series (either ready-made or generated on the spot) and, possibly, random deviations from the standard costs prescribed by the user (spreads). All of these numbers are, again, generated by dedicated instances of MT19937. + +For the sake of exhaustiveness, it has to be noted that there is, aside from random epsilons, a handful of deterministic epsilons that help define the way hydro or other storable resources should be managed. In the course of the simulation, these auxiliary parameters take the form of penalties that may be put or not on hydro hourly power fluctuations (two types of penalties may be used for that purpose, they appear explicitly in the problem formulation with notations $\epsilon_\lambda^1$ and $\epsilon_\lambda^2$). + +Finally, upstream of the proper optimization, there is a last set of hydro-related parameters that help drive the hydro heuristic engine (this code is deemed to provide a way for Antares to use storable resources when no actual stock value is available). Note that, since the heuristic stage is completely independent from the actual optimization, the absolute magnitude of the hydro-drivers has absolutely no influence on the output of the weekly problem (large numbers could be used instead of epsilons, provided their relative scale is preserved). + +The following diagram summarizes the situation regarding both random and epsilon numbers defined and used within Antares. They are meant to build up, along with the regular description of the power system (physical limits and standard costs), an optimization framework that is up to the complex tasks at hand: balanced Monte- Carlo draws, reproducible simulations exploring the whole span of optimal operating configurations. + +![Random_Parameters](img/Random_Parameters.png) + +| Random Epsilons | Minimum absolute value | Maximum absolute value | +|-----------------|-------------------------|--------------------------| +| N_THERMAL | $5 \cdot 10^{-4}$ €/MWh | $6 \cdot 10^{-4}$ €/MWh | +| N_UNSUPPLIED | $5 \cdot 10^{-4}$ €/MWh | $6 \cdot 10^{-4}$ €/MWh | +| N_SPILLAGE | $5 \cdot 10^{-4}$ €/MWh | $6 \cdot 10^{-4}$ €/MWh | +| N_HYDRO | $5 \cdot 10^{-4}$ €/MWh | $10 \cdot 10^{-4}$ €/MWh | + +It can be noted that, in absolute value, all random epsilons are smaller than the lower bound of the (non-zero) actual +costs that can be defined through the user interface (CLB – cost lower bound : $5 \cdot 10^{-3}$ €/MWh) + +[^1]: User guide , section « optimization preferences : "export mps problems" + +[^2]: For the sake of simplicity, the **Antares\_Simulator** application will be further denoted « Antares » + +[^3]: See «hydro» sections of the General User guide ("hydro" standing as a generic name for all types of energy storage facilities) + +Copyright © RTE 2007-2023 – Version 8.6.0 + +Last Rev : M. Doquet - 25 JAN 2023 + +[^10]: Contraints 10(a) are not implemented if the "heuristic" mode is used without any leeway and if there are no pumping capacities.
    Contraints 10(b) are implemented if the "heuristic" mode is used without any leeway.
    Contraints 10(c) are implemented if there are pumping capacities. + +[^12]: Contraints 12(a) are implemented only if the "heuristic" mode is used.
    Contraints 12(b) are implemented only if the "power fluctuations" option is set to "minimize ramping".
    Contraints 12(c) are implemented only if the "power fluctuations" option is set to "minimize excursion". + +[^14]: Constraints 14(a) are not implemented if the "heuristic" mode is used without any leeway and if there are no pumping capacities.
    Constraints 14(b) and 14(c) are implemented only if the option "hydro pricing mode" is set to "accurate". + +[^14a]: In the equation attached to the first time slot t, $R_{\lambda_{t-1}}$ is not a variable but a parameter (reservoir initial level) + +[^8]: The constraints implemented depend on the option selected for unit commitment. In "fast" mode, implementation is restricted to (16), whereas "accurate" mode involved modelling of constraints (16) to (23). Note that in both cases, a heuristic stage takes place between the "uplifted" and "nominal" optimization runs to deal with integrity issues. + +[^9]: This does not actually limit the model's field of application: all datasets can easily be put in a format that meets this commitment. + +[^FB]: FB stands for "flow-based", denomination used in the framework given to the internal electricity market of western Europe. + +[^KL]: KL stands for "Kirchhoff-and-Loop". Such a model was used in the European [E-Highway project](http://www;e-highwy2050.eu). + +[^user]: And sometimes out of reach of the solver user as well (if the code is in closed form and if the user is not given access to the parameters by the solver’s interface) + +[^solutions]: Provided that the code be compiled with hardware-independent floating point-related options (IEEE754 arithmetic and micro-coding of math library functions). + +[^alike]: Consider for instance a case where a fleet of ten exactly identical plants, in a highly symmetric system, is expected to generate an overall amount of power roughly equivalent to the nominal capacity of two of them. Simulations results indicating that this power should exclusively be provided by a specific pair of units (the other eight remaining always idle, throughout all Monte Carlo scenarios), would appear heavily biased, though not mathematically wrong. + +[^costs]: These random noises affect only cost-related parameters and not RHS parameters (such perturbations, which have not been implemented so far, might bring some benefits as regards degeneracy). It can also be noted that, in the special case of hydro, the random noise is present in the problem formulation given in this document, with notation $\epsilon_\lambda^0$. diff --git a/docs/user-guide/solver/06-hydro-heuristics.md b/docs/user-guide/solver/06-hydro-heuristics.md new file mode 100644 index 0000000000..78ff065933 --- /dev/null +++ b/docs/user-guide/solver/06-hydro-heuristics.md @@ -0,0 +1,193 @@ +# Hydro heuristics + +_**This section is under construction**_ + +## Seasonal hydro pre-allocation + +Basically, the seasonal hydro pre-allocation process comprises two stages carried out two times +(first time: monthly scale; second time: daily scale). + +- Stage 1: Definition of an allocation ideal modulation profile, which may be based (or not) on local and/or + remote load profiles. +- Stage 2: Mitigation of the previous raw profile to obtain a feasible hydro ideal target, + compatible as much as possible with reservoir rule curves. + +The description given hereafter makes use of the following local notations, +not be confused with those of the document "optimization problem formulation" +(dedicated to the optimal hydro-thermal unit-commitment and dispatch problem): + +- $Z$ Number of Areas (zones $z$) in the system +- $M_{zh}$ Hourly time-series of cumulated must-generation of all kinds for zone $z$ +- $M_{zd}$ Daily time-series of cumulated must-generation of all kinds for zone $z$ (sum of $M_{zh}$) +- $M_{zm}$ Monthly time-series of cumulated must-generation of all kinds for zone $z$ (sum of $M_{zh}$) +- $M_{z.}$ Either $M_{zd}$ or $M_{zm}$, relevant time index "." is defined by the context +- $L_{z.}$ Time-series of "natural" load for zone $z$ +- $A$ Inter-area hydro-allocation matrix (dimension_ $x Z$ ) $A_{uv}$ is a weight given to the load + of area $u$ in the definition of the monthly and daily primary hydro generation target of area $v$ + Extreme cases are: + + - **A is the identity matrix** + The hydro storage energy monthly and weekly profiles of each zone $z$ depend only on the local demand and + must-run generation in $z$ + - **A has a main diagonal of zeroes** + The hydro storage energy monthly and weekly profiles of each zone $z$ do not depend at all on the local + demand and must-run generation in $z$ +- $L_{z.}^+$ Time-series of "net" load for zone $z$, defined as: $L{z.}^+ = L{z.} - M{z.}$ +- $L_{z.}$ Time-series of "weighted" load for zone $z$, defined as:_ $L_{z.} = A^t L_{z.}^+$ + +All following parameters are related to the generic zone $z$: + +- $\alpha$ "inter-monthly generation breakdown" parameter + +- $\beta$ "inter-daily generation breakdown" parameter + +- $j$ "follow-load" parameter + +- $\mu$ "reservoir-management" parameter + +- $S$ Reservoir size + +- $\overline{S_d}$ Reservoir maximum level at the end of day d, expressed as a fraction of $S$ (rule curve) + +- $\underline{S_d}$ Reservoir minimum level at the end of day d, expressed as a fraction of $S$ (rule curve) + +- $S_0$ Reservoir initial level at the beginning of the first day of the "hydro-year" + +- $I_d$ Natural inflow of energy to the reservoir during day d + +- $I_m$ Natural inflow of energy to the reservoir during month m (sum of $I_d$ + +- $\overline{W_d}$ Maximum energy that can be generated on day d (standard credit) + + All following variables, defined for both stages, are related to the generic zone: + +- $S_d^k$ Reservoir level at the end of day d, at the end of stage k of pre-allocation + +- $S_m^k$ Reservoir level at the end of month m, at the end of stage k of pre-allocation + +- $O_d^k$ Overflow from the reservoir on day d, at the end of stage k of pre-allocation (inflow in excess to an already full reservoir) + +- $W_d^k$ Energy to generate on day d, at the end of stage k of pre-allocation + +- $W_m^k$ Energy to generate on month m, at the end of stage k of pre-allocation + + +Following variables and parameters are local to linear optimization problems $M$ & $D(Tm)$ +solved within the heuristic. For the sake of clarity, the same generic index is used for all time steps, +knowing that in $M$ there are 12 monthly time-steps, while in $D(m)t$ there are from 28 to 31 daily +time-steps. Costs $\gamma_{Var}$ given to these variables are chosen to enforce a logical hierarchy +of penalties (letting the reservoir overflow is worse than violating rule curves, which is worse than deviating +from the generation objective assessed in stage 1, etc.) + +- $Y$ Generation deficit at the end of the period, as compared to the objective aimed at + +- $O_t$ Overflow from the reservoir on time step $t$ + +- $G_t, \overline{G_t}$ Optimal generation and maximum generation on time step $t$ + +- $T_t$ Generation objective assessed in the first stage, for time step t ( $W_m^1$ or $W_d^1$) + +- $S_t, \overline{S_t}, \underline{S_t}$ Optimal stock level, maximum level, minimum level at the end of time step $t$ + +- $I_t$ Natural inflow on time step $t$ + +- $D_t$ Deviation (absolute difference) between target reached and initial aim + +- $\Delta$ Maximum deviation throughout the period + +- $V_t^+$ Amplitude of the violation of the upper rule curve at time step $t$ + +- $V_t^-$ Amplitude of the violation of the lower rule curve at time step $t$ + +- $Y$ Maximum violation of lower rule curve throughout the period + + +**General heuristic for each zone** + +_Begin_ + +$$if (not.\mu) : \{ S \leftarrow \infty ; \underline{S_d} \leftarrow 0; \overline{S_d}; S_0 \leftarrow S/2 \}$$ + +_M1:_ + +$$if (j \text{ and } \mu) : \text{for } m\in [1, 12]: W_m^1 \leftarrow \frac{L_m^{\alpha}.(\sum_{m}{I_m})}{(\sum_{m}{L_m^{\alpha}})}$$ + +$$else: \text{for } m\in [1, 12]: \{W_m^1 \leftarrow I_m\}$$ + + +_M2:_ + +$$\text{for } m\in [1, 12]: W_m^2 \leftarrow \text{Solution of linear problem M}$$ + +_D1:_ + +$$if (j): \text{for } d\in [1, 31]: W_d^1 \leftarrow \frac{L_d^{\beta}. (W_m^2)}{(\sum_{d\in m}{L_d^{\beta}})}$$ + +$$else: \text{for } d\in [1, 31]: W_d^1 \leftarrow \frac{I_d . (W_m^2)} {(\sum_{d\in m}{I_d})}$$ + +_D2:_ + +$$\text{for } m \in [1, 12]: W_{d\in m}^2 \leftarrow \text{Solution of linear problem D(m)}$$ + +_End_ + +Note: In the formulation of the optimal hydro-thermal unit-commitment and dispatch problem (see dedicated document), the reference hydro energy __HIT__ used to set the right hand sides of hydro- constraints depends on the value chosen for the optimization preference "simplex range" and is defined as follows: + +- Daily : for each day **d** of week $\omega$ : $HIT = W_d^2$ +- Weekly : for week $\omega$: $HIT = \sum_{d\in \omega}{W_d^2}$ + +**Optimization problem M** + +$$\min_{G_t, S_t, ...}{\gamma_{\Delta}\Delta + \gamma_Y Y + \sum_{t}{(\gamma_D D_t + \gamma_{V+} V_t^+ + \gamma_{V-} V_t^-)}}$$ + +s.t + +$$S_t \geq 0$$ + +$$S_t \leq S$$ + +$S_t + G_t - S_{t-1} = I_t$ (see note [^monthly_allocation]) + +$$\sum_{t}{G_t} = \sum_{t}{T_t}$$ + +$$G_t - D_t \leq T_t$$ + +$$G_t + D_t \geq T_t$$ + +$$V_t^- + S_t \geq \underline{S_t}$$ + +$$V_t^+ - S_t \geq -\overline{S_t}$$ + +$$Y - V_t^- \geq 0$$ + + +**Optimization problems $D(m)$** + +$$\min_{G_t, S_t, ...}{\gamma_{\Delta}\Delta + \gamma_Y Y + \sum_{t}{(\gamma_D D_t + \gamma_{V-} V_t^- + \gamma_{O} O_t + \gamma_S S_t)}}$$ +s.t + +$$S_t \geq 0$$ + +$$S_t \leq S$$ + +$$G_t \geq 0$$ + +$$G_t \leq \overline{G_t}$$ + +$S_t + G_t + O_t - S_{t-1} = I_t$ (see note [^daily_allocation]) + +$\sum_{t}{G_t + Y} = \sum_{t}{T_t} + Y_{m-1}$ (value of Y previously found in solving **$D(m-1)$**) + +$$G_t - D_t \leq T_t$$ + +$$G_t + D_t \geq T_t$$ + +$$\Delta - D_t \geq 0$$ + +$$V_t^- + S_t \geq \underline{S_t}$$ + +$$Y - V_t^- \geq 0$$ + +[^monthly_allocation]: In the first equation, $S_{t-1}$ is equal to initial stock $S_0$ + +[^daily_allocation]: In the first equation, $S_{t-1}$ is either the initial stock used in M or the final stock of the previous month ($D(m-1)$) diff --git a/docs/user-guide/solver/07-thermal-heuristic.md b/docs/user-guide/solver/07-thermal-heuristic.md new file mode 100644 index 0000000000..372ceb8bed --- /dev/null +++ b/docs/user-guide/solver/07-thermal-heuristic.md @@ -0,0 +1,83 @@ +# Description of the thermal heuristic + +## Introduction + +By default, Antares-Simulator performs a linear resolution of the adequacy problem. This involves a special treatment of the integer variables, which are the number of dispatched units (NODU) for each thermal cluster. + +The purpose of this section is to describe the heuristic treatment of these integer variables in order to allow the linearisation of the weekly optimisation problem. + +Please note that this content is only relevant in case the user chooses a linear resolution of the Antares problem. If the MILP resolution of the adequacy problem is chosen by the user, no heuristic is applied, the problem is solved directly considering integer variables. + +## General presentation of the resolution steps + +The linearised resolution of the weekly adequacy problem[^1] is summarized in the diagram below: + +![Global diagram](img/global_diagram.png){ .add-padding-and-white-bg } + +The general principle of the linear resolution is that two iterations of the weekly optimisation problem will be solved: +- A first resolution in which integer variables are either linearised, or completely removed, depending on the "unit commitment mode" chosen (step 1). +- A second resolution in which the NODU per cluster is fixed, and only the production level of each thermal cluster is set (step 3). + +Between these two steps, a heuristic is used to fix the values of the integer variables which will be used in the second resolution (step 2). + +Finally, a final annual heuristic is applied on the NODUs of the whole year to resolve potential inconsistencies caused by the decoupling of weeks. Economic variables (e.g. OV. COST and OP. COST) are also computed at that stage. + +The way steps 1 and 2 are performed depends on a parameter set by the user in the "Advanced parameters" section, which is the "unit-commitment mode". This parameter can take three values: + +- The "fast" unit-commitment mode uses simplified methods to accelerate the weekly problem solving, while providing a consistent approximated solution. +- The "accurate" unit-commitment mode embeds a more complex approach, which provides solutions which are closer to the optimum, at the cost of longer calculation times. +- The "MILP" commitment mode involves an exact weekly resolution of the weekly problems, at the expense of longer and more variables computation times. If the MILP resolution of the adequacy problem is chosen by the user, no heuristic is applied, the problem is solved directly considering integer variables. This section is therefore not applicable for the MILP mode. + +**IMPORTANT:** As explained in the following parts of this section, the fast mode implies that startup and fixed costs are not considered in the optimisation problem. It should then be discarded in studies involving significant thermal clusters startup and fixed costs. Additionally, the fast mode implies that minimum on and off durations are approximated to be of the same duration (the maximum of the two). + + +## First resolution, integer-determination heuristic, and second resolution (steps 1, 2, 3) + +### Fast mode +#### Step 1: first problem resolution +The general idea of the fast mode is to completely remove the constraints and costs involving integers (the $M_\theta$, $M_\theta^+$ and $M_\theta^-$ variables) in step 1. This means that the first resolution of the weekly problem does not consider constraints (17) to (23) in the [optimisation problem formulation](01-modeling.md). Constraint (16) related to the minimum/maximum output of the thermal cluster is kept. In addition, costs related to integer variables (start-up and hourly fixed costs) are not included in the objective function. + +The first resolution of the problem is then run, and provides hourly power outputs for each thermal cluster $P_{\theta,t}^{optim1}$. At each hour, an initial value of the NODU of each cluster in then calculated: $M_{\theta,t}^{guide}$ = $ceil(\frac{P_{\theta,t}^{optim1}}{\overline{P_{\theta} } }) $. + +#### Step 2: fast mode heuristic +In step 2, for each cluster, a parameter $\Delta_{adjust,\theta} = max(\Delta_\theta^+, \Delta_\theta^-)$ is then calculated, which is the maximum of the minimum on and off durations. Hence, they are approximated to be of the same duration. For each week and each thermal cluster, the week is then divided in intervals of length $\Delta_{adjust,\theta}$. The week is supposed to be cyclic (hour 1 is the timestep followin hour 168), just like in the weekly optimization problem solved by Antares. Within each interval, the NODU of the cluster is increased to the maximum value of $M_{\theta, t}^{guide}$ during this period. This process is run several time by shifting the intervals timestep by timestep until all the possible week splits have been performed. Finally, the solution which minimizes the number of adjustments of the NODU is used as the solution of step 2 $M_{\theta,t}^{heuristic}$. + +![Step 2 of the "fast" thermal mode](img/thermal_heuristic_fast_step_2.png){ .add-padding-and-white-bg } +

    Illustration of step 2 of the fast mode, with $\Delta_{adjust,\theta}$ equal to 2. Here, both solutions are acceptable as they involve 3 NODU adjustments.

    + +#### Step 3: second resolution +Finally, the result of the heuristic $M_{\theta,t}^{heuristic}$ is converted into a lower bound of the power output of each thermal cluster in step 3: $P_{\theta,t}^{min}=\underline{P_\theta}*M_{\theta,t}^{heuristic}$. The second resolution of the problem is then run considering this lower bound, and still excluding integer variables and constraints (17) to (23) of the [optimisation problem formulation](01-modeling.md). In particular, this means that startup and fixed costs are not considered in the formulation of the optimisation problem in any of the two resolutions. However, they are added ex-post and visible in the output variables. + +### Accurate mode + +#### Step 1: first problem resolution +The accurate mode aims at taking into account integer variables in both resolutions of the optimisation problem (steps 1 and 3), but considering them as continuous variables in step 1, and fixing them as parameters in step 3. Contrary to the fast mode, constraints (17) to (23) of the [optimisation problem formulation](01-modeling.md) are taken into account in both resolutions, as well as the start-up and fixed costs in the objective function, but the integer variables $M_\theta$ are considered continuous. + +The first resolution of the problem is then run. As an output, the integer NODU for each thermal cluster is calculed by rounding up the continuous NODUs which are the output of this resolution: $M_{\theta,t}^{guide}=ceil(M_{\theta,t}^{optim1})$. The variables counting the number of units being started-up or shut-down at any time step $M_{\theta,t}^{+}$ and $M_{\theta,t}^{-}$ are also calculated at that stage. + +#### Step 2: accurate mode heuristic +Step 2 of the accurate mode starts by checking for each cluster and for each week whether any constraint of minimum time up or down (constraints (22) and (23) of the [weekly optimisation problem](01-modeling.md)) is violated. If no constraint is violated for a given thermal cluster at a given week, no further action is performed and the output variable of this step $M_{\theta,t}^{heuristic}=M_{\theta,t}^{guide}$. + +For a given cluster and a given week, if any of these constraints is violated, a small optimisation problem is run, which aims at minimizing the changes to the NODU of the cluster while respecting constraints (22) and (23). The output of this optimisation problem is then $M_{\theta,t}^{heuristic}$. + +#### Step 3: second resolution +Finally, the output of step 2 $M_{\theta,t}^{heuristic}$ is converted into a lower bound of the NODU of each thermal cluster for the second resolution: $M_{\theta,t} \geq M_{\theta,t}^{heuristic}$. The second resolution of the problem is then run considering this lower bound, and still including integer variables (as continuous variables) and constraints (17) to (23) of the [optimisation problem formulation](01-modeling.md), and start-up and fixed costs in the objective function. + +## Annual smoothing heuristic (step 4) + +As a final step of the resolution of a Monte-Carlo year, an annual smoothing heuristic is run on the whole year. It addresses two situations: +- Non-optimal stops/starts around week changes +- Failure to take account of fixed and start-up costs in fast mode. + +The general principle of this heuristic is that while respecting the production plan determined at the end of the second resolution and the minimum power output of each unit, we calculate a minimum duration below which it is more economically interesting to leave a group on rather than shutting it down and restarting it at a later stage. This duration is defined as follows: + +$$d=\frac{\sigma_\theta^+}{\tau_\theta}$$ +with $\sigma_\theta^+$ the startup cost of a unit of cluster $\theta$, and ${\tau_\theta}$ the fixed cost of a unit of cluster $\theta$ when it is on. + + +The smoothing heuristic may then choose to increase the NODU in certain clusters when it identifies that a shut-down/start-up sequence lasted shorter than duration d. The new NODU cannot exceed the maximum accepted NODU to respect the production plan, which is equal to $floor(\frac{P_\theta}{\underline{P_\theta}})$. + +![Step 4: smoothing heuristic](img/thermal_smoothing_heuristic.png). + + +[^1]: The formulation of the weekly optimization problem is described in the ["Formulation of the optimisation problems"](01-modeling.md) section. \ No newline at end of file diff --git a/docs/user-guide/solver/08-command-line.md b/docs/user-guide/solver/08-command-line.md new file mode 100644 index 0000000000..0aa433c33c --- /dev/null +++ b/docs/user-guide/solver/08-command-line.md @@ -0,0 +1,57 @@ +--- +hide: + - toc +--- + +# Command-line instructions + +**Executable**: antares-solver + +## Simulation + +| command | usage | +|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------------| +| -i, --input | Study folder | +| --expansion | Force the simulation in [expansion](04-parameters.md#mode) mode | +| --economy | Force the simulation in [economy](04-parameters.md#mode) mode | +| --adequacy | Force the simulation in [adequacy](04-parameters.md#mode) mode | +| --parallel | Enable [parallel](optional-features/multi-threading.md) computation of MC years | +| --force-parallel=VALUE | Override the max number of years computed [simultaneously](optional-features/multi-threading.md) | +| --use-ortools | Use the [OR-Tools](https://developers.google.com/optimization) modelling library (under the hood) | +| --ortools-solver=VALUE | The solver to use (only available if use-ortools is activated). Possible values are: `sirius` (default), `coin`, `xpress`, `scip` | + +## Parameters + +| command | usage | +|:-------------------------|:--------------------------------------------------------------------------------------------------| +| -n, --name=VALUE | Set the name of the new simulation | +| -g, --generators-only | Run the time-series generators only | +| -c, --comment-file=VALUE | Specify the file to copy as comments of the simulation | +| -f, --force | Ignore all warnings at loading | +| --no-output | Do not write the results in the output folder | +| -y, --year=VALUE | Override the [number of MC years](04-parameters.md#nbyears) | +| --year-by-year | Force the [writing the result output for each year](04-parameters.md#year-by-year) (economy only) | +| --derated | Force the [derated](04-parameters.md#derated) mode | +| -z, --zip-output | Write the results into a single zip archive | + +## Optimization + +| command | usage | +|:-------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| --optimization-range | Force the [simplex optimization range](04-parameters.md#simplex-range) ('day' or 'week') | +| --no-constraints | Ignore all binding constraints | +| --no-ts-import | Do not import timeseries into the input folder (this option may be useful for running old studies without upgrade) | +| -m, --mps-export | Export anonymous MPS, weekly or daily optimal UC+dispatch linear | +| -s, --named-mps-problems | Export named MPS, weekly or daily optimal UC+dispatch linear | +| --solver-logs | Print solver logs | +| --solver-parameters | Set solver-specific parameters, for instance `--solver-parameters="THREADS 1 PRESOLVE 1"` for XPRESS or `--solver-parameters="parallel/maxnthreads 1, lp/presolving TRUE"` for SCIP. Syntax is solver-dependent, and only supported for SCIP & XPRESS. | + +## Misc. + +| command | usage | +|:----------------|:-----------------------------------------------------------------| +| --progress | Display the progress of each task | +| -p, --pid=VALUE | Specify the file where to write the process ID | +| --list-solvers | Display a list of LP solvers available through OR-Tools and exit | +| -v, --version | Print the version of the solver and exit | +| -h, --help | Display this help and exit | \ No newline at end of file diff --git a/docs/user-guide/solver/09-appendix.md b/docs/user-guide/solver/09-appendix.md new file mode 100644 index 0000000000..1f8e24673d --- /dev/null +++ b/docs/user-guide/solver/09-appendix.md @@ -0,0 +1,217 @@ +# Appendix + +[//]: # (TODO: the contents of this page may be dispatched in opther pages) + +## Details on the "include-exportmps" parameter +[//]: # (TODO: specify where the MPS files are written) + +This [parameter](04-parameters.md#include-exportmps) does not influence the way calculations are carried out, +nor does it change their results. +The effect of this preference is that, if the parameter is activated, *Antares* will produce and store in the +simulation output folder two files for every linear problem solved in the whole simulation. + +- The first file ("problem" file) contains a standardized description of the mathematical problem solved by *Antares'* + built-in linear solver. The format standard used in this file is known as "MPS". +- The second file ("criterion" file) contains the value of the optimal (minimum) value found for the objective function + of the optimization problem (overall system cost throughout a day or a week). + +All commercial as well as open-source linear solvers are able to process MPS files. As a consequence, tests aiming at +comparing *Antares* solver with other commercial solutions can be easily carried out: all that has to be done is to +submit the MPS problem to the solver at hand and measure its performances (calculation time, criterion value) +with those of *Antares*. + +Note that this kind of comparison brings no information regarding the quality of the physical modelling on which the +simulation is based. It is useful, however, to gather evidence on mathematical grounds. + +File names are structured as follows: +- When the optimization parameter [simplex-range](04-parameters.md#simplex-range) is set on `week`: + Problem-MC year-week number-date-time.mps + Criterion-MC year-week number-date-time.txt +- When the optimization parameter [simplex-range](04-parameters.md#simplex-range) is set on `day`: + Problem-MC year-week number-date-time-day number.mps + Criterion-MC year-week number-date-time-day number.txt + + +[//]: # (TODO: add link to "two successive optimization problems" doc) +Besides, each economic problem generally needs to be solved through two successive optimization problems. +Files related to these two problems will bear almost the same name, the only difference being the "time" suffix. +The files related to the second optimization (final *Antares* results) are those that bear the latest tag. + +Finally, in some rare cases where the problems to solve are small and fast, the files attached to the two optimization +rounds may begin to be printed within the same second. In these cases, an additional suffix is added before the mps or +txt extension. + +> _**Note:**_ The extra runtime and disk space resulting from the activation of the "mps" option may be quite significant. +> This option should therefore be used only when a comparison of results with those of other solvers is actually intended. + +## Details on the "include-unfeasible-problem-behavior" parameter + +This [parameter](04-parameters.md#include-unfeasible-problem-behavior) can take one of the four values: +`ERROR_DRY`, `ERROR_MPS`, `WARNING_DRY`, `WARNING_MPS` + +If `ERROR_DRY` or `ERROR_MPS` is selected, the simulation will stop right after encountering the first mathematically +unfeasible optimization (daily or weekly) problem. No output will be produced beyond this point. +Should the dataset contain several unfeasible problems (i.e. regarding different weeks of different MC years), +it is possible that successive runs of the same simulation stop at different points (if parallel computation is used, +the triggering problem may differ from one run to the other). + +If `WARNING_DRY` or `WARNING_MPS` is selected, the simulation will skip all mathematically unfeasible optimization +(daily or weekly) problems encountered, fill out all results regarding these problems with zeroes and then resume the +simulation. The hydro reservoir levels used for resuming the simulation are those reached at the end of the last successful week. + +With `..._DRY` options, no specific data is printed regarding the faulty problem(s). +With `..._MPS` options, the full expression of the faulty problem(s) is printed in the standard "MPS" format, +thus allowing further analysis of the infeasibility issue. + + +## Details on the "initial-reservoir-levels" parameter (DEPRECATED since 9.2) + +### version 9.2: The reservoir level is now always determined with cold start behavior. + +This parameter can take the two values "cold start" or "hot start". [default: cold start]. Simulations results may in some circumstances be heavily impacted by this setting, hence proper attention should be paid to its meaning before considering changing the default value. + +**General:** + +This parameter is meant to define the initial reservoir levels that should be used, in each system area, when processing +data related to the hydropower storage resources to consider in each specific Monte-Carlo year. + +As a consequence, Areas which fall in either of the two following categories are not impacted by the value of the parameter: +- No hydro-storage capability installed +- Hydro-storage capability installed, but the "reservoir management" option is set to "False" + +Areas that have some hydro-storage capability installed and for which explicit reservoir management is required are concerned by the parameter. The developments that follow concern only this category of Areas. + +**Cold Start:** + +On starting the simulation of a new Monte-Carlo year, the reservoir level to consider in each Area on the first day of +the initialization month is randomly drawn between the extreme levels defined for the Area on that day. + +More precisely: + +- The value is drawn according to the probability distribution function of a "Beta" random variable, whose four internal parameters are set so as to adopt the following behavior: + Lower bound: Minimum reservoir level. + Upper bound: Maximum reservoir level + Expectation: Average reservoir level + Standard Deviation: (1/3) (Upper bound-Lower bound) + +- The random number generator used for that purpose works with a dedicated seed that ensures that results can be reproduced + [^17] from one run to another, regardless of the simulation runtime mode (sequential or parallel) + and regardless of the number of Monte-Carlo years to be simulated [^18]. + +**Hot Start:** + +On starting the simulation of a new Monte-Carlo year, the reservoir level to consider in each Area on the first day of the initialization month is set to the value reached at the end of the previous simulated year, if three conditions are met: + +- The simulation calendar is defined throughout the whole year, and the simulation starts on the day chosen for initializing the reservoir levels of all Areas. + +- The Monte-Carlo year considered is not the first to simulate, or does not belong to the first batch of years to be simulated in parallel. In sequential runtime mode, that means that year #N may start with the level reached at the end of year #(N-1). In parallel runtime mode, if the simulation is carried out with batches of B years over as many CPU cores, years of the k-th batch + [^19] may start with the ending levels of the years processed in the (k-1)-th batch. + +- The parallelization context (see [Multi-threading](optional-features/multi-threading.md)) must be set to ensure that the M Monte-Carlo years to simulate will be processed in a round number of K consecutive batches of B years in parallel (i.e. M = K\*B and all time-series refresh intervals are exact multiple of B). + +The first year of the simulation, and more generally years belonging to the first simulation batch in parallel mode, are initialized as they would be in the cold start option. + +**Note that:** + +- _Depending on the hydro management options used, the amount of hydro-storage energy generated throughout the year may either match closely the overall amount of natural inflows of the same year, or differ to a lesser or greater extent. In the case of a close match, the ending reservoir level will be similar to the starting level. If the energy generated exceeds the inflows (either natural or pumped), the ending level will be lower than the starting level (and conversely, be higher if generation does not reach the inflow credit). Using the "hot start" option allows to take this phenomenon into account in a very realistic fashion, since the consequences of hydro decisions taken at any time have a decisive influence on the system's long term future._ + +- _When using the reservoir level "hot start" option, comparisons between different simulations make sense only if they rely on the exact same options, i.e. either sequential mode or parallel mode over the same number of CPU cores._ + +- _More generally, it has to be pointed out that the "hydro-storage" model implemented in Antares can be used to model "storable" resources quite different from actual hydro reserves: batteries, gas subterraneous stocks, etc._ + +## Details on the "hydro-heuristic-policy" parameter +[//]: # (TODO: update this paragraph) +_**This section is under construction**_ + +This parameter can take the two values "Accommodate rule curves" or "Maximize generation". [default: Accommodate rule curves]. + +**General:** + +This parameter is meant to define how the reservoir level should be managed throughout the year, either with emphasis put on the respect of rule curves or on the maximization of the use of natural inflows. + +**Accommodate rule curves:** + +Upper and lower rule curves are accommodated in both monthly and daily heuristic stages (described page 58). In the second stage, violations of the lower rule curve are avoided as much as possible (penalty cost on $\Psi$. higher than penalty cost on Y). This policy may result in a restriction of the overall yearly energy generated from the natural inflows. + +**Maximize generation:** + +Upper and lower rule curves are accommodated in both monthly and daily heuristic stages (described page 58). In the second stage, incomplete use of natural inflows is avoided as much as possible (penalty cost on Y higher than penalty cost on $\Psi$). This policy may result in violations of the lower rule curve. + +## Details on the "hydro-pricing-mode" parameter +[//]: # (TODO: update this paragraph) +_**This section is under construction**_ + +This parameter can take the two values "fast" or "accurate". [default: fast]. + +Simulations carried out in "accurate" mode yield results that are theoretically optimal as far as the techno-economic modelling of hydro (or equivalent) energy reserves is concerned. It may, however, require noticeably longer computation time than the simpler "fast" mode. + +Simulations carried out in "fast" mode are less demanding in computer resources. From a qualitative standpoint, they are expected to lead to somewhat more intensive (less cautious) use of stored energy. + +**General:** + +This parameter is meant to define how the reservoir level difference between the beginning and the end of an optimization week should be reflected in the hydro economic signal (water value) used in the computation of optimal hourly generated /pumped power during this week. + +**Fast:** + +The water value is taken to remain about the same throughout the week, and a constant value equal to that found at the date and for the level at which the week_ **begins** _is used in the course of the optimization. A value interpolated from the reference table for the exact level reached at each time step within the week is used ex-post in the assessment of the variable "H.COST" (positive for generation, negative for pumping) defined in [Output Files](03-outputs.md). This option should be reserved to simulations in which computation resources are an issue or to simulations in which level-dependent water value variations throughout a week are known to be small. + +**Accurate:** + +The water value is considered as variable throughout the week. As a consequence, a different cost is used for each "layer" of the stock from/to which energy can be withdrawn/injected, in an internal hydro merit-order involving the 100 tabulated water-values found at the date at which the week **ends**. A value interpolated from the reference table for the exact level reached at each time step within the week is used ex-post in the assessment of the variable "H.COST" (positive for generation, negative for pumping) defined in [Output Files](03-outputs.md). This option should be used if computation resources are not an issue and if level-dependent water value variations throughout a week must be accounted for. + +## Details on the "unit-commitment-mode" parameter +[//]: # (TODO: update this paragraph) +_**This section is under construction**_ + +This parameter can take the two values "fast" or "accurate". [default: fast]. + +Simulations carried out in "accurate" mode yield results that are expected to be close to the theoretical optimum as far as the techno-economic modelling of thermal units is concerned. They may, however, require much longer computation time than the simpler "fast" mode. + +Simulations carried out in "fast" mode are less demanding in computer resources. From a qualitative standpoint, they are expected to lead to a more costly use of thermal energy. This potential bias is partly due to the fact that in this mode, start-up costs do not participate as such to the optimization process but are simply added ex post. + +**General:** + +In its native form [^20], the weekly optimization problem belongs to the MILP (Mixed Integer Linear Program) class. The Integer variables reflect, for each time step, the operational status (running or not) of each thermal unit. Besides, the amount of power generated from each unit can be described as a so-called semi-continuous variable (its value is either 0 or some point within the interval [Pmin , Pmax]). Finally, the periods during which each unit is either generating or not cannot be shorter than minimal (on- and off-) thresholds depending on its technology. + +The Unit Commitment mode parameter defines two different ways to address the issue of the mathematical resolution of this problem. In both cases, two successive so-called "relaxed" LP global optimizations are carried out. In-between those two LPs, a number of local IP (unit commitment of each thermal cluster) are carried out. + +Besides, dynamic thermal constraints (minimum on- and off- time durations) are formulated on time-indices rolling over the week; this simplification brings the ability to run a simulation over a short period of time, such as one single week extracted from a whole year, while avoiding the downside (data management complexity, increased runtime) of a standard implementation based on longer simulations tiled over each other (illustration below). + +![Standard_Implementation](img/Standard_Implementation.png) + +![Antares_Implementation](img/Antares_Implementation.png) + +**Fast:** + +In the first optimization stage, integrity constraints are removed from the problem and replaced by simpler continuous constraints. + +For each thermal cluster, the intermediate IP looks simply for an efficient unit-commitment compatible with the operational status obtained in the first stage, with the additional condition (more stringent than what is actually required) that on- and off- periods should be exact multiple of the higher of the two thresholds specified in the dataset. + +In the second optimization stage, the unit commitment set by the intermediate IPs is considered as a context to use in a new comprehensive optimal hydro-thermal schedule assessment. The amount of day-ahead (spinning) reserve, if any, is added to the demand considered in the first stage and subtracted in the second stage. Start-up costs as well as No-Load Heat costs are assessed in accordance with the unit-commitment determined in the first stage and are added ex post. + +**Accurate:** + +In the first optimization stage, integrity constraints are properly relaxed. Integer variables describing the start-up process of each unit are given relevant start-up costs, and variables attached to running units are given No-Load Heat costs (if any), regardless of their generation output level. Fuel costs / Market bids are attached to variables representing the generation output levels. + +For each thermal cluster, the intermediate IP looks for a unit-commitment compatible with the integrity constraints in the immediate neighborhood of the relaxed solution obtained in the first stage. In this process, the dynamic thresholds (min on-time, min off-time) are set to their exact values, without any additional constraint. + +In the second optimization stage, the unit commitment set by the intermediate IP is considered as a context to use in a new comprehensive optimal hydro-thermal schedule assessment. The amount of day-ahead (spinning) reserve, if any, is added to the demand considered in the first stage and subtracted in the second stage. + +## Details on the "renewable-generation-modelling" parameter +[//]: # (TODO: update this paragraph) +_**This section is under construction**_ + +This parameter can take the two values “aggregated†or “clusterâ€. For a new study, it will default to cluster. For a legacy (Antares version <8.1.0) study it will default to aggregated. + +If the parameter is set to “aggregatedâ€, the user will have access to the Wind & Solar windows, but not the Renewable window. When the parameter is set to “clusterâ€, the Renewable window will be available, but not the Wind nor the Solar windows. The data stored in the windows that are not available will always be conserved. However, only Renewable data (and not the wind and solar data) will be considered for the calculations when the parameter is set to “clusterâ€. And only the wind and solar data (and not the renewable data) will be considered for the calculations when the parameter is set to “aggregatedâ€. + +The Renewable window can be filled out with the different renewable clusters inside each node. Each renewable cluster needs to have a group specified or will default to the «Other RES 1» group. Production Timeseries can be filled out much like the Thermal production ones. Note that unlike thermal clusters, negative production values are allowed. The Renewable window is described in more details in the “4. Active Windows†section. In the Simulation window, only “Ready-made†timeseries can be selected for renewables for now. This should be modified in a future release. The MC scenario builder for Renewables works the same way as for Thermal Clusters. + +[^17]: As long as the System's list of Areas does not change + +[^18]:E.g. : if three playlists A,B,C are defined over 1000 years (A: years 1 to 1000, B: years 1 to 100, C: Years 13,42,57,112), initial reservoir levels in each Area are identical in the playlists' intersection (years 13,42,57) + +[^19]: If the playlist is full, these years have numbers # (k-1)B+1 ,…., #kB + +[^20]: Described in the note "Optimization Problems Formulation" + diff --git a/docs/reference-guide/Antares_Implementation.png b/docs/user-guide/solver/img/Antares_Implementation.png similarity index 100% rename from docs/reference-guide/Antares_Implementation.png rename to docs/user-guide/solver/img/Antares_Implementation.png diff --git a/docs/reference-guide/Antares_Process.png b/docs/user-guide/solver/img/Antares_Process.png similarity index 100% rename from docs/reference-guide/Antares_Process.png rename to docs/user-guide/solver/img/Antares_Process.png diff --git a/docs/user-guide/solver/img/Random_Parameters.png b/docs/user-guide/solver/img/Random_Parameters.png new file mode 100644 index 0000000000..d3dade2078 Binary files /dev/null and b/docs/user-guide/solver/img/Random_Parameters.png differ diff --git a/docs/reference-guide/Standard_Implementation.png b/docs/user-guide/solver/img/Standard_Implementation.png similarity index 100% rename from docs/reference-guide/Standard_Implementation.png rename to docs/user-guide/solver/img/Standard_Implementation.png diff --git a/docs/user-guide/solver/img/global_diagram.png b/docs/user-guide/solver/img/global_diagram.png new file mode 100644 index 0000000000..d06737abd2 Binary files /dev/null and b/docs/user-guide/solver/img/global_diagram.png differ diff --git a/docs/user-guide/solver/img/thermal_heuristic_fast_step_2.png b/docs/user-guide/solver/img/thermal_heuristic_fast_step_2.png new file mode 100644 index 0000000000..1d023cc9a5 Binary files /dev/null and b/docs/user-guide/solver/img/thermal_heuristic_fast_step_2.png differ diff --git a/docs/user-guide/solver/img/thermal_smoothing_heuristic.png b/docs/user-guide/solver/img/thermal_smoothing_heuristic.png new file mode 100644 index 0000000000..beb8b85d22 Binary files /dev/null and b/docs/user-guide/solver/img/thermal_smoothing_heuristic.png differ diff --git a/docs/user-guide/solver/optional-features/00-index.md b/docs/user-guide/solver/optional-features/00-index.md new file mode 100644 index 0000000000..ff5deced5b --- /dev/null +++ b/docs/user-guide/solver/optional-features/00-index.md @@ -0,0 +1,9 @@ +[//]: # (Index used by Sphinx to generate correct PDF tree) +# Optional features + +```{toctree} +:hidden: +multi-threading.md +adequacy-patch.md +xpress.md +``` \ No newline at end of file diff --git a/docs/reference-guide/Reduced_Allowance.png b/docs/user-guide/solver/optional-features/Reduced_Allowance.png similarity index 100% rename from docs/reference-guide/Reduced_Allowance.png rename to docs/user-guide/solver/optional-features/Reduced_Allowance.png diff --git a/docs/user-guide/solver/optional-features/adequacy-patch.md b/docs/user-guide/solver/optional-features/adequacy-patch.md new file mode 100644 index 0000000000..b92a07a8eb --- /dev/null +++ b/docs/user-guide/solver/optional-features/adequacy-patch.md @@ -0,0 +1,241 @@ +# Adequacy Patch calculation +(available since v8.3.0) + +[//]: # (TODO: update this page if needed) +_**This section is under construction**_ + +## Foreword + +The operational algorithm of Euphémia market coupling implements "de-optimization" rules in order to fix the sharing of "Energy Not Served" (ENS) between the market areas when there is any (in a way to ensure a certain fairness in the sharing of this ENS): this is what we call the adequacy patch. +The requirement of fairness rules in the sharing of ENS within Antares studies increased with the introduction of flow-based modelling. Previously, this problem was mainly solved with the hurdle cost mechanism (small costs on interconnections) limiting exports from areas where ENS was encountered. However, implicit rules in Antares for sharing ENS, even outside the Flow-Based domain, are not fully satisfactory, even with hurdle costs, because they prioritize the treatment of ENS in countries directly connected to countries with margins, to the detriment of more distant countries. In a context of decommissioning of coal and nuclear plants in France and in Europe, cases of simultaneous ENS over the domain will increase. Consequently, the need of adequacy patch to share fairly this ENS is arising. + +It should be noted that, in the current implementation of the patch within Antares, the implementation covers only one of the three main features of the ‘curtailment sharing and minimization’ principles in EUPHEMIA, namely: + +1. Local matching constraint. + +2. Secondary problem of sharing of curtailment by the quadratic term. + +3. The implemented solution does not yet consider the feature in EUPHEMIA, related to ‘minimization of curtailment’ in the primal problem which includes an extra penalty term directly in the global objective function in EUPHEMIA by multiplying the maximum curtailment ratio with a large M pre-factor in the total welfare. + +## Local matching rule (Antares Simulator 8.3) + +The rule implemented is called the « Local Matching » rule: + +- This rule consists in satisfying **ENS $\leq$ DENS** (Domestic Energy not Served) for all physical areas inside the adequacy patch. +- It specifies that an area cannot export more than its local margin. + +This means that an area which can serve local demand with local generation, should never have ENS. + +_**Notes**_ + +- _The local matching rule is only part of the economic mode of Antares (Not the Adequacy mode);_ +- _DENS outputs of Antares, for all selected areas, are available in the General values tab, as year-by-year and synthetic results. All the statistic values for it are calculated as well (min, max, mean, standard deviation). For the areas not part of the patch, the output DENS is set to 0._ + +### Specifications of the evolution concerning the optimization problem + +To calculate the DENS used to constrain the ENS variations of each area, a first iteration is performed. During this first iteration, the usual optimization problem is slightly modified before being solved. The objective of this first iteration is to get an ENS of each area which will represent its DENS. In order to achieve this, links between areas are forced to have a capacity of 0. To ensure that customizable models will still work using this new feature, different categories are created for the areas, enabling different behaviours as needed. The different categories are: + +- "virtual": The area is a virtual area, +- "physical outside": The area is a physical area not included in the adequacy patch domain, +- "physical inside": The area is a physical area included in the adequacy patch domain. + +In case Flow-Based is represented in the study, the "hub" node introduced for the Flow-based modelling should also be included in the list of physical areas (this one should be declared by the user in its list of physical nodes). + +#### First iteration + +In the first iteration, the following link capacities in the following direction will be set to 0 MW: + +- node "physical inside" <-> node "physical inside" +- node "physical inside" -> node "physical outside" +- node "physical outside" -> node "physical inside": optional/user defined (default `true`), +- node "physical outside" <-> node "physical outside": optional/user defined (default `true`). + +Once the first iteration is completed, we have access to the DENS value, which represents the ability of an area to fulfil its local load thanks to its local production capacities: +- DENS = ENS for each physical area inside the adequacy patch perimeter + +#### Second iteration + +During the second iteration, all link capacities between physical nodes are set to the values provided as input data (as it is done in the current Antares version). The only change compared to a simulation without the adequacy patch is that the upper bound of the ENS on the areas included in the patch is now constrained by the DENS found during the first iteration. This is introduced in the optimization problem for physical areas that are declared in the adequacy patch domain (areas declared as "physical inside"): + +- ENS $\leq$ DENS + (for all physical areas inside the adequacy patch). + +## Curtailment sharing rule (Antares Simulator 8.5) + +The second implemented rule is called the « Curtailment Sharing » rule (henceforth CSR). + +The idea is that when countries on the network have positive DENS, they should have relatively similar levels of unsupplied energy (as the name suggests, so that the curtailment is shared). The quantity that is to be measured and compared across countries is: ENS/PTO where PTO is the Price Taking Orders. There are different options of defining the PTOs. In this development we will consider two: + +- PTOs are the DENS of the country +- PTOs are the Load of the country + +The considered countries are only nodes "2" (areas defined as physical areas inside the adequacy patch), the problem to be solved is an hourly problem. Precisely, the hourly problem to be solved concerns only hours for which of the sum of the ENS in all nodes "2" is exceeding a user-defined threshold. If it is not the case, all the treatments described below should be ignored for this hour and the algorithm should then consider the next hour. So, at that step, we will solve the CSR quadratic optimization problem on a reduced domain, limited to nodes "2" and the links that exist between these nodes 2. + +_**Notes**_ + +- _Local matching and curtailment sharing rule are only part of the economic mode of Antares (Not the Adequacy mode);_ + +_**Convention**_: + +- _A is any node of type "2" in the network, an area that is defined as a physical area inside the adequacy patch. Each variable/parameter/constraint applied on A is implicitly applied to any node of type "2";_ +- _B represents any node of type "2" linked to A;_ +- _A is alphabetically before B, therefore their link in Antares would be called A/B. Furthermore, regarding the flow on this link (variable that contains the algebraic value of the power flow between the 2 nodes to be optimized):_ + - _if the flow value is positive, the power flow goes from node A to node B, it is an export for node A and an import for node B;_ + - _if the flow value is negative, the power flow goes from node B to node A, it is an import for node A and an export for node B._ + +### Variable definitions + +- Flows over links variables (3 set of variables: "Flow", "Flow_direct" and "Flow_indirect"): +Inside the optimization problem, the "flow" variable is actually split in 2 positive variables for the resolution. It is required in order to write some constraints. We define the 2 positive variables, "Flow_direct" and "Flow_indirect" with this simple relation: +Flow = Flow_direct – Flow_indirect + +- "net_position" variable: +"net_position (node A)" is the balance between node A and all other nodes "2" connected to node A. + +- "ENS" variable: +"ENS (node A)" contains the ENS to be optimized for that node. + +- "Spillage" variable: +"Spillage (node A)" contains the Spillage to be optimized for that node. + +### Parameter definitions + +- "net_position_init" parameter: +The "net_position_init (node A)" parameter value is the value of the "net_position" calculated from the output of the Antares calculation for node A, considering results we get from the Antares calculation at the end of Local matching rule optimization. + +- "ENS_init" parameter: +The "ENS_init (node A)" parameter value is the value of the "ENS" obtained from the output of the Antares calculation for node A at the end of Local matching rule optimization. + +- "DENS_new" parameter: The "DENS_new (node A)" parameter value is an update of the value of the "DENS" parameter which takes into account the result of Antares calculation (therefore different from the one estimated in Local matching rule optimization). + +- "Spillage_init" parameter: +The "Spillage_init (node A)" parameter value is the value of the "Spillage" obtained from the output of the Antares calculation for node A at the end of Local matching rule optimization. + +- "Hurdle cost" parameter on links: +This parameter, fixed on links, is kept from the Antares optimization problem. +Like "flows" we can split "Hurdle cost" in "Hurdle_cost_direct" and "Hurdle_cost_indirect" + +### Constraints and relations between variables + +- **Constraints on "Flows", "Flow_direct" and "Flow_indirect" variables:** +These variables should have exactly the same constraints as the ones considered in the Antares problem: + + - NTC constrains (independent lower and upper bounds for each link). + - Flowbased binding constraints to be extracted from the hourly binding constraint list. + +- **Relation between "Flows" over links and "net_position" on nodes:** +The value of "net_position (node A)" is deduced from "flow" variable as follows: + + - net_position (node A) = $\sum$ algebraic "Flows" over links involving node A + Remember that: + + - a "Flow" that goes from another node "2" to node A is an import for node A and should be counted positively + - a "Flow" that goes from node A to another node "2" is an export for node A and should be counted negatively. + +- **The detailed formulation for calculating the value of "net_position (node A)" is, for all "nodes 2 upstream" and all "nodes 2 downstream":** + - net_position (node A) = $\sum$ flow_direct (node 2 upstream -> node A) + $\sum$ flow_indirect (node A <- node 2 downstream) - $\sum$ flow_indirect (node 2 upstream <- node A) - $\sum$ flow_direct (node A -> node 2 downstream) + + Considering that: + + - "Node 2 upstream" is any node "2" which name in alphabetic order is before node A + - "Node 2 downstream" is any node "2" which name in alphabetic order is after node A + +- **Formula for calculating DENS_new parameter:** + - DENS_new (node A) = max [ 0; ENS_init (node A) + net_position_init (node A) - DTG.MRG (node A)] + + Depending on the parameter in the GUI that includes or not possible imports from nodes "1" to nodes "2" in the DENS calculation, we should modify this formula. Precisely, it is when "NTC from physical areas outside to physical areas inside adequacy patch" is set to null then the formulation such be modified as follows: + + - DENS_new (node A) = max [ 0; ENS_init (node A) + net_position_init (node A) + $\sum$ flows (node 1 -> node A) - DTG.MRG (node A)] + + The detailed formulation for calculating the last term is, for all "nodes 1 upstream" and all "nodes 1 downstream": + + - $\sum$ flows (node 1 -> node A) = $\sum$ flow_direct (node 1 upstream -> node A) + $\sum$ flow_indirect (node A <- node 1 downstream) + + Considering that: + - "Node 1 upstream" is any node "1" which name in alphabetic order is before node A + - "Node 1 downstream" is any node "1" which name in alphabetic order is after node A + + The consideration of a correct DENS_new as presented above should ensure that the Local Matching Approach is respected, (node A) can’t be "Exporting" and having ENS after CSR. + +- **Relation induced by node balancing conservation:** + - ENS (node A) + net_position (node A) – spillage (node A) = ENS_init (node A) + net_position_init (node A) – spillage_init (node A) + + Actually, this simplified formulation takes into account that these variables are the only ones we are allowed to update by this optimization (power generation for all nodes and power flows between other nodes than nodes "2" will not be modified). + +- **Constraint induced by Local matching rule:** + + - ENS (node A) $\leq DENS_{new}(node~A)$ + +- **Positivity constraints:** + + - ENS (node A) $\geq$ 0 + - spillage (node A) $\geq$ 0 + +_**Notes**_ + +- _"Spillage" variable and "Spillage_init" parameter have been introduced only to deal with some situations for which "Flowbased" constraints, combining with adequacy patch rules, lead to an increase of Total ENS over the different nodes "2". Such increase of Total ENS could happen for 2 reasons:_ + + - _We have new violations of Local Matching rule and the optimal solution found by Antares is no longer a valid solution, regards to this rule;_ + - _The curtailment sharing rule target is to minimize $\sum$(ENS$^2$/PTO) and such objective is not exactly equivalent than minimizing Total ENS._ + + _As a matter of fact, if we sum over all nodes "2" the relation induced by node balancing conservation, as the sum of all "net_position" is null, it leads to:_ + + - _Total ENS – Total Spillage = Total ENS_init – Total Spillage_init, over all nodes "2"_ + + _So, an increase of Total ENS will necessarily lead to the same increase of Total Spillage._ + +- _Spillage results after curtailment sharing rule quadratic optimization are presented in the separate column inside Antares output, titled "SPIL. ENRG. CSR" so the user has access to the spillage results both prior to and after CSR optimization._ +- _In order to avoid solver issues, lower and upper boundaries of the ENS and Spillage variables can be relaxed using GUI option "Relax CSR variable boundaries". Following relaxations can be imposed:_ + - $-10^{-m} \leq ENS(node~A) \leq DENS_{new} (node~A) + 10^{-m}$ + - $-10^{-m} \leq spillage(node~A) \leq + \infty$ + + Where $m$ is an integer defined by the user. + +### Objective function + +- Minimize $\left[ \sum\frac{ENS^2}{PTO} + \sum \frac{1}{M} \left( hurdle cost direct \times flow direct \right) + \sum \frac{1}{M} \left( hurdle cost indirect \times flow_ indirect \right) \right]$ + +The 2 latest terms are introduced to minimize loop flows in the considering domain, and $M$ is the highest curtailment cost between a link's origin and destination nodes, used to adapt the scale of hurdle costs to this new objective (in practice, those tend to be the same for all nodes, typically 3000€/MW or 10000€/MW). +In order to assess the quality of the CSR solution additional verification can be imposed by activating GUI option "Check CSR cost function value prior and after CSR optimization". Values of the objective function prior to and after quadratic optimization will be calculated and compared. If the objective function value after the quadratic optimization has decreased, the new CSR solution will be accepted and presented in the Antares output. However, if after quadratic optimization the objective function value has increased (or stayed the same), LMR solution will be adopted as the final one and warning will be logged out with the appropriate information (year, hour cost prior to quad optimization, cost after quadratic optimization). + +- $QUAD 0 = \left[ \sum \frac{ENS init^2}{PTO} + \sum \frac{1}{M} \left( hurdle cost direct \times flow direct init \right) + \sum \frac{1}{M} \left( hurdle cost indirect \times flow indirect init \right) \right]$ +- $QUAD 1 = \left[ \sum \frac{ENS final^2}{PTO} + \sum \frac{1}{M} \left( hurdle cost direct \times flow direct final \right) + \sum \frac{1}{M} \left( hurdle cost indirect \times flow indirect final \right) \right]$ + +If: + +- $QUAD 0 \leq QUAD 1$ +(CSR does not improve QUAD) then the "_init" solution is kept and the CSR solution is hence disregarded. +- $QUAD 0 > QUAD 1$ +(CSR does improve QUAD) then the "CSR" solution is kept as final result updating the "_init" solution as stated above. + +### Post-optimization process + +For the CSR triggered hours, if after quadratic optimization, area inside adequacy patch still experiences unsupplied energy: + +- ENS (node A) > 0 + +following adjustments will be performed. Available dispatchable margin "DTG MRG" will be used to compensate for the residual unsupplied energy ENS: + +- ENS (node A) = max[0.0, ENS (node A) - DTG.MRG (node A)] + +Remaining dispatchable margin after above-described post-optimisation calculation is stored inside new column "DTG MRG CSR" + +- DTG.MRG.CSR (node A) = max[0.0, DTG.MRG (node A) - ENS (node A)] + +Note that for all the hours for which curtailment sharing rule was not triggered, as well as for the hours for which curtailment sharing rule was triggered but after quadratic optimization ENS (node A) is equal to zero, DTG.MRG.CSR (node A) will be equal to DTG.MRG (node A). For the curtailment sharing rule triggered hours, if after quadratic optimization and above-described post calculation process, area inside adequacy patch still experiences unsupplied energy, marginal price "MRG.PRICE" will be aligned with the price cap in the model (set to Unsupplied Energy Cost in the results). + +- MRG.PRICE (node A) = Unsupplied Energy Cost (node A) + +_**Notes**_ + +- _SPIL. ENRG. CSR and DTG MRG CSR outputs of Antares, for all selected areas, are available in the General values tab, as year-by-year and synthetic results. All the statistic values for it are calculated as well (min, max, mean, standard deviation). For the areas not part of the patch, the default output is set to 0._ +- _LMR VIOL. outputs of Antares, for all selected areas, are available in the General values tab, as year-by-year and synthetic results. For the areas not part of the patch, the default output is set to 0. +LMR violation check is performed for all hours (CSR triggered or not) after LMR linear optimization (prior to CSR quadratic optimization). Hourly value of LMR violation is set to value one if all following conditions are met:_ + + - _ENS_init (node A) > 0;_ + - _net_position_init (node A) + $\sum$ flows (node 1 -> node A) < 0;_ + - _Abs[net_position_init (node A) + $\sum$ flows (node 1 -> node A)] > ENS_init (node A) + GUI_defined_threshold._ + + _Second equation is satisfied if the area is exporting power. Depending on the GUI option member ($\sum$ flows (node 1 -> node A)) is optional._ + + diff --git a/docs/user-guide/solver/optional-features/multi-threading.md b/docs/user-guide/solver/optional-features/multi-threading.md new file mode 100644 index 0000000000..c2c13bee46 --- /dev/null +++ b/docs/user-guide/solver/optional-features/multi-threading.md @@ -0,0 +1,62 @@ +--- +hide: + - toc +--- + +# Multi-threading + +[//]: # (TODO: update this page if needed) +_**This section is under construction**_ + +Multi-threading is also available on the proper calculation side, on a user-defined basis. + +Provided that hardware resources are large enough, this mode may reduce significantly the overall runtime of heavy simulations. + +To benefit from multi-threading, the simulation must be run in the following context: + +- The [parallel](../08-command-line.md#simulation) option must be enabled (it is disabled by default) +- The simulation [mode](../04-parameters.md#mode) must be either `Adequacy` or `Economy` + +When the "parallel" solver option is used, each Monte-Carlo year is dispatched in an individual process on the available CPU cores. +The number of such individual processes depends on the characteristics of the local hardware and on the value given to +the study-dependent [number-of-cores-mode](../04-parameters.md#number-of-cores-mode) advanced parameter. +This parameter can take five different values (Minimum, Low, Medium, High, Maximum). +The number of independent processes resulting from the combination (local hardware + study settings) is given in the +following table, which shows the CPU allowances granted in the different configurations. + +| _Available CPU Cores_ | _Minimum_ | _Low_ | _Medium_ | _Large_ | _Maximum_ | +|:---------------------:|:---------:|:---------:|:---------:|:----------:|:---------:| +| _1_ | 1 | 1 | 1 | 1 | 1 | +| _2_ | 1 | 1 | 1 | 2 | 2 | +| _3_ | 1 | 2 | 2 | 2 | 3 | +| _4_ | 1 | 2 | 2 | 3 | 4 | +| _5_ | 1 | 2 | 3 | 4 | 5 | +| _6_ | 1 | 2 | 3 | 4 | 6 | +| _7_ | 1 | 2 | 3 | 5 | 7 | +| _8_ | 1 | 2 | 4 | 6 | 8 | +| _9_ | 1 | 3 | 5 | 7 | 8 | +| _10_ | 1 | 3 | 5 | 8 | 9 | +| _11_ | 1 | 3 | 6 | 8 | 10 | +| _12_ | 1 | 3 | 6 | 9 | 11 | +| _S > 12_ | 1 | Ceil(S/4) | Ceil(S/2) | Ceil(3S/4) | S-1 | + +**Note**: The number of independent threads actually launched by Antares in parallel mode may appear smaller than that shown in the table above. In this case, the resources monitor menu and the dashboard displayed on starting the simulation indicates: + +simulation cores: **nn** reduced to **pp** + +**nn** is the regular allowance and **pp** is the practical value that the solver has to work with. Allowance reduction may occur if the built-in Time-Series generators are activated, their "refresh" status is set to "Yes" and the values given to the "refresh span" parameters are not appropriate (parallel execution demand that refresh operations do not take place within a bundle of parallel years). Optimal use of the "parallel" execution mode is obtained when all activated built-in time –series generators are set up in either of the two following ways: +- Refresh status : **No** +- Refresh status : **Yes**, refresh span = **Ki \* (CPU allowance)** , with **Ki >= 1** + +Examples of reduction from an initial allowance of 12 cores are given hereafter. The reduced allowance is the size of the **smallest** bundle of parallel years between two consecutive "refresh" (it indicates the slowest point of the simulation [^23]). Note that RAM requirements displayed in the resources monitor are, contrariwise, assessed on the basis on the **largest** bundle of parallel years encountered in the simulation). + +![Reduced_Allowance](Reduced_Allowance.png) + +The Table indicates either the refresh status (No) or the refresh span (the associated refresh status "yes" is implicit). + + + +[^23]: When the number of MC years to run is smaller than the allowance, the parallel run includes all of these years in a single bundle and there is no "reduced allowance" message + +[^24]: +The smallest bundle in this case is the ninth (year number 97 to year number 100).The first 8 bundles involve 12 MC years each. diff --git a/docs/user-guide/solver/optional-features/xpress.md b/docs/user-guide/solver/optional-features/xpress.md new file mode 100644 index 0000000000..961ad83b50 --- /dev/null +++ b/docs/user-guide/solver/optional-features/xpress.md @@ -0,0 +1,50 @@ +# Usage with FICO® Xpress Optimizer + +[//]: # (TODO: update this page if needed) +_**This section is under construction**_ + +## Introduction +The FICO Xpress optimizer is a commercial optimization solver for linear programming (LP), mixed integer linear programming (MILP), convex quadratic programming (QP), convex quadratically constrained quadratic programming (QCQP), second-order cone programming (SOCP) and their mixed integer counterparts. + +Antares Solver only uses LP, with plans to use MILP at some point in the future. Various benchmarks have revealed that Xpress allows faster simulations than Sirius on large studies. + +## Using Xpress in the command-line +``` +antares-x.y-solver --use-ortools --ortools-solver xpress [options] +``` + +## Setup +The `XPRESSDIR` env variable must point to the Xpress install directory. The author strongly suggest placing this in your .bashrc if you use Bash +``` +export XPRESSDIR=path/to/xpress/install/dir +``` + +An Xpress install directory looks like this. Actually, only these files are required, the rest are unnecessary +``` +xpress814 <= XPRESSDIR +└── lib + ├── libxprs.so -> libxprs.so.40 + ├── libxprs.so.40 <= The Xpress shared library + └── xpauth.xpr <= A valid licence +``` + +## Checking that Xpress works +After setting up Xpress, the following command line should display a line if Xpress is installed and a valid licence is found. +``` +antares-x.y-solver --list-solvers | grep xpress +``` + +## Compatibility +Antares Simulator 8.x has been shown to work with Xpress 8.13.0. Trying to use other versions may work, but can lead to crashes. + +## Known issues +### Performance issues with Xpress 9.x +The following Xpress versions suffer a performance regression that makes them unsuitable for use with Antares Simulator +- 9.0.x +- 9.1.x +- 9.2.x + +As of Q3 2023, it is best to stick to Xpress 8.13.0 for best performance + +### Community license is very restrictive +FICO offers a Community License for testing purposes. It should be noted however that it is extremely restrictive. You may experience issues when trying to run Antares Solver with this license, even on small test-cases. diff --git a/docs/user-guide/ts-generator/00-index.md b/docs/user-guide/ts-generator/00-index.md new file mode 100644 index 0000000000..d4ead75883 --- /dev/null +++ b/docs/user-guide/ts-generator/00-index.md @@ -0,0 +1,12 @@ +[//]: # (Index used by Sphinx to generate correct PDF tree) +# Time-series generator + +```{toctree} +:hidden: +01-overview-tsgenerator.md +02-inputs.md +03-outputs.md +04-parameters.md +05-algorithm.md +06-command-line.md +``` \ No newline at end of file diff --git a/docs/user-guide/ts-generator/01-overview-tsgenerator.md b/docs/user-guide/ts-generator/01-overview-tsgenerator.md new file mode 100644 index 0000000000..e77bab6872 --- /dev/null +++ b/docs/user-guide/ts-generator/01-overview-tsgenerator.md @@ -0,0 +1,9 @@ +# Overview + +_**This section is under construction**_ + +The Time-Series Generator tool is intended to be used before running an *Antares* simulation if you +do not dispose of all the needed input data. +This tool can be used to generate automatically [any or all](04-parameters.md) stochastic input data +(such as renewable energy production time-series) +and put them automatically inside the *Antares* [solver](../solver/02-inputs.md)'s input directory. diff --git a/docs/user-guide/ts-generator/02-inputs.md b/docs/user-guide/ts-generator/02-inputs.md new file mode 100644 index 0000000000..66cac87646 --- /dev/null +++ b/docs/user-guide/ts-generator/02-inputs.md @@ -0,0 +1,7 @@ +# Input files + +_**This section is under construction**_ + +> _**Note:**_ Some specific input data may be located outside the study folder: this is the case for the historical +> times-series to be processed by the time-series analyzer, which may be stored either within the "user" subfolder of +> the study or anywhere else (for instance, on a remote "historical data" or "Meteorological data" server). \ No newline at end of file diff --git a/docs/user-guide/ts-generator/03-outputs.md b/docs/user-guide/ts-generator/03-outputs.md new file mode 100644 index 0000000000..5336711567 --- /dev/null +++ b/docs/user-guide/ts-generator/03-outputs.md @@ -0,0 +1,27 @@ +# Output files + +_**This section is under construction**_ + +1. The outputs of the Antares time-series analyzer are not printed in the general output files but kept within + the input files structure (the reason being that they are input data for the Antares time - series generators). + The associated data may nonetheless be accessed to be reviewed, updated and deleted at any time through the GUI. +2. The times-series analyzer requires the use of a temporary directory in which intermediate files are created + in the course of the analysis and deleted in the end, unless the user wishes to keep them for further examination. + Its location is user-defined and should usually be the "user" subfolder if files are to be kept, otherwise any + proper temporary space such as `C..../Temp`. + +## Scenario mapping file +"scenariobuilder.dat" + +**MC Scenario builder** For each Monte-Carlo year of the simulation defined in the "Simulation" window, +this command allows to state, for each kind of time-series, whether it should be randomly drawn from +the available set (be it ready-made or Antares-generated) _**OR**_ should take a user-defined value +(in the former case, the default "rand" value should be kept; in the latter, the value should be the reference number +of the time-series to use). Multiple simulation profiles can be defined and archived. +The default active profile gives the "rand" status for all time-series in all areas (full probabilistic simulation). + +Regarding Hydro time-series, the scenario builder gives, in addition to the assignment of a specific number to use +for the inflows time-series, the ability to define the initial reservoir level to use for each MC year, also hydro +max power scenario builder is available to support time-series for Maximum Generation and Maximum Pumping because +the number of TS's for ROR, Hydro Storage and Minimum Generation can be different than the number of TS's for +Maximum Generation and Maximum Pumping. \ No newline at end of file diff --git a/docs/user-guide/ts-generator/04-parameters.md b/docs/user-guide/ts-generator/04-parameters.md new file mode 100644 index 0000000000..debe1465cc --- /dev/null +++ b/docs/user-guide/ts-generator/04-parameters.md @@ -0,0 +1,210 @@ +# Parameters + +_**This section is under construction**_ + +[//]: # (TODO: check that these parameters are not used in the solver.) +[//]: # (If they are used by the solver -but only in case some TS are generated-, keep them here but add cross mentions to them) + +--- +## General parameters +These parameters are listed under the `[general]` section in the `.ini` file. + +--- +### Time-series parameters + + +#### generate +- **Expected value:** comma-seperated list of 0 to N elements among the following (case-insensitive): + `load`, `wind`, `hydro`, `thermal`, `solar`, `renewables`, `max-power` (ex: `generate = load, hydro, wind`) +- **Required:** no +- **Default value:** empty +- **Usage:** if left empty, all the time-series will be imported from input files. Else, the time-series + listed in this parameter will be generated randomly by the simulator. + +> _**WARNING:**_ time-series generation is not available for transmission capacities (NTC) + +--- +#### nbtimeseriesload +- **Expected value:** unsigned integer +- **Required:** no +- **Default value:** 1 +- **Usage:** if `load` time-series are [automatically generated](#generate), this parameter sets the number of different + time-series to generate. + +--- +#### nbtimeserieshydro +- **Expected value:** unsigned integer +- **Required:** no +- **Default value:** 1 +- **Usage:** if `hydro` time-series are [automatically generated](#generate), this parameter sets the number of different + time-series to generate. + +--- +#### nbtimeserieswind +- **Expected value:** unsigned integer +- **Required:** no +- **Default value:** 1 +- **Usage:** if `wind` time-series are [automatically generated](#generate), this parameter sets the number of different + time-series to generate. + +--- +#### nbtimeseriesthermal +- **Expected value:** unsigned integer +- **Required:** no +- **Default value:** 1 +- **Usage:** if `thermal` time-series are [automatically generated](#generate), this parameter sets the number of different + time-series to generate. + +--- +#### nbtimeseriessolar +- **Expected value:** unsigned integer +- **Required:** no +- **Default value:** 1 +- **Usage:** if `solar` time-series are [automatically generated](#generate), this parameter sets the number of different + time-series to generate. + +--- +#### refreshtimeseries +[//]: # (TODO: verify usage) +- **Expected value:** comma-seperated list of 0 to N elements among the following (case-insensitive): + `load`, `wind`, `hydro`, `thermal`, `solar`, `renewables`, `max-power` +- **Required:** no +- **Default value:** empty +- **Usage:** if some time-series are [automatically generated](#generate), this parameter selects those of them that have + to be periodically renewed in run-time + +> _**WARNING:**_ time-series refresh is not available for transmission capacities (NTC) + +--- +#### intra-modal +[//]: # (TODO: verify usage) +- **Expected value:** comma-seperated list of 0 to N elements among the following (case-insensitive): + `load`, `wind`, `hydro`, `thermal`, `solar`, `renewables`, `ntc`, `max-power` +- **Required:** no +- **Default value:** empty +- **Usage:** if some time-series are [automatically generated](#generate), this parameter selects those of them that are + correlated, i.e. for which the same time-series should be used together in a given scenario. + +> _**WARNING:**_ inter-modal correlation is not available for transmission capacities (NTC) +> _**WARNING:**_ this is the historical correlation mode + +--- +#### inter-modal +[//]: # (TODO: document this parameter) +_**This section is under construction**_ +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +> _**Note:**_ +> A full meteorological correlation (for each MC year) is, from a theoretical standpoint, achievable by activating +> "intramodal" and "intermodal" for all but the `thermal` kind of time-series. The availability of an underlying +> comprehensive multidimensional meteorological database of ready-made time-series is the crux of the matter when it +> comes to using this configuration. + +--- +#### improveunitsstartup +[//]: # (TODO: document this parameter -seems deprecated-) +_**This section is under construction**_ +- **Expected value:** +- **Required:** **yes** +- **Default value:** +- **Usage:** + +--- +#### refreshintervalload +- **Expected value:** strictly positive integer +- **Required:** no +- **Default value:** 100 +- **Usage:** if `load` time-series are automatically [generated](#generate) and [refreshed](#refreshtimeseries), this + parameter sets their refresh interval (in number of Monte-Carlo years). + +--- +#### refreshintervalhydro +- **Expected value:** strictly positive integer +- **Required:** no +- **Default value:** 100 +- **Usage:** if `hydro` time-series are automatically [generated](#generate) and [refreshed](#refreshtimeseries), this + parameter sets their refresh interval (in number of Monte-Carlo years). + +--- +#### refreshintervalwind +- **Expected value:** strictly positive integer +- **Required:** no +- **Default value:** 100 +- **Usage:** if `wind` time-series are automatically [generated](#generate) and [refreshed](#refreshtimeseries), this + parameter sets their refresh interval (in number of Monte-Carlo years). + +--- +#### refreshintervalthermal +- **Expected value:** strictly positive integer +- **Required:** no +- **Default value:** 100 +- **Usage:** if `thermal` time-series are automatically [generated](#generate) and [refreshed](#refreshtimeseries), this + parameter sets their refresh interval (in number of Monte-Carlo years). + +--- +#### refreshintervalsolar +- **Expected value:** strictly positive integer +- **Required:** no +- **Default value:** 100 +- **Usage:** if `solar` time-series are automatically [generated](#generate) and [refreshed](#refreshtimeseries), this + parameter sets their refresh interval (in number of Monte-Carlo years). + + +--- +## Input parameters +These parameters are listed under the `[input]` section in the `.ini` file. + +--- +#### import +- **Expected value:** comma-seperated list of 0 to N elements among the following (case-insensitive): + `load`, `wind`, `hydro`, `thermal`, `solar`, `renewables`, `ntc`, `max-power` +- **Required:** no +- **Default value:** empty +- **Usage:** if some time-series are [automatically generated](#generate), this parameter selects those of them that + should be exported into the input files (in replacement of the original ones). + +> _**Note:**_ +> you can also use [archives](../solver/04-parameters.md#archives) to store the time-series in the output folder. + +--- +## Seeds - Mersenne Twister parameters +These parameters are listed under the `[seeds - Mersenne Twister]` section in the `.ini` file. +They allow the user to set the seeds of random number generators, in order to ensure the results are repeatable. + +--- +#### seed-tsgen-load +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** if `load` time-series are [automatically generated](#generate), this parameter fixes the seed for its + random generator. + +--- +#### seed-tsgen-hydro +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** if `hydro` time-series are [automatically generated](#generate), this parameter fixes the seed for its + random generator. + +--- +#### seed-tsgen-wind +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** if `wind` time-series are [automatically generated](#generate), this parameter fixes the seed for its + random generator. + +--- +#### seed-tsgen-thermal +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** if `thermal` time-series are [automatically generated](#generate), this parameter fixes the seed for its + random generator. + +--- +#### seed-tsgen-solar +- **Expected value:** unsigned integer +- **Required:** **yes** +- **Usage:** if `solar` time-series are [automatically generated](#generate), this parameter fixes the seed for its + random generator. \ No newline at end of file diff --git a/docs/user-guide/ts-generator/05-algorithm.md b/docs/user-guide/ts-generator/05-algorithm.md new file mode 100644 index 0000000000..85afee3ca9 --- /dev/null +++ b/docs/user-guide/ts-generator/05-algorithm.md @@ -0,0 +1,429 @@ +# Algorithm + +_**This section is under construction**_ + +## General + +When ready-made time-series are not available or are too scarce for building the required number of Monte-Carlo annual simulation scenarios, Antares provides means to generate sets of stochastic time-series to use instead. + +The different categories of time-series call for wholly different generation processes: + +- For thermal power, the generator is based on the animation of a daily three-state Markov chain (available – planned outage – forced outage) attached to each plant. + +- For Hydro-power, the generator works out monthly time-series of energies, based on the assumption that they can be modeled by Log Normal variables with known correlations through space and time. So as to keep the model simple, for an interconnected system made of N areas, the user defines, along with the N expectations and N standard deviations of the monthly energies, the N X N correlation matrix R(n,m) of the logs of the annual hydro energies between the areas n,m, and the N average auto-correlations r(k) between one month and the next in each area k. The correlation **C(n,i,m,j)** between the logs of hydro energies in area **n**, month **i** and area **m**, month **j** is taken to be + +$$C(n,i,m,j) = R(n,m)*\sqrt{(r(n) \cdot r(m))^{|j-i|}}$$ + + +This most simplified model asks for considerably fewer data than a comprehensive 12N X 12N time-space matrix. Note that if R is positive semi-definite but C is not, matrix C is automatically transformed into a fitting p.s.d matrix and the data generation keeps going on (however, the log report will show a warning message). If the primary matrix R is not p.s.d, data are considered as corrupted, the generation stops and a fatal error message will be displayed in the log report + +- For Wind power, Solar power and Load, the required time-series are 8760-hour long and have to emulate as closely as possible the response of the system to variations of wind speed, sunshine and temperature. In all three cases, the rationale of the model is to offer the possibility to consider either the final variable to model (wind power output, solar power output, load) or an underlying intermediate variable (wind speed, nebulosity, deviation between load and the level expected in standard temperature conditions) as a stationary stochastic process, with given marginal laws, given auto-correlation functions and given spatial correlations (eventually, the values of the final variables and those of the core stationary process are tied by diurnal/seasonal rhythms and scaling functions). + +The identification of all relevant parameters can be made outside Antares by any appropriate means but can also be made automatically by the time-series analyzer, which is then to be fed with the largest available set of historical time-series. Note however that, using the time-series analyzer, one has to consider whether the time-series at hand are statistically meaningful or whether they need some pre-processing (for instance, if wind power time-series are gathered for a period within which the fleet has been expanded, the time-series to analyze should be expressed in % of installed power rather than in MW. For Solar power, the relevant variable to model as a stationary stochastic process is probably not the raw output of solar power but more likely a meteorological indicator related to the sky clarity (for instance , time-series of nebulosity expressed on a 0-100 scale may be used). + +Once generated by appropriate algorithms, the values of the stationary processes are turned into final values by using a number of parameters that put back in the series the diurnal and seasonal patterns that may have been observed in the course of the historical data analysis and that were temporarily removed to identify the core stationary processes. + + +## Time-series generation (load, wind, solar): principles + +For the generation of wind, solar and load time-series, Antares gives access to different marginal laws and autocorrelation functions presented hereafter. Note that wind speed modeling should usually be based upon a Weibull modeling, while almost all other situations are likely to be best modeled by Beta variables. + +The stationary processes are defined at a monthly scale. For each month, there are: + +- Four parameters for the definition of the marginal law + +TS Gen. Parameters : $\alpha$, $\beta$, $\gamma$ and $\delta$ + +| **Law** | $\alpha$ | $\beta$ | $\gamma$ | $\delta$ | **Expectation** | **Variance** | +|---------|:----------:|:---------:|:----------:|:----------:|:---------------:|:------------:| +| Uniform | N/A | N/A | $< \delta$ | $> \gamma$ | ${(\delta - \gamma)\over 2}$ | ${(\delta - \gamma)^2\over 12}$ | +| Beta | >0 | >0 | $< \delta$ | $> \gamma$ | $\gamma + {\alpha(\delta - \gamma)\over (\alpha + \beta)}$ | $\alpha\beta(\delta - \gamma)^2\over (\alpha + \beta + 1)(\alpha + \beta)^2$ | +| Normal | Any | >0 | N/A | N/A | $\alpha$ | $\beta^2$ | +| Weibull | >=1
    <50 | >0 | N/A | N/A | $\beta \Gamma (1 + {1\over\alpha})$ | $\beta^2[\Gamma(1+{2\over \alpha}) - \Gamma (1 + {1\over \alpha})^2]$ | +| Gamma | >=1
    <50 | >0 | N/A | N/A | $\alpha * \beta$ | $\alpha * \beta^2$ | + +_Uniform: uniform defined on ($\gamma$, $\delta$)._ +_Beta: Beta ($\alpha$, $\beta$) defined on ($\gamma$, $\delta$)._ +_Normal: expectation $\alpha$, standard deviation $\beta$._ +_Weibull: shape $\alpha$, scale $\beta$, defined on (0,+$\infty$)._ +_Gamma: shape $\alpha$, scale $\beta$, defined on (0, +$\infty$)._ + +In the expressions of expectation and variance, $\Gamma(x)$ is the standard Euler Function. + + +- Two parameters for the definition of the autocorrelation function + +**TS Gen. Parameters : $\theta$ and $\mu$** + +| **Law** | $\theta$ | $\mu$ | **Corr(Xt, Xt+h)** | +|-----|----|-----|--------| +| Pure exponential decay | $\theta > 0$ | $\mu = 1$ | $e^{-\theta h}$ | +| Smoothed exponential decay [^decay] | $\theta > 0$ | $ 1 < \mu < 24$ | $\Phi(\theta, \mu, h)$ | + +$$\Phi(\theta, \mu, h)\ =\ {1\over A}\ *\ \sum_{i=0, \mu}{\ \sum_{j=h, h+\mu}{e^{-\theta|j-i|}}}$$ + +**with** + +$$A=\mu + 2 \sum_{i=1, \mu; j=1, \mu; j > i}{e^{-\theta(j-i)}}$$ + + +## Time-series generation (load, wind, solar): GUI + +The section of the GUI specific to the generation of wind, solar and load time-series comprises: + +1. **Spatial correlation matrices that are located within the "spatial correlation" tab of each path "Wind|Solar|Load / <area\_name>"** + + This tab contains a workspace for the description of 12 monthly spatial correlation matrices $\Xi$ and one annual correlation matrix. For the stochastic generators to work properly, these matrices must meet the usual requirements (matrices must be p.s.d, symmetric, with all terms between -100 and +100, and a main diagonal made of 100s). If this is not the case, generators will emit an infeasibility diagnosis. Matrices can be either set up manually OR automatically filled out by the time-series analyzer (see next paragraph). + + Depending on the choices made in the main "simulation" window, the matrices used will be either the 12 monthly matrices or the annual matrix. Whether to use the first or the second option depends on the quality of the statistical data at hand: with high quality data (for instance, that derived from the analysis of a very large pool of historical data), use of monthly correlations is recommended because monthly differences between matrices have a physical meaning ; with less robust data (derived from a handful of historical data,…), use of the single annual correlation matrix should be preferred because it smooths out the numeric noise which impairs the monthly matrices. + +2. **Four parameters and four subtabs that are located within the "local" tab of each path "Wind|Solar|Load / <area\_name>"** + +**FOUR PARAMETERS** + +- Capacity: This first parameter is used to scale up time-series generated on the basis of the ($\alpha$, $\beta$, $\gamma$, $\delta$, $\theta$, $\mu$) parameters described previously in the "principles" paragraph, together with coefficients characterizing the diurnal pattern (see below) + +- Distribution: This second parameter gives the type of marginal distribution of the stationary stochastic processes to generate (Beta, Weibull, Normal, Gamma, Uniform) + +- Translation: This third parameter has three possible values: + + - Do not use: parameter ignored + - Add before scaling: A specific 8760-hour array is added to the time-series produced by the primary stochastic generator, BEFORE use of the conversion table (optional) followed by the final multiplication by the capacity factor + - Add after scaling: A specific 8760-hour array is added to the time-series produced by the primary stochastic generator, AFTER use of the conversion table (optional) followed by the final multiplication by the capacity factor + +- Conversion: This fourth parameter has two possible values: + + - Do not use: Any transfer function that may be described in the "conversion" subtab (see below) should not be used for the final stage of data elaboration (for instance, if the primary parameters describe the physics of wind speeds, the time-series eventually produced should remain wind speeds and not wind power). + + - Use: The time-series produced by the stochastic generators (wind speeds, for instance) are turned into other values (wind power) by using the transfer function described in the "conversion" subtab. + +**FOUR SUBTABS** + +- Subtab "Coefficients" + A twelve-month table of values for the primary parameters $\alpha$, $\beta$, $\gamma$, $\delta$, $\theta$, $\mu$
    + This table may be either filled out manually or automatically (use of the time-series analyzer) + +- Subtab "Translation" + Contains an 8760-hour array T to add to the time-series generated, prior or after scaling. This array can be either filled out manually or by the time-series analyzer. + +- Subtab "Daily profile" + A 24\*12 table of hourly / monthly coefficients K(hm) that are used to modulate the values of the stationary stochastic process by which the actual process is approximated. This table can be either filled out manually or by the time-series analyzer. + +- Subtab "Conversion" + A table of 2 \* N values (with 1<=N<=50) that is used to turn the initial time-series produced by the generators (for instance, wind speeds) into final data (for instance, wind power). The transfer function (speed to power, etc.) is approximated by N discrete points whose abscises X(N) an ordinates Y(N) are given by the table. + +## Time-series analysis (load, wind, solar) + +The time-series analyzer module available in Antares is meant to identify the values that should be given to the parameters used in the time-series generators (load, solar power, wind power) so as to fit best historical time-series at hand. + +**IMPORTANT: ** When the time-series analyzer is used, it automatically updates the parameters relevant to the analysis (for instance: analysis of "wind" time-series will overwrite all local and global "wind" parameters [correlation matrices] that may have been previously set manually). + +The primary TS analyzer window shows two tabs: + +**1. Tab "Time-series and areas"** + +- Time-series (load, wind, solar): class of parameters to be assessed by the analyzer + +- Browse: location of the historical time-series files. These are txt files in which 8760-hour time-series must be stored in adjacent columns separated by a tabulation + +- For each area: + + - Activity status + - yes: parameters will be assessed and updated by the analyzer + - no: the area will be skipped (**local** parameters for the area will remain unchanged, however **spatial** correlation with other areas will be reset to zero) + + - Distribution + - Type of distribution to fit (beta, normal, etc.) + + - Data + - Raw: data to analyze are the actual historical time-series + - Detrended: data to analyze are the time-series of the deviations to average (for instance: load time-series need to be analyzed in "detrended" mode while wind speeds can be analyzed in "raw" mode) + + - File to analyze + - Name of the file that should contain historical time-series to analyze + - Status + - Ready (a file bearing the expected name was found) + - Not found (no file found with the expected name) + +**IMPORTANT:** To generate stochastic data similar to the historical data analyzed, generation parameters must be kept consistent with the results of the analysis, which means, in the generators: + +- Keep the same: + + - Type of distribution + - Values for $\alpha$, $\beta$, $\gamma$, $\delta$ and for the diurnal–seasonal pattern (table of 12 X 24 values) + - Value for the "capacity" parameter (the analyzer automatically sets it to 1) + +- Besides: + - "Conversion" option must be set to "no" + - "Translation" option must be set to "do not use "if data were analyzed as "raw" and to "add after scaling" or "add before scaling" if data were analyzed as "detrended" (both options give the same value in this case because the scaling is 1:1) + +**2. Tab "Global settings"** + +- Temporary folder: workspace that can be used for the analysis (cleaned after use) + +- Analyzer settings + + - Short-term autocorrelation adjustment (%) + - Long-term autocorrelation adjustment (%)
    + These two parameters are used by Antares as targets for the fitting of $\theta$ and $\mu$ parameters. For instance, if the historical time-series autocorrelation function is such that Corr(T,T+ 18 hours)=90 % and Corr(T,T+60 hours)= 50%, and if the parameters in the analyzer are (ST = 90%,LT = 50%) , then it will search values of $\theta$ and $\mu$ matching the historical autocorr.function in two points(18 hours, 60 hours). + + - Trimming threshold (%)
    + In the spatial correlation matrices, terms lower than the threshold will be replaced by zeroes + +- Input data + + - Time-series per area (n)
    + limits the analysis to the first n historical time-series at hand + - Upper-bound (Max)
    + In the analysis, all values above Max in the historical files will be replaced by Max + - Lower-bound (Min)
    + In the analysis, all values below Min in the historical files will be replaced by Min + +**IMPORTANT:** For each month, time-series to analyze are assumed to represent a stationary stochastic signal modulated by 24 hourly shape-factors. All of these shape-factors are expected to be different from zero. If the signal is partly masked by sequences of zeroes (for instance, if solar power time-series are to be analyzed as such because time-series of nebulosity are not available), the analysis is possible but is subject to the following restrictions: + +- **Use of the "detrended" mode in the first Tab is mandatory** _(use of the "raw" mode would produce wrong correlation matrices)_ + +- **Short- and Long- Term autocorrelation parameters in the second Tab must be identical and set to 99%** _(to ensure that auto-correlation be assessed for the shortest possible time lag, i.e. one hour)_ + +**NOTICE:** For the whole year, the analyzer delivers a table of 12x24 hourly shape-factors consistent with the 12 sets of parameters identified for the stationary stochastic processes. The content of the table depends on the mode of analysis chosen: + +- **"raw"** analysis: for each month, the sum of the 24 hourly shape-factors is equal to 24 (i.e. each term is a modulation around the daily average). + +- **"detrended"** analysis: for the whole year, hourly coefficients are expressed relatively to the annual hourly peak of the (zero-mean) signal absolute value. (i.e. all factors belong to the [0,1] interval) + +## Time-series generation (thermal) + +The thermal time-series generation will only be launched: +- On thermal clusters that have the Generated TS parameter set to “Force generation†+- And, when in the Simulation window, the Stochastic TS parameter for Thermal is set to "Onâ€, on the thermal clusters that have the Generated TS parameter set to "Use global parameter". + +The stochastic generator for time-series of available dispatchable power generation works, for each plant of each set (cluster), with the following parameters: + +- The nominal plant capacity and a 8760-hour array of modulation coefficients to apply to it (default value: 1) + +- A 365-day array of forced outages rates ("FOR", lies in [0,1] ) + +- A 365-day array of planned outages rates ("POR", lies in [0,1]) + +- A 365-day array of forced outages average durations ("FOD" in days, integer, lies in [1,365]) + +- A 365-day array of planned outages average durations ("POD" in days, integer,lies in [1,365]) + +- A 365-day array of planned outages minimum number (PO Min Nb) (integer, lies in [0, PO Max Nb]) + +- A 365-day array of planned outages maximum number (PO Max Nb) (integer, lies in [PO Min Nb, Nb of units in the cluster] + +- Two parameters describing how forced outages durations may randomly deviate from their average value (law: uniform or geometric , volatility: lie in [0,1]) + +- Two parameters describing how planned outages durations may randomly deviate from their average value (law: uniform or geometric , volatility: lie in [0,1]) + +**1. Outage duration : meaning and modeling** + +In the thermal time-series generator, the concept of outage duration (either forced or planned) is simple enough: for any given plant affected by such an event, it is the duration of a single outage, expressed in days. + +The fact that 365 different values can be used to describe what may happen in the course of a year (for each kind of outages) means that the average outage duration may depend on the day the outage begins on. For instance, very short outages may be sometimes be planned on week-ends. Likewise, historical statistics can show that forced outages do not last the same average time in winter and summer, etc. + +In complement to the average value of the duration D of outages beginning on a particular day, the time-series generator allows to set two parameters that describe how the actual outage durations may deviate from the calendar-related average value. + +- The first parameter (law) can take either the value "uniform" or "geometric":
    + Uniform: the actual outage duration will be randomly drawn (one draw per outage), according to a **uniform distribution** centred on the average value **D**. The width of the interval [min duration, max duration] will depend on the value of the second parameter (volatility).
    + Geometric: the actual outage duration will be expressed as the sum of a fixed value F and a randomly drawn (one draw per outage) variable following a **geometric distribution** of expectation G, with **F+G=D**. The ratio of F to G will depend on the value of the second parameter (volatility). + + +- The second parameter (volatility) can take any value within [0,1]: + + - 0: The outage duration does not show any stochastic fluctuation at all.
    + Therefore, regardless of the chosen distribution law:
    + **
    actual duration = D
    ** + + - 1: The variability of the actual outage duration is as high as the chosen distribution law makes it possible, which means respectively that: + + - If choice = "uniform": **1 <= actual duration <= 2D-1** + - If choice = "geometric": **F = 0 and G = D**
    + (which in turn implies 1 <= actual duration <= #4D) + + - 0<V<1: The variability of the actual outage duration is such that the ratio $\sigma / D$ of its standard deviation to its expectation has a value that depends on **V** , on **D** and on the chosen distribution law. More precisely: + + - If choice = "uniform": $\sigma / D = [{1/3}^{0.5}] \* V \* (D-1) / D $
    + and
    + **Duration min = D (1-V) + V**
    + **Duration max = D (1+V) - V** + + - If choice = "geometric": $\sigma / D = V \* [(D-1) / D]^{0.5}$
    + and
    + **Duration min = F**
    + **Duration max # 4D-3F**
    + _with F = D – G_
    + _G = 2z /[(1+4z)^0.5 - 1]_
    + _z = (V^2) \* D \* (D-1)_ + +**NOTE:** _The calculation time required for the generation of time-series does not depend of the kind of chosen law but depends on the fact that the volatility is null or not (it is minimal for zero-volatility)._ + +**NOTE:** _A geometric law associated with a volatility parameter V yielding a characteristic parameter F (according to the previous formulas) will produce a distribution summarized by:_ + +- _63 % of values in the interval [F, D]_ +- _23 % of values in the interval [D, 2D-F]_ +- _12 % of values in the interval [2D-F, 4D-3F]_ +- _2 % of values in the interval [4D-3F, infinite)_ + +**Remark:** _Antares is able to provide these options because it involves more than a simple Markov chain mechanism (intrinsically limited to : law = geometric, volatility = 1)_ + +**2. Outage rates: meaning and modeling** + +The concept of outage rate is not always clearly distinguished from the notion of failure rate, to which it is closely related. + +Outage rates OR represent the average **proportion** of time during which a plant is unavailable (for instance, OR = 5.2%). + +Failure rates FR represent the average **number** of outages **starting** during a period of time of a given length (for instance, FR = 1.5 per year). If the time step is short enough (typically one day, which is the value used in Antares), the failure rates are always lower than 1 (for instance, FR = (1.5 / 365) per day). + +When this condition is met and if the physical outage process can be modelled by a Poisson process, failure rates can be interpreted as probabilities. + +In Antares the following relation between failure rates FR, outage rates OR and outage durations OD is used: + +**
    FR = OR / [OR+ OD \* ( 1 – OR )]
    ** + +To determine whether a plant available on day D is still available on day D+1, the Antares stochastic generator therefore makes draws based on the failure rates equivalent to the data provided in the form of outage rates and outage durations. + +Since two processes may be described in the GUI, consecutive draws are made for each process so as to determine whether: + +- An outage of the first category begins (it will last for the specified duration) +- An outage of the second category begins (it will last for the specified duration) +- No outage occurs, the plant is still available on D+1 + +Whether to describe the "planned outage" process as a random process or not depends of the kind of data at hand, which is often related to the horizon of the studies to carry out: when actual overhauls plans are known, the PO rates can be set at 1 when the plant is deemed to be unavailable and to zero on the other days. + +For long term studies in which only general patterns are known, season-, month- or week- modulated rates and duration may be used to describe the "planned" process as a stochastic one. Another possible use of the model is to incorporate the overhauls plans in the "nominal capacity modulation" array, and consider the stochastic "planned outage" processor as a simulator for a second modality of forced outage (longer or shorter than the main component) + +**NOTE:** _Once the outage duration and outage rate are defined, the failure rate is completely determined. For the sake of clarity, the Antares GUI displays still another parameter often used in reliability analysis, which is the MTBF (Mean Time Between Failure). Relations between MTBF, FR and OR are:_ + +_**
    FR= 1 / ( MTBF+1 ) OR = OD / ( MTBF+OD )
    **_ + +**NOTE:** _When two stochastic processes of outages (forced and planned, or forced-type-1 and forced-type-2) are used, the overall resulting outage rate OOR is not equal to the sum of the two rates FOR and POR. Instead, the following relation holds:_ + +_**
    OOR = ( FOR + POR – 2\*FOR\*POR ) / (1 - FOR\*POR)
    **_ + +_The explanation of this formula lies in the definition of the different outages rates:_ + +_Over a long period of operation, FOR represents the ratio of the time spent in forced outages to the overall time not spent in planned outages._ + +_Likewise, POR represents the ratio of the time spent in planned outages to the overall time not spent in forced outages._ + +_OOR represents the ratio of the time spent in either forced or planned outages to the overall operation period._ + +_The period of operation can be broken down into three categories of hours:_ + +_F hours spent in forced outages_ + +_P hours spent in planned outages_ + +_A hours of availability_ + +_The following relations hold and explain the previous formula:_ + +_FOR = F/(A+F)_ + +_POR=P/(A+P)_ + +_OOR=(F+P)/(A+F+P)_ + +**3. Planned Outages Minimum and Maximum Numbers** + +In the description given so far regarding how outages are modeled, no true difference was made between "forced" and "planned" outages, i.e. both relied on unconstrained random draws. This is satisfactory only if the process to model through the "planned" data is actually little constrained, or not at all. + +In all other occurrences, it makes sense to define a general framework for the maintenance schedule. In Antares this is defined at the cluster scale by two specific 365-day arrays: + +
    PO Min Nb and PO Max Nb.
    + +These parameters are used by the time-series generator as constraints that **cannot be violated**, regardless of the raw outcome of regular random draws. To meet these constraints, the generator may have to anticipate or delay "planned" outages yielded by the primary random draws stage. If data regarding planned outage rates and planned outage Max and Min numbers are not consistent, the Max and Min Numbers take precedence. + +_Examples (for simplicity'sake, they are described here with only one value instead of 365):_ + +_Cluster size = 100 PO rate =10% PO Min Nb=0 PO Max Nb= 100_ + +- _Actual number in [0,100], average = 10, wide fluctuations (unconstrained)_ + +_Cluster size = 100 PO rate =10% PO Min Nb=7 PO Max Nb= 11_ + +- _Actual number in [7,11], average = 10 (to remain within the bounds, some outages will be anticipated, while others will be delayed)_ + +_Cluster size = 100 PO rate =0% PO Min Nb=10 PO Max Nb= 10_ + +- _Actual number =10 (to remain within the bounds, outages are set up even if none come from random draws)_ + +## Time-series analysis (thermal) + +The stochastic generator for time-series of available dispatchable power generation needs to be given assumptions regarding forced & planned outages rates & durations. Depending on the quality and quantity of statistics at hand, these estimates can be either described as "flat" (same constant values used from the beginning to the end of the year) or as more or less modulated signals, with the possibility of choosing different values for each day of the year. + +Different ways can be considered to work out values for FOR,POR,FOD,POD from historical data regarding outages. For any (family of) plant(s) to study, notations have to be defined with respect to the "calendar accuracy" chosen by the user. For the sake of clarity, assume from now on that the user wants to assess weekly rates and durations, that is to say: describe the whole year with 52 values for rates and durations, for both forced and planned outages (within any given week, identical values will therefore be assigned to the seven days of the week). + +With the following notations: + +- D(w) = Overall cumulated statistical observation time available for week (w) + for instance, for w = 1= first week of January : D(w) = 3500 days coming from 10 years of observation of 50 identical plants + +- Df(w) = Within D(w), overall time spent in forced outages, either beginning during week w or before (for instance , Df(1) = 163 days) + +- Dp(w) = Within D(w), overall time spent in planned outages, either beginning during week w or before (for instance, Dp(1) = 22 days) + +- Kf(w) = Number of forced outages beginning during week (w) + (for instance, Kf(1) = 26) + +- Kp(w) = Number of planned outages beginning during week (w) + (for instance, Kp(1) = 3) + +- FOT(w) = Overall cumulated time (expressed in days) spent in forced outages beginning during week (w) (for instance, FOT(1)= 260) + Note that if outages last more than one week FOT(w) necessarily includes days from weeks w+1, w+2,… + +- POT(w) = Overall cumulated time (expressed in days) spent in planned outages beginning during week (w) (for instance, POT(1) = 84) + Note that if outages last more than one week POT(w) necessarily includes days from weeks w+1, w+2,… + +The following formulas can be used : + +**FOD (w) = FOT(w) / Kf(w)** + +**POD (w) = POT(w) / Kp(w)** + +**FOR(w) = FOD(w) / [FOD(w) + ( (D(w) - Dp(w)) / Kf(w))]** + +**POR(w) = POD(w) /[POD(w) + ( (D(w) - Df(w))) / Kp(w))]** + +_For the examples given above, the estimated parameters would therefore be :_ + +_FOD(1) = 10 (days)_ + +_POD(1) = 28 (days)_ + +_FOR(1) = 0.0695 # 7 %_ + +_POR(1) = 0.0245 # 2.5 %_ + +_These values should eventually (using the GUI or other means) be assigned to the first seven days of January._ + +## Time-series generation and analysis (hydro) + +The stochastic hydro generator assesses monthly time-series of energies, based on the assumption that they can be modeled by Log Normal variables. The values generated are interpreted as monthly amounts of hydro energies generated (sum of Run of River – ROR – and hydro storage – HS) or as amounts of hydro inflows, depending on the modeling chosen for the area (straightforward estimate of energies generated or explicit management of reservoirs). + +The historical data to work from depend on the kind of modeling chosen (statistics of monthly generation in the first case, or statistics of monthly inflows in the second case). + +In both cases, assuming that a large number of historical time-series of energies are available, the rationale of the assessment of parameters is the following (from now on, "energies" mean either "ROR and HS energies generated" or "inflows to ROR and HS"), + +1. For each area n, build up annual energy time-series **A(n)** by aggregation of the original monthly energy time-series **M(n)**. For each pair of areas (n,m) , assess the correlation **R(n,m)** between the random variables **Log(A(n))** and **Log(A(m))**. Expressed in percentage, matrix **R** should be used to fill out the "spatial correlation tab" of in the active window "hydro" + +2. For each area n, build up two monthly time-series derived from the original array **M(n)**, by proceeding as follows. Assuming that **M(n)** has K elements (for instance, K= 180 if 15 years of statistics are available): + + - **M'(n)** = time-series of K-1 elements obtained by deleting the first element of the time-series Log(M(n)) + - **M''(n)** = time-series of K-1 elements obtained by deleting the last element of the time-series Log(M(n)) + + Assess the correlation **IMC(n)** between the random variables **M'(n)** and **M''(n)**. This value (lying in [-1,1]) should be used to fill out the field "inter-monthly correlation value" of the "local data" tab in the "hydro" active window. + +3. For each area n, build up 12 monthly energy time-series derived from the original array **M(n)** by extracting from **M(n)** the values related to each month of the year (**M1(n)**= time-series of energies in January,…, **M12(n)** = time-series of energies in December.) + + Assess the expectations and standard deviations of the 12 random variables **M1(n)** ,…, **M12(n)**. These values should be used to fill out the fields "expectation" and "std deviation" of the "local data" tab in the "hydro" active window. + + Aside from expectation and standard deviations, minimum and maximum bounds can be freely set on the monthly overall energies (ROR + HS). Whether to assess these bounds by examination of historical data or on the basis of other considerations depends on the context of the studies to carry out. + +4. For each area n, extract from the 12 monthly overall energy time-series **M1(n) ,…, M12(n)** the contribution of the 12 monthly time-series of ROR energies **R1(n),…, R12(n)**. + + Assess the expectations of the 12 random variables **R1(n)/M1(n),…., R12(n)/M12(n)** . These values should be used to fill out the fields "ROR share" of the "local data" tab in the "hydro" active window. + +[^decay]: Obtained by the generation of purely exponentially autocorrelated values (parameter $\theta$ ) followed by a moving average transformation (parameter $\mu$ ). $\theta$ and $\mu$ should be carefully chosen so as to accommodate at best the experimental data at hand. If meaningful historical data are available, this identification may be directly made using the Antares time-series analyzer. diff --git a/docs/user-guide/ts-generator/06-command-line.md b/docs/user-guide/ts-generator/06-command-line.md new file mode 100644 index 0000000000..68ba48017f --- /dev/null +++ b/docs/user-guide/ts-generator/06-command-line.md @@ -0,0 +1,12 @@ +--- +hide: + - toc +--- + +# Command-line instructions + +| command | meaning | +|:----------------|:------------------------------------------------------------------------------------------------------------------------| +| --all-thermal | Generate TS for all thermal clusters | +| --thermal=VALUE | Generate TS for a list of area IDs and thermal clusters IDs, example: `--thermal="area1ID.clusterID;area2ID.clusterID"` | +| -h, --help | Display this help and exit | diff --git a/mkdocs.yml b/mkdocs.yml index 47ba7974c0..23187934c1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -8,10 +8,12 @@ theme: logo: assets/logo.png favicon: assets/Icone.png prev_next_buttons_location: none + custom_dir: docs/overrides features: - navigation.instant - navigation.top - - navigation.expand + - content.tabs.link + # - navigation.expand # - navigation.sections # - header.autohide # - toc.separate @@ -28,34 +30,61 @@ theme: name: Switch to light mode nav: - - 'Home': index.md - - 'Antares ecosystem' : 'https://antares-doc.readthedocs.io' - - 'Reference guide': - - 'Introduction': 'reference-guide/01-introduction.md' - - 'Data organization': 'reference-guide/02-data_organization.md' - - 'Commands': 'reference-guide/03-commands.md' - - 'Active windows': 'reference-guide/04-active_windows.md' - - 'Output files': 'reference-guide/05-output_files.md' - - 'Time-Series analysis and generation': 'reference-guide/06-time_series_analysis_and_generation.md' - - 'Kirchhoff''s constraint generator': 'reference-guide/07-kirchhoffs_constraint_generator.md' - - 'Miscellaneous': 'reference-guide/08-miscellaneous.md' - - 'System requirements': 'reference-guide/09-system_requirements.md' - - 'Command line': 'reference-guide/10-command_line.md' - - 'Adequacy patch (v8.3.0+)': 'reference-guide/14-adequacy-patch.md' - - 'File format changes': 'reference-guide/13-file-format.md' - - 'Attribution notices': 'reference-guide/12-attribution_notices.md' - - 'Optimisation problem' : 'reference-guide/11-modeling.md' - - 'Build': - - 'Introduction': 'build/0-INSTALL.md' - - 'Development requirements': 'build/1-Development-requirements.md' - - 'Dependencies install': 'build/2-Dependencies-install.md' - - 'Build': 'build/3-Build.md' - - 'Tests (user)': 'build/4-Tests-user.md' - - 'Tests (developer)' : 'build/4-Tests-dev.md' - - 'Installer creation': 'build/5-Installer-creation.md' - - 'Continuous Integration' : 'build/continuous-integration.md' - - 'OR-tools integration' : 'build/ortools-integration.md' - - 'Changelog': 'CHANGELOG.md' + - 'Home': 'index.md' + - 'User guide': + - 'Overview': 'user-guide/01-overview.md' + - 'Installation': 'user-guide/02-install.md' + - 'Getting started': 'user-guide/03-getting_started.md' + - 'Solver': + - 'Overview': 'user-guide/solver/01-overview.md' + - 'Input files': 'user-guide/solver/02-inputs.md' + - 'Output files': 'user-guide/solver/03-outputs.md' + - 'Parameters': 'user-guide/solver/04-parameters.md' + - 'Optimization model': 'user-guide/solver/05-model.md' + - 'Hydro heuristics': 'user-guide/solver/06-hydro-heuristics.md' + - 'Thermal heuristics': 'user-guide/solver/07-thermal-heuristic.md' + - 'Command-line instructions': 'user-guide/solver/08-command-line.md' + - 'Optional features': + - 'Multi-threading': 'user-guide/solver/optional-features/multi-threading.md' + - 'Adequacy patch': 'user-guide/solver/optional-features/adequacy-patch.md' + - 'Usage with FICO® Xpress Optimizer': 'user-guide/solver/optional-features/xpress.md' + - 'Appendix': 'user-guide/solver/09-appendix.md' + - 'Time-series generation': + - 'Overview': 'user-guide/ts-generator/01-overview.md' + - 'Input files': 'user-guide/ts-generator/02-inputs.md' + - 'Output files': 'user-guide/ts-generator/03-outputs.md' + - 'Parameters': 'user-guide/ts-generator/04-parameters.md' + - 'Algorithm': 'user-guide/ts-generator/05-algorithm.md' + - 'Command-line instructions': 'user-guide/ts-generator/06-command-line.md' + - 'Other features': + - 'Batch Runner': 'user-guide/other-features/batchrun.md' + - 'Config Checker': 'user-guide/other-features/config.md' + - 'GUI': 'user-guide/other-features/ui-simulator.md' + - 'Kirchhoff''s constraint generator': 'user-guide/other-features/kirchhoff-constraints-builder.md' + - 'Study Cleaner': 'user-guide/other-features/study-cleaner.md' + - 'Study Finder': 'user-guide/other-features/study-finder.md' + - 'Study Updater': 'user-guide/other-features/study-updater.md' + - 'Time-Series Analyzer': 'user-guide/other-features/analyzer.md' + - 'Vacuum': 'user-guide/other-features/vacuum.md' + - 'Year-by-Year Aggregator': 'user-guide/other-features/ybyaggregator.md' + - 'Migration guides': 'user-guide/04-migration-guides.md' + - 'Attribution notices': 'user-guide/05-attribution_notices.md' + - 'Developer guide': + - 'Overview': 'developer-guide/0-Overview.md' + - 'Development requirements': 'developer-guide/1-Development-requirements.md' + - 'Dependencies install': 'developer-guide/2-Dependencies-install.md' + - 'Build': 'developer-guide/3-Build.md' + - 'Tests (user)': 'developer-guide/4-Tests-user.md' + - 'Tests (developer)': 'developer-guide/4-Tests-dev.md' + - 'Installer creation': 'developer-guide/5-Installer-creation.md' + - 'Continuous Integration': 'developer-guide/continuous-integration.md' + - 'OR-tools integration': 'developer-guide/ortools-integration.md' + - 'Changelog': 'developer-guide/CHANGELOG.md' + - 'External links': + - 'Antares ecosystem': 'https://antares-doc.readthedocs.io' + - 'Antares website': 'https://antares-simulator.org' + - 'RTE website': 'http://www.rte-france.com/' + plugins: - search @@ -66,7 +95,8 @@ extra_css: extra_javascript: - https://code.jquery.com/jquery-3.6.0.min.js - https://polyfill.io/v3/polyfill.min.js?features=es6 - - https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML + - javascripts/mathjax.js + - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js markdown_extensions: - footnotes @@ -80,6 +110,7 @@ markdown_extensions: - admonition - pymdownx.details - pymdownx.superfences - - pymdownx.tabbed + - pymdownx.tabbed: + alternate_style: true -copyright: Copyright © 2007 - 2021 RTE +copyright: Copyright © 2007 - 2024 RTE diff --git a/ortools_tag b/ortools_tag index 898fb20318..fdaa0174f8 100644 --- a/ortools_tag +++ b/ortools_tag @@ -1 +1 @@ -v9.5-rte2.0 \ No newline at end of file +v9.8-rte1.0 \ No newline at end of file diff --git a/readthedocs.yml b/readthedocs.yml index e6c09bb5bd..a10c6735eb 100644 --- a/readthedocs.yml +++ b/readthedocs.yml @@ -1,9 +1,12 @@ version: 2 +build: + os: "ubuntu-20.04" + tools: + python: "3.11" + python: - version: 3.7 install: - requirements: requirements-doc.txt - mkdocs: configuration: mkdocs.yml diff --git a/simtest.json b/simtest.json index 2866454d33..422fd8e3bd 100644 --- a/simtest.json +++ b/simtest.json @@ -1,3 +1,3 @@ { - "version": "v8.7.0" + "version": "v9.2.0a" } diff --git a/sonar-project.properties b/sonar-project.properties index 5e8384525c..bf90dbda19 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,7 +1,7 @@ sonar.projectName=Antares_Simulator sonar.projectKey=AntaresSimulatorTeam_Antares_Simulator sonar.organization=antaressimulatorteam -sonar.projectVersion=8.7.0 +sonar.projectVersion=9.1.0 # ===================================================== # Properties that will be shared amongst all modules @@ -12,9 +12,9 @@ sonar.sources=src sonar.tests=src/tests sonar.sourceEncoding=UTF-8 -sonar.exclusions=src/ext/**,src/tests/** +sonar.exclusions=src/ext/**,src/tests/**,src/ui/** sonar.coverage.exclusions=src/ext/**,src/tests/**,src/analyzer/**,src/distrib/**,src/tools/**,src/ui/** sonar.cfamily.build-wrapper-output=_build/output sonar.coverageReportPaths=coverage.xml -sonar.cfamily.threads=2 +sonar.cfamily.threads=4 diff --git a/src/.clang-format b/src/.clang-format index d6263eff26..0db7cae595 100644 --- a/src/.clang-format +++ b/src/.clang-format @@ -50,16 +50,25 @@ AccessModifierOffset: -4 # argument2) AlignAfterOpenBracket: Align +# If not None, when using initialization for an array of structs aligns the fields into columns. +# Possible values: Left, Right, None +AlignArrayOfStructures: None + # If true, aligns consecutive assignments # -> false: since it can be strange when types with different length are near # each other AlignConsecutiveAssignments: false +AlignConsecutiveBitFields: false + # If true, aligns consecutive declarations # -> false: since it can be strange when types with different length are near # each other AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: false + + # Options for aligning backslashes in escaped newlines # -> Align: escaped newlines as far left as possible # #define A \ @@ -82,6 +91,9 @@ AlignOperands: true # double* c // Comment AlignTrailingComments: true +# We favor breaking between arguments +AllowAllArgumentsOnNextLine: false + # If the function declaration doesn’t fit on a line, allow putting all # parameters of a function declaration onto the next line even if # BinPackParameters is false. @@ -93,10 +105,15 @@ AlignTrailingComments: true # int e); AllowAllParametersOfDeclarationOnNextLine: false +AllowBreakBeforeNoexceptSpecifier: Never + # If true, allows contracting simple braced statements to a single line # -> false: Not allowed for the sake of absolute clarity AllowShortBlocksOnASingleLine: false +# No short instructions on single line +AllowShortEnumsOnASingleLine: false + # If true, short case labels will be contracted to a single line # -> false: Not allowed, only one instruction per line AllowShortCaseLabelsOnASingleLine: false @@ -109,17 +126,18 @@ AllowShortFunctionsOnASingleLine: false # -> false: Not allowed AllowShortIfStatementsOnASingleLine: false +# Exception to our "no single line" rule, +# to allow for lambda-based one liners: +# std::sort(vec.begin(), vec.end(), [](auto v) { return v.a < v.b; }); +AllowShortLambdasOnASingleLine: All + # If true, while (true) continue; can be put on a single line # -> false: Not allowed AllowShortLoopsOnASingleLine: false -# DEPRECATED -# The function definition return type breaking style to use -# -> None: Break after return type automatically -AlwaysBreakAfterDefinitionReturnType: None - # The function declaration return type breaking style to use -# -> None: Break after return type automatically +# -> None: Break after return type automatically, +# according to penalty system AlwaysBreakAfterReturnType: None # If true, always break before multiline string literals @@ -149,8 +167,6 @@ BinPackParameters: false # the same way: break before all braces # See BreakBeforeBraces -# BreakAfterJavaFieldAnnotations: ignored for C++ - # The way to wrap binary operators when expression are too long to hold on a # single line # -> All: Break before operators, so that they can easily be identified at the @@ -191,7 +207,7 @@ BreakStringLiterals: true # Maximum number of characters per line # -> 100: Historically 80 for C++, but quite deprecated today; it is dicutable -# but 100 seemed to be more adequat in our case +# but 100 seemed to be more adequat in our case. ColumnLimit: 100 # A regular expression that describes comments with special meaning, which @@ -204,16 +220,10 @@ CommentPragmas: '^ IWYU pragma:' # -> false: one line per namespace, ugly otherwise CompactNamespaces: false -# If the constructor initializers don’t fit on a line, put each initializer on -# its own line -# -> true -ConstructorInitializerAllOnOneLineOrOnePerLine: true - # The number of characters to use for indentation of constructor initializer # lists -# -> 1 to highlight the brace at the end of the initialization and emphasize -# that it is inside the constructor, but before any instruction -ConstructorInitializerIndentWidth: 1 +# -> 4 Same indentation level as the block instructions +ConstructorInitializerIndentWidth: 4 # Indent width for line continuations # -> 2: So that it is differenciable from other identations @@ -234,41 +244,120 @@ DerivePointerAlignment: false # -> false DisableFormat: false +# No line between access modifier and code +EmptyLineAfterAccessModifier: Never + +# Always one line before public/private/protected +# to clearly separate the following block +EmptyLineBeforeAccessModifier: Always + # If true, clang-format detects whether function calls and definitions are # formatted with one parameter per line # -> false: allways use the convention specified in this file ExperimentalAutoDetectBinPacking: false -# A vector of macros that should be interpreted as foreach loops instead of as -# function calls. -# -> no macro -ForEachMacros: [] - # If true, clang-format adds missing namespace end comments and fixes invalid # existing ones # -> true: add a lot of clarity to these endless braces at the end of a file FixNamespaceComments: true +# A vector of macros that should be interpreted as foreach loops instead of as +# function calls. +# -> no macro +ForEachMacros: [ ] + +# Use include blocks +IncludeBlocks: Regroup + +# First main header, then std libs, then boost, then yuni, then antares +IncludeCategories: + # antares headers with " + - Regex: '^"antares/.*' + Priority: 10 + SortPriority: 10 + CaseSensitive: false + # antares headers with < + - Regex: '^|")' + Priority: 5 + SortPriority: 4 + # yuni headers + - Regex: '^(<|")yuni/.*' + Priority: 5 + CaseSensitive: false + # boost + - Regex: '^(<|")boost/.*' + Priority: 2 + # stdlib + - Regex: '^<.*' + Priority: 1 + CaseSensitive: false + # everything else (targets to be internal lib headers) + - Regex: '.*' + Priority: 15 + CaseSensitive: false + +# Definition of main header of a cpp file +IncludeIsMainRegex: '([-_](test))?$' +IncludeIsMainSourceRegex: '' + + +# public/private/protected not indented +IndentAccessModifiers: false + +IndentCaseBlocks: false + # Indent case labels one level from the switch statement # -> false IndentCaseLabels: false +IndentExternBlock: NoIndent + +IndentGotoLabels: false + # The preprocessor directive indenting style to use # -> None: never indent preprocessor directives IndentPPDirectives: None +IndentRequiresClause: false + # The number of columns to use for indentation # -> 4: Good compromise between visible and limiting additional spaces IndentWidth: 4 # Indent if a function definition or declaration is wrapped after the type -# -> true: to be clear on the fact that this is not another function declaration -IndentWrappedFunctionNames: true +# -> false: so that function name remains at indentation level +IndentWrappedFunctionNames: false + +# We always use braces to identify blocks, even one-lines +InsertBraces: true + +# This is standard +InsertNewlineAtEOF: true + +# Leave integer literals as they are +IntegerLiteralSeparator: + Binary: 0 + Decimal: 0 + Hex: 0 + +# Remove unnecessary empty lines +KeepEmptyLinesAtEOF: false # If true, the empty line at the start of blocks is kept # -> false: this is useless KeepEmptyLinesAtTheStartOfBlocks: false +# Indent lambda according to its signature, to make it clear it relates to it +LambdaBodyIndentation: Signature + +# Ensure consistent use of unix like EOF. +LineEnding: LF + # The maximum number of consecutive empty lines to keep # -> 1: Use comments to differenciate important parts of a big portion of code # (or split it into functions for instance) rather than a big block of @@ -279,27 +368,66 @@ MaxEmptyLinesToKeep: 1 # -> None: Do not add an indentation level NamespaceIndentation: None + +# Each constructor initializer on its own line. +PackConstructorInitializers: Never + +# Penalties are used to decide where to break long lines, +# when multiple alternatives are possible. +# We use a "high" cost for breaking before assignment and first parameter, +# to favor breaking between function parameters and chained methods. +PenaltyBreakAssignment: 1000 +PenaltyBreakBeforeFirstCallParameter: 100 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +# Important to allow method chaining, +# and not breaking assignment or after function parenthesis +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 200 + # Pointer and reference alignment style # -> Left: the type of a variable is at its left, and the * or the & are part of # this type PointerAlignment: Left +# const goes before type +QualifierAlignment: Left + +# & and * go with type, not variable name +ReferenceAlignment: Left + # If true, clang-format will attempt to re-flow comments # -> true: because clang-format does it better than you ReflowComments: true +# No unnecessary ; +RemoveSemicolon: true + +# Concept-related options to be discussed at some point +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope + +# Always have empty lines between function and classes definitions +SeparateDefinitionBlocks: Always + # If true, clang-format will sort #includes # -> false: see coding guidelines -SortIncludes: false +SortIncludes: true # If true, clang-format will sort using declarations -# -> false -SortUsingDeclarations: false +# -> LexicographicNumeric to take into account sub-namespaces +SortUsingDeclarations: LexicographicNumeric # If true, a space is inserted after C style casts # -> false SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false + # If true, a space will be inserted after the ‘template’ keyword # -> false SpaceAfterTemplateKeyword: false @@ -308,10 +436,31 @@ SpaceAfterTemplateKeyword: false # -> true SpaceBeforeAssignmentOperators: true +# "case 1: break;" instead of "case 1 : break;" +SpaceBeforeCaseColon: false + +# Foo foo{ bar }; +SpaceBeforeCpp11BracedList: false + +# Foo::Foo(): a(a) {} +SpaceBeforeCtorInitializerColon: false + +# class Foo: Bar {} +SpaceBeforeInheritanceColon: false + # Defines in which cases to put a space before opening parentheses # -> ControlStatements: Before if/while/for statements SpaceBeforeParens: ControlStatements +# for (auto v: values) {} +SpaceBeforeRangeBasedForLoopColon: false + +# int a[5] +SpaceBeforeSquareBrackets: false + +# void f() {} +SpaceInEmptyBlock: false + # If true, spaces may be inserted into () # -> false SpaceInEmptyParentheses: false @@ -334,9 +483,17 @@ SpacesInCStyleCastParentheses: false # -> false SpacesInContainerLiterals: false +# Minimum one space to separate the start of the comment +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 + # If true, spaces will be inserted after ( and before ) # -> false -SpacesInParentheses: false +# SpacesInParentheses: false + +# Keep previous behaviour with SpacesInParentheses: false +SpacesInParens: Never # If true, spaces will be inserted after [ and before ]. Lambdas or unspecified # size array declarations will not be affected @@ -345,8 +502,7 @@ SpacesInSquareBrackets: false # Format compatible with this standard, e.g. use A > instead of A> # for LS_Cpp03 -# Cpp11 -Standard: Cpp11 +Standard: c++20 # The number of columns used for tab stops # Note: this property is not used since tabs are forbidden (see UseTab) @@ -355,4 +511,4 @@ TabWidth: 8 # The way to use tab characters in the resulting file # -> Never: Allways use spaces -UseTab: Never \ No newline at end of file +UseTab: Never diff --git a/src/CMakeGraphVizOptions.cmake b/src/CMakeGraphVizOptions.cmake new file mode 100644 index 0000000000..285c4aead4 --- /dev/null +++ b/src/CMakeGraphVizOptions.cmake @@ -0,0 +1,3 @@ +set(GRAPHVIZ_GENERATE_PER_TARGET FALSE) +set(GRAPHVIZ_IGNORE_TARGETS "absl.*") +set(GRAPHVIZ_EXTERNAL_LIBS FALSE) \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 077445d3b7..0148e31899 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,15 +1,16 @@ cmake_minimum_required(VERSION 3.14) # FetchContent_MakeAvailable # Version -set(ANTARES_VERSION_HI 8) -set(ANTARES_VERSION_LO 7) +set(ANTARES_VERSION_HI 9) +set(ANTARES_VERSION_LO 1) set(ANTARES_VERSION_REVISION 0) + # Beta release set(ANTARES_BETA 0) set(ANTARES_RC 0) -set(ANTARES_VERSION_YEAR 2023) +set(ANTARES_VERSION_YEAR 2024) project(antares VERSION ${ANTARES_VERSION_HI}.${ANTARES_VERSION_LO}.${ANTARES_VERSION_REVISION}) @@ -35,7 +36,7 @@ include(CheckCXXCompilerFlag) include(CMakeDependentOption) include(FetchContent) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) if (DEFINED VCPKG_ROOT) include(${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake) @@ -66,8 +67,6 @@ execute_process(COMMAND OUTPUT_VARIABLE GIT_SHA1_SHORT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) -string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE) - # Build Configuration set(ANTARES_TARGET "${CMAKE_BUILD_TYPE}") @@ -143,7 +142,7 @@ OMESSAGE("") OMESSAGE("") #Display Build Configuration (debug or release) -if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") +if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") OMESSAGE("{antares} Build Configuration: RELEASE") else() OMESSAGE("{antares} Build Configuration: DEBUG") @@ -152,7 +151,7 @@ endif() # # Yuni Framework # -if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") +if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(YUNI_TARGET_MODE "release") set(ANTARES_VERSION_TARGET "release") else() @@ -184,76 +183,26 @@ message(STATUS "Build antares tools: ${BUILD_TOOLS}") option(BUILD_ORTOOLS "Build OR-Tools" OFF) message(STATUS "Build OR-Tools: ${BUILD_ORTOOLS}") -option(BUILD_MINIZIP "Build minizip" OFF) -message(STATUS "Build minizip: ${BUILD_MINIZIP}") +option(WITH_ANTLR4 "With antlr4" OFF) +message(STATUS "With antlr4: ${WITH_ANTLR4}") -#Define install directory -if (NOT DEPS_INSTALL_DIR) - SET(DEPS_INSTALL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../rte-antares-deps-${CMAKE_BUILD_TYPE}) +option(WITH_YAMLCPP "With yaml-cpp" OFF) +message(STATUS "With yaml-cpp: ${WITH_YAMLCPP}") -else() - if(NOT IS_ABSOLUTE ${DEPS_INSTALL_DIR}) - SET(DEPS_INSTALL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../${DEPS_INSTALL_DIR}) - endif() +option(BUILD_MERSENNE_TWISTER_PYBIND11 "Build pybind11 bindings for Mersenne-Twister" OFF) +if (${BUILD_MERSENNE_TWISTER_PYBIND11}) + find_package(pybind11 REQUIRED) endif() - -# Add DEPS_INSTALL_DIR with antares-xpansion CMAKE_BUILD_TYPE -if ("${CMAKE_BUILD_TYPE}" STREQUAL "release") - - string(REPLACE ${CMAKE_BUILD_TYPE} Release - DEPS_INSTALL_DIR_XPANSION - ${DEPS_INSTALL_DIR}) - - list(APPEND CMAKE_PREFIX_PATH ${DEPS_INSTALL_DIR_XPANSION}) - -elseif("${CMAKE_BUILD_TYPE}" STREQUAL "debug") - - string(REPLACE ${CMAKE_BUILD_TYPE} Debug - DEPS_INSTALL_DIR_XPANSION - ${DEPS_INSTALL_DIR}) - - list(APPEND CMAKE_PREFIX_PATH ${DEPS_INSTALL_DIR_XPANSION}) - -endif() - -list(APPEND CMAKE_PREFIX_PATH ${DEPS_INSTALL_DIR}) -message(STATUS "CMAKE_PREFIX_PATH : ${CMAKE_PREFIX_PATH}") - -# Build Needed dependencies -add_subdirectory(antares-deps) - -#Add needed definition in case of external dependencies compilation -include (antares-deps/cmake/additionnal-definitions.cmake) - #Boost header libraries find_package(Boost REQUIRED) -#TODO : Add ZLIB if VCPKG used why is this needed -if (VCPKG_TOOLCHAIN) - #zlib - find_package(ZLIB REQUIRED) -endif() - #Sirius solver if(POLICY CMP0074) cmake_policy(SET CMP0074 NEW) endif() -if (VCPKG_TOOLCHAIN) - list(APPEND CMAKE_PREFIX_PATH "${sirius_solver_ROOT}") - list(APPEND CMAKE_PREFIX_PATH "${ortools_ROOT}") -endif() - -find_package(sirius_solver) - -if (NOT sirius_solver_FOUND) - message (FATAL_ERROR "Sirius solver not found. Sirius solver can be compiled with -DBUILD_sirius=ON or you can specify previous dependency install directory with -DCMAKE_PREFIX_PATH or -DDEPS_INSTALL_DIR") -endif() - -#gflags needed for ortools -set(GFLAGS_USE_TARGET_NAMESPACE TRUE) -find_package(gflags) +find_package(sirius_solver REQUIRED) find_package(ortools) if(NOT ortools_FOUND OR BUILD_ORTOOLS) @@ -269,7 +218,8 @@ message(STATUS "OR-Tools tag ${ORTOOLS_TAG}") set(BUILD_SAMPLES "OFF" CACHE INTERNAL "") set(BUILD_FLATZINC "OFF" CACHE INTERNAL "") set(BUILD_EXAMPLES "OFF" CACHE INTERNAL "") - set(USE_SCIP "OFF" CACHE INTERNAL "") + set(USE_SCIP "ON" CACHE INTERNAL "") + set(USE_GLPK "ON" CACHE INTERNAL "") # We build OR-Tools as a static lib. Cyclic dependencies are detected # without this flag. set(BUILD_SHARED_LIBS "OFF" CACHE INTERNAL "") @@ -280,27 +230,17 @@ message(STATUS "OR-Tools tag ${ORTOOLS_TAG}") FetchContent_MakeAvailable(ortools) endif() -find_package(minizip) - -if(NOT minizip_FOUND OR BUILD_MINIZIP) - # Repository + tag - set(MZ_REPOSITORY "https://github.com/zlib-ng/minizip-ng.git") - set(MZ_TAG "3.0.7") - # CMake flags - set(MZ_LZMA "OFF" CACHE INTERNAL "") - set(MZ_ZSTD "OFF" CACHE INTERNAL "") - set(MZ_BZIP2 "OFF" CACHE INTERNAL "") - set(MZ_PKCRYPT "OFF" CACHE INTERNAL "") - set(MZ_WZAES "OFF" CACHE INTERNAL "") - set(MZ_OPENSSL "OFF" CACHE INTERNAL "") - set(MZ_ICONV "OFF" CACHE INTERNAL "") - - FetchContent_Declare(minizip - GIT_REPOSITORY ${MZ_REPOSITORY} - GIT_TAG ${MZ_TAG}) - - FetchContent_MakeAvailable(minizip) -endif() +find_package(minizip-ng QUIET) +if (minizip-ng_FOUND) + add_library(MINIZIP::minizip ALIAS MINIZIP::minizip-ng) +else () + find_package(minizip) + if (minizip_FOUND) + message (STATUS "Found minizip (not minizip-ng).") + else () + message (FATAL_ERROR "Minizip not found.") + endif () +endif () #wxWidget not needed for all library find is done in ui CMakeLists.txt if (VCPKG_TOOLCHAIN AND NOT BUILD_wxWidgets) @@ -311,9 +251,11 @@ endif() # TODO : review Standard Settings include(cmake/common-settings.cmake) +add_subdirectory(config) + # Configure config.h with current ANTARES version -configure_file("config.h.cmake" "${CMAKE_CURRENT_BINARY_DIR}/config.h") -configure_file("config.h.cmake" "${CMAKE_CURRENT_SOURCE_DIR}/config.h") +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/config/config.h.in" + "${CMAKE_CURRENT_SOURCE_DIR}/config/include/antares/config/config.h") # Yuni Framework configure_file("cmake/ProfileBuild.template.cmake" "ext/yuni/src/ProfileBuild.cmake") @@ -322,6 +264,7 @@ add_subdirectory("ext/yuni/src") OMESSAGE("") # empty line # Sub Directories +add_subdirectory(api) add_subdirectory(libs) #antares-core fswalker if(BUILD_UI) @@ -355,11 +298,11 @@ OMESSAGE("") # Informations for NSIS if(WIN32 OR WIN64) if(MSVC) - if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") + if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(NSIS_TARGET "Release") - else("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") + else() set(NSIS_TARGET "Debug") - endif("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") + endif() set(COMPILER_MARK "v") #set(COMPILER_INCLUDE "vs9") else(MSVC) @@ -436,7 +379,7 @@ else() set(CPACK_PACKAGE_VERSION_MINOR ${ANTARES_VERSION_LO}) set(CPACK_PACKAGE_VERSION_PATCH ${ANTARES_VERSION_REVISION}${ANTARES_VERSION_TAG}) - set(CPACK_DEBIAN_PACKAGE_DEPENDS "libwxgtk3.0-gtk3-0v5") + set(CPACK_DEBIAN_PACKAGE_DEPENDS "libwxgtk3.0-gtk3-0v5 | libwxgtk3.2-dev") set(CPACK_RPM_PACKAGE_REQUIRES "wxGTK3") set(CPACK_RPM_PACKAGE_AUTOREQPROV "0") @@ -448,3 +391,5 @@ endif() # Load packaging facilities. include(CPack) +#Last. We need all target defined +add_subdirectory(packaging) diff --git a/src/analyzer/CMakeLists.txt b/src/analyzer/CMakeLists.txt index 1a3759f1c3..232f363939 100644 --- a/src/analyzer/CMakeLists.txt +++ b/src/analyzer/CMakeLists.txt @@ -9,56 +9,58 @@ include(../cmake/common-settings.cmake) # Le main -Set(SRCS main.cpp - atsp/atsp.h - atsp/atsp.hxx - atsp/atsp.cpp - atsp/load.cpp - atsp/misc.cpp - atsp/preflight.cpp - atsp/correlations.cpp - atsp/cache.cpp - ) +Set(SRCS main.cpp + atsp/atsp.h + atsp/atsp.hxx + atsp/atsp.cpp + atsp/load.cpp + atsp/misc.cpp + atsp/preflight.cpp + atsp/correlations.cpp + atsp/cache.cpp +) -if(WIN32) - file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.o") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.rc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.rc") +if (WIN32) + file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.o") + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.rc.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.rc") - if(MINGW) - # resource compilation for mingw - ADD_CUSTOM_COMMAND(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.o" - COMMAND windres.exe "-I${CMAKE_CURRENT_SOURCE_DIR}" - "-i${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.rc" - -o "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.o") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.o") - else(MINGW) + if (MINGW) + # resource compilation for mingw + ADD_CUSTOM_COMMAND(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.o" + COMMAND windres.exe "-I${CMAKE_CURRENT_SOURCE_DIR}" + "-i${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.rc" + -o "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.o") + SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.o") + else (MINGW) FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/analyzer.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.rc") - endif(MINGW) -endif(WIN32) + SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/analyzer.rc") + endif (MINGW) +endif (WIN32) -add_executable(antares-${ANTARES_PRG_VERSION}-analyzer ${SRCS}) +add_executable(antares-analyzer ${SRCS}) -install(TARGETS antares-${ANTARES_PRG_VERSION}-analyzer EXPORT antares-analyzer DESTINATION bin) +install(TARGETS antares-analyzer EXPORT antares-analyzer DESTINATION bin) INSTALL(EXPORT antares-analyzer - FILE antares-analyzerConfig.cmake - DESTINATION cmake + FILE antares-analyzerConfig.cmake + DESTINATION cmake ) -target_link_libraries(antares-${ANTARES_PRG_VERSION}-analyzer - PRIVATE - yuni-static-core - Antares::args_helper - ${CMAKE_THREADS_LIBS_INIT} - antares-core #local.h - PUBLIC - Antares::study #atsp -> xcast - Antares::sys - ) +target_link_libraries(antares-analyzer + PRIVATE + yuni-static-core + Antares::args_helper + ${CMAKE_THREADS_LIBS_INIT} + antares-core #local.h + Antares::misc + Antares::locale + PUBLIC + Antares::study #atsp -> xcast + Antares::sys +) -import_std_libs(antares-${ANTARES_PRG_VERSION}-analyzer) -executable_strip(antares-${ANTARES_PRG_VERSION}-analyzer) +import_std_libs(antares-analyzer) +executable_strip(antares-analyzer) diff --git a/src/analyzer/atsp/atsp.cpp b/src/analyzer/atsp/atsp.cpp index 73b4fb5b1f..2f990c00c8 100644 --- a/src/analyzer/atsp/atsp.cpp +++ b/src/analyzer/atsp/atsp.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "atsp.h" @@ -38,21 +32,23 @@ const uint ATSP::lonmois[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const uint ATSP::durmois[12] = {744, 672, 744, 720, 744, 720, 744, 744, 720, 744, 720, 744}; const uint ATSP::posmois[12] = {0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016}; -ATSP::ATSP() : - pRoundingCount(), - pRounding80percentCount(), - pRoundingCountTotal(), - HOR(0.92), - pLimitMemory(200 * 1024 * 1024), - pCacheMemoryUsed(), - pAutoClean(false) +ATSP::ATSP(): + pRoundingCount(), + pRounding80percentCount(), + pRoundingCountTotal(), + HOR(0.92), + pLimitMemory(200 * 1024 * 1024), + pCacheMemoryUsed(), + pAutoClean(false) { } ATSP::~ATSP() { for (uint i = 0; i != pArea.size(); ++i) + { delete pArea[i]; + } if (pAutoClean) { @@ -88,23 +84,35 @@ void ATSP::printSummary() const logs.info() << " trimming threshold : " << pRoundOff; if (pUseUpperBound) + { logs.info() << " upper bound : " << pUpperBound; + } else + { logs.info() << " upper bound : (none)"; + } if (pUseLowerBound) + { logs.info() << " lower bound : " << pLowerBound; + } else + { logs.info() << " lower bound : (none)"; + } logs.info() << " memory cache size : " << (pLimitMemory / 1024 / 1024) << "Mo"; logs.info() << " auto-clean : " << (pAutoClean ? "yes" : "no"); logs.info(); if (pArea.size() > 1) + { logs.info() << " " << pArea.size() << " areas to analyze"; + } else + { logs.info() << " 1 area to analyze"; + } for (uint i = 0; i != pArea.size(); ++i) { @@ -141,19 +149,25 @@ bool ATSP::writeMoments() const for (uint j = 0; j < 12; ++j) { for (uint k = 0; k < 4; ++k) + { f << "MONTH " << (j + 1) << '\t'; + } } f << "\n\t"; for (uint j = 0; j < 12; ++j) + { f << " EXPEC\t STAND\t SKEWN\t KURTO\t"; + } f << '\n'; for (uint i = 0; i < pArea.size(); ++i) { const AreaInfo& info = *(pArea[i]); if (!info.enabled) + { continue; + } f << info.name << '\t'; const MomentCentrSingle& moment = moments_centr_net[i]; @@ -163,7 +177,9 @@ bool ATSP::writeMoments() const const double* m = moment.data[j]; for (uint k = 0; k < 4; ++k) + { f << m[k] << '\t'; + } } f << '\n'; } @@ -180,13 +196,16 @@ bool ATSP::cachePreload(unsigned index, { options = Matrix<>::optImmediate | Matrix<>::optFixedSize, }; + if (pCacheMatrix[index].loadFromCSVFile(filename, NBS, height, options, &buffer)) { pCacheLastValidIndex = index + 1; return true; } else + { pCacheMatrix[index].clear(); + } return false; } diff --git a/src/analyzer/atsp/atsp.h b/src/analyzer/atsp/atsp.h index 19a4cb304b..c64b2a5f43 100644 --- a/src/analyzer/atsp/atsp.h +++ b/src/analyzer/atsp/atsp.h @@ -1,37 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __PREPROCESSOR_ATSP_H__ #define __PREPROCESSOR_ATSP_H__ -#include #include + +#include #include -#include + #include +#include namespace Antares { @@ -85,12 +81,14 @@ class ATSP final { double data[12][4]; }; + using MomentCentr = std::vector; struct HiddenHoursSingle { int data[12][24]; }; + using HiddenHours = std::vector; private: @@ -259,6 +257,7 @@ class ATSP final ** Ce seuil n'est pas utilise quand l'analyse porte sur une loi normale */ const double HOR; // 0.92 by default + enum { //! nombre de valeurs d'autocorrelation calculees (de X0-X0 à X0-X119) @@ -281,6 +280,7 @@ class ATSP final static const uint lonmois[12]; static const uint durmois[12]; static const uint posmois[12]; + enum { durjour = 24 diff --git a/src/analyzer/atsp/atsp.hxx b/src/analyzer/atsp/atsp.hxx index 29015ba000..869be2adb9 100644 --- a/src/analyzer/atsp/atsp.hxx +++ b/src/analyzer/atsp/atsp.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __PREPROCESSOR_ATSP_HXX__ #define __PREPROCESSOR_ATSP_HXX__ diff --git a/src/analyzer/atsp/cache.cpp b/src/analyzer/atsp/cache.cpp index 8179c57c71..07ecd37803 100644 --- a/src/analyzer/atsp/cache.cpp +++ b/src/analyzer/atsp/cache.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "atsp.h" @@ -43,13 +37,15 @@ void ATSP::cacheCreate() void ATSP::cacheDestroy() { delete[] pCacheMatrix; - pCacheMatrix = NULL; + pCacheMatrix = nullptr; } void ATSP::cacheClear() { for (uint i = 0; i != pCacheLastValidIndex; ++i) + { pCacheMatrix[i].clear(); + } pCacheMemoryUsed = sizeof(Matrix<>) * pArea.size(); pCacheLastValidIndex = 0; } diff --git a/src/analyzer/atsp/correlations.cpp b/src/analyzer/atsp/correlations.cpp index ae9db4a0c0..af3c800d5c 100644 --- a/src/analyzer/atsp/correlations.cpp +++ b/src/analyzer/atsp/correlations.cpp @@ -1,33 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "atsp.h" #include -#include "../solver/misc/matrix-dp-make.h" +#include +#include "antares/solver/misc/matrix-dp-make.h" + +#include "atsp.h" using namespace Yuni; @@ -116,17 +112,23 @@ bool ATSP::computeMonthlyCorrelations() do { if (pCacheMemoryUsed + sizePerMatrix > pLimitMemory) + { break; + } --iZ; const uint i = mapping[iZ]; const String& folder = folderPerArea[i]; pStr.clear() << folder << SEP << "userfile-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; if (!cachePreload(i, pStr, durmois[m], buffer)) + { break; + } } while (iZ); } @@ -141,7 +143,9 @@ bool ATSP::computeMonthlyCorrelations() { pStr.clear() << folder << SEP << "userfile-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; if (!SERIE_N.loadFromCSVFile(pStr, NBS, @@ -171,14 +175,18 @@ bool ATSP::computeMonthlyCorrelations() { pStr.clear() << folderJ << SEP << "userfile-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; if (!SERIE_P.loadFromCSVFile(pStr, NBS, durmois[m], Matrix<>::optImmediate | Matrix<>::optFixedSize, &buffer)) + { continue; + } } double coeff = 0.; @@ -247,14 +255,18 @@ bool ATSP::computeMonthlyCorrelations() Matrix<>::ColumnType& outcol = CORR_YNP.entry[i]; const Matrix<>::ColumnType& col = CORR_MNP.entry[i]; for (uint j = 0; j < realAreaCount; ++j) + { outcol[j] += col[j] / 12.; + } } for (uint i = 0; i < realAreaCount; ++i) { Matrix<>::ColumnType& outcol = CORR_YNPZ.entry[i]; const Matrix<>::ColumnType& col = CORR_MNPZ.entry[i]; for (uint j = 0; j < realAreaCount; ++j) + { outcol[j] += col[j] / 12.; + } } // Rounding monthly correlation coefficients (matrix trimming) -zero -excluded @@ -263,7 +275,7 @@ bool ATSP::computeMonthlyCorrelations() auto& column = CORR_MNP[i]; for (uint j = 0; j < i; ++j) { - if (Math::Abs(column[j]) < RTZ) + if (std::abs(column[j]) < RTZ) { column[j] = 0.; CORR_MNP[j][i] = 0.; @@ -286,7 +298,7 @@ bool ATSP::computeMonthlyCorrelations() auto& column = CORR_MNPZ[i]; for (uint j = 0; j < i; ++j) { - if (Math::Abs(column[j]) < RTZ) + if (std::abs(column[j]) < RTZ) { column[j] = 0.; CORR_MNPZ[j][i] = 0.; @@ -308,21 +320,29 @@ bool ATSP::computeMonthlyCorrelations() pStr.clear() << pTemp << SEP << tsName << SEP << "origin-corr-zero_in-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; CORR_MNPZ.saveToCSVFile(pStr); // Writing the monthly correlation coefficients, excluding zeroes, before sdp check pStr.clear() << pTemp << SEP << tsName << SEP << "origin-corr-zero_no-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; CORR_MNP.saveToCSVFile(pStr); // Converting original matrix with zero signal into an admissible matrix resultNDP.zero(); - shrink = Solver::MatrixDPMake( - tmpNDP.entry, CORR_MNPZ.entry, resultNDP.entry, ID.entry, ID.width, tmpArray); + shrink = Solver::MatrixDPMake(tmpNDP.entry, + CORR_MNPZ.entry, + resultNDP.entry, + ID.entry, + ID.width, + tmpArray); if (shrink < 1.) { if (shrink <= -1.) @@ -341,7 +361,9 @@ bool ATSP::computeMonthlyCorrelations() for (uint y = 1; y < resultNDP.height; ++y) { for (uint x = 0; x < y; ++x) + { resultNDP[x][y] = resultNDP[y][x]; + } } for (uint i = 1; i < CORR_MNPZ.width; ++i) { @@ -366,8 +388,12 @@ bool ATSP::computeMonthlyCorrelations() // Note : this default code should be replaced by proper eigen value // analysis (see Higham 2002 / Strabic 2016) { - shrink = Solver::MatrixDPMake( - tmpNDP.entry, CORR_MNP.entry, resultNDP.entry, ID.entry, ID.width, tmpArray); + shrink = Solver::MatrixDPMake(tmpNDP.entry, + CORR_MNP.entry, + resultNDP.entry, + ID.entry, + ID.width, + tmpArray); if (shrink <= -1.) { logs.error() << "invalid data, can not be processed"; @@ -392,12 +418,16 @@ bool ATSP::computeMonthlyCorrelations() for (uint y = 1; y < resultNDP.height; ++y) { for (uint x = 0; x < y; ++x) + { resultNDP[x][y] = resultNDP[y][x]; + } } pStr.clear() << pTemp << SEP << tsName << SEP << "correlation-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; resultNDP.saveToCSVFile(pStr); } @@ -420,7 +450,7 @@ bool ATSP::computeMonthlyCorrelations() auto& column = CORR_YNP[i]; for (uint j = 0; j < i; ++j) { - if (Math::Abs(column[j]) < RTZ) + if (std::abs(column[j]) < RTZ) { column[j] = 0.; CORR_YNP[j][i] = 0.; @@ -443,7 +473,7 @@ bool ATSP::computeMonthlyCorrelations() auto& column = CORR_YNPZ[i]; for (uint j = 0; j < i; ++j) { - if (Math::Abs(column[j]) < RTZ) + if (std::abs(column[j]) < RTZ) { column[j] = 0.; CORR_YNPZ[j][i] = 0.; @@ -470,8 +500,12 @@ bool ATSP::computeMonthlyCorrelations() // Converting original matrix without zero signal into an admissible matrix - shrink = Solver::MatrixDPMake( - tmpNDP.entry, CORR_YNPZ.entry, resultNDP.entry, ID.entry, ID.width, tmpArray); + shrink = Solver::MatrixDPMake(tmpNDP.entry, + CORR_YNPZ.entry, + resultNDP.entry, + ID.entry, + ID.width, + tmpArray); if (shrink < 1.) { if (shrink <= -1.) @@ -490,7 +524,9 @@ bool ATSP::computeMonthlyCorrelations() for (uint y = 1; y < resultNDP.height; ++y) { for (uint x = 0; x < y; ++x) + { resultNDP[x][y] = resultNDP[y][x]; + } } for (uint i = 1; i < CORR_YNPZ.width; ++i) { @@ -501,16 +537,24 @@ bool ATSP::computeMonthlyCorrelations() } // Converting original matrix without zero signal into an admissible matrix - shrink = Solver::MatrixDPMake( - tmpNDP.entry, CORR_YNP.entry, resultNDP.entry, CORR_YNPZ.entry, CORR_YNPZ.width, tmpArray); + shrink = Solver::MatrixDPMake(tmpNDP.entry, + CORR_YNP.entry, + resultNDP.entry, + CORR_YNPZ.entry, + CORR_YNPZ.width, + tmpArray); if (shrink < 1.) { if (shrink <= -1.) // CORR_YNP is too close to sdp boundary, shrink CORR_YNP instead // Note : this default code should be replaced by proper eigen value // analysis (see Higham 2002 / Strabic 2016) { - shrink = Solver::MatrixDPMake( - tmpNDP.entry, CORR_YNP.entry, resultNDP.entry, ID.entry, ID.width, tmpArray); + shrink = Solver::MatrixDPMake(tmpNDP.entry, + CORR_YNP.entry, + resultNDP.entry, + ID.entry, + ID.width, + tmpArray); if (shrink <= -1.) { logs.error() << "invalid data, can not be processed"; @@ -533,7 +577,9 @@ bool ATSP::computeMonthlyCorrelations() for (uint y = 1; y < resultNDP.height; ++y) { for (uint x = 0; x < y; ++x) + { resultNDP[x][y] = resultNDP[y][x]; + } } // Annual correlation coefficients @@ -565,7 +611,7 @@ bool ATSP::computeMonthlyCorrelations() const auto& col = resultNDP[iZ]; for (uint jZ = iZ + 1; jZ < realAreaCount; ++jZ) { - if (not Math::Zero(col[jZ])) + if (!Utils::isZero(col[jZ])) { const uint j = mapping[jZ]; f << pArea[i]->name << '%' << pArea[j]->name << " = " << col[jZ] << '\n'; @@ -580,7 +626,9 @@ bool ATSP::computeMonthlyCorrelations() { pStr.clear() << pTemp << SEP << tsName << SEP << "correlation-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; if (not CORR_MNP.loadFromCSVFile(pStr, @@ -599,7 +647,7 @@ bool ATSP::computeMonthlyCorrelations() const auto& col = CORR_MNP.entry[iZ]; for (uint jZ = iZ + 1; jZ < realAreaCount; ++jZ) { - if (not Math::Zero(col[jZ])) + if (!Utils::isZero(col[jZ])) { const uint j = mapping[jZ]; f << pArea[i]->name << '%' << pArea[j]->name << " = " << col[jZ] @@ -625,7 +673,9 @@ bool ATSP::computeMonthlyCorrelations() } } else + { logs.error() << "Impossible to create " << pStr; + } } // removing the mapping list diff --git a/src/analyzer/atsp/load.cpp b/src/analyzer/atsp/load.cpp index f4eb43941a..b23f86f551 100644 --- a/src/analyzer/atsp/load.cpp +++ b/src/analyzer/atsp/load.cpp @@ -1,32 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "atsp.h" #include -#include "../../config.h" +#include "antares/config/config.h" + +#include "atsp.h" using namespace Yuni; @@ -59,12 +54,12 @@ bool ATSP::loadFromINIFile(const String& filename) CString<50, false> key; CString<50, false> value; - for (section = ini.firstSection; section != NULL; section = section->next) + for (section = ini.firstSection; section; section = section->next) { if (section->name == ".general") { IniFile::Property* p = section->firstProperty; - for (; p != NULL; p = p->next) + for (; p; p = p->next) { key = p->key; key.toLower(); @@ -87,23 +82,33 @@ bool ATSP::loadFromINIFile(const String& filename) if (key == "target") { if (value == "load") + { pTimeseries = Data::timeSeriesLoad; + } else if (value == "solar") + { pTimeseries = Data::timeSeriesSolar; + } else if (value == "wind") + { pTimeseries = Data::timeSeriesWind; + } continue; } if (key == "width") { if (not value.to(pTimeseriesCount)) + { logs.error() << "impossible to read the number of timeseries"; + } continue; } if (key == "height") { if (not value.to(pMHeight)) + { logs.error() << "impossible to read the height"; + } continue; } if (key == "medium-term-autocorrelation") @@ -154,7 +159,9 @@ bool ATSP::loadFromINIFile(const String& filename) pLimitMemory *= 1024u * 1024u; } else + { pLimitMemory *= 1024u * 1024u; + } continue; } if (key == "clean") @@ -173,7 +180,7 @@ bool ATSP::loadFromINIFile(const String& filename) info->distribution = Data::XCast::dtBeta; IniFile::Property* p = section->firstProperty; - for (; p != NULL; p = p->next) + for (; p; p = p->next) { key = p->key; key.toLower(); @@ -219,7 +226,9 @@ bool ATSP::loadFromINIFile(const String& filename) } if (!checkStudyVersion()) + { return false; + } logs.info() << "Target study: " << pStudyFolder; @@ -297,29 +306,22 @@ bool ATSP::loadFromINIFile(const String& filename) bool ATSP::checkStudyVersion() const { - auto v = Data::StudyTryToFindTheVersion(pStudyFolder); - switch (v) + auto v = Data::StudyHeader::tryToFindTheVersion(pStudyFolder); + if (v == Data::StudyVersion::unknown()) { - case Data::versionUnknown: - { - logs.error() << "The folder is not a study"; + logs.error() << "Couldn't indentify the study version, is the folder a correct study ?"; return false; } - case Data::versionFutur: + if (v > Data::StudyVersion::latest()) { logs.error() << "The format of the study folder requires a more recent version of Antares"; return false; } - default: + if (v < Data::StudyVersion::latest()) { - if ((uint)v != (uint)Data::versionLatest) - { - logs.error() << "The study folder must be upgraded from v" << Data::VersionToCStr(v) - << " to v" - << Data::VersionToCStr(static_cast(Data::versionLatest)); - return false; - } - } + logs.error() << "The study folder must be upgraded from v" << v.toString() << " to v" + << Data::StudyVersion::latest().toString(); + return false; } return true; } diff --git a/src/analyzer/atsp/misc.cpp b/src/analyzer/atsp/misc.cpp index 4498842325..cfbe8f7189 100644 --- a/src/analyzer/atsp/misc.cpp +++ b/src/analyzer/atsp/misc.cpp @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "atsp.h" #include -#include +#include + +#include "atsp.h" using namespace Yuni; @@ -51,7 +46,9 @@ void ATSP::roundMatrixValues(Matrix<>& m) ++pRoundingCount; } if (src[y] > pUpperBound80percent) + { ++pRounding80percentCount; + } } } pRoundingCountTotal += m.width * m.height; @@ -86,7 +83,9 @@ void ATSP::Extrait_bloc(Matrix<>& out, auto& outcol = out.entry[j]; const auto& srccol = MTRX.entry[j + indcol]; for (uint i = 0; i < nblig; ++i) + { outcol[i] = srccol[i + indlig]; + } } } @@ -99,7 +98,9 @@ void ATSP::Colonne_moyenne(double* out, const Matrix<>& MTRX, uint nblig, uint n { d = 0.; for (uint j = 0; j < nbcol; ++j) + { d += MTRX[j][i]; + } out[i] = d / nbcol; } } @@ -116,9 +117,13 @@ void ATSP::Mtrx_bound(double& rmin, double& rmax, const Matrix<>& MTRX, uint nbl for (uint i = 0; i < nblig; ++i) { if (col[i] > rmax) + { rmax = col[i]; + } if (col[i] < rmin) + { rmin = col[i]; + } } } } @@ -129,7 +134,9 @@ void ATSP::Mtrx_abs(Matrix<>& out, const Matrix<>& MTRX, uint nblig, uint nbcol) for (uint j = 0; j < nbcol; ++j) { for (uint i = 0; i < nblig; ++i) - out[j][i] = Math::Abs(MTRX[j][i]); + { + out[j][i] = std::abs(MTRX[j][i]); + } } } @@ -138,7 +145,9 @@ double ATSP::Moyenne_generale(double* A, uint nblig) { double x = 0.; for (uint i = 0; i < nblig; ++i) + { x += A[i]; + } return x / nblig; } @@ -160,14 +169,18 @@ void ATSP::Extrait_col(double* out, const Matrix<>& MTRX, uint nblig, uint indco { const Matrix<>::ColumnType& col = MTRX.entry[indcol]; for (uint i = 0; i < nblig; ++i) + { out[i] = col[i]; + } } // met dans A le carre de B void ATSP::Square(double* A, const double* B, uint nblig) { for (uint i = 0; i < nblig; ++i) + { A[i] = B[i] * B[i]; + } } // met (B- le scalaire x) dans A @@ -178,7 +191,9 @@ void ATSP::Retranche_scalaire(Matrix<>& A, const Matrix<>& B, double x, uint nbl const Matrix<>::ColumnType& src = B.entry[j]; auto& out = A.entry[j]; for (uint i = 0; i < nblig; ++i) + { out[i] = src[i] - x; + } } } @@ -191,7 +206,9 @@ void ATSP::Divise_scalaire(Matrix<>& A, const Matrix<>& B, double x, uint nblig, auto& out = A.entry[j]; for (uint i = 0; i < nblig; ++i) + { out[i] = src[i] / x; + } } } @@ -199,21 +216,27 @@ void ATSP::Divise_scalaire(Matrix<>& A, const Matrix<>& B, double x, uint nblig, void ATSP::Cube(double* A, const double* B, uint nblig) { for (uint i = 0; i < nblig; ++i) + { A[i] = B[i] * B[i] * B[i]; + } } // met dans A B^4 void ATSP::Dsquare(double* A, const double* B, uint nblig) { for (uint i = 0; i < nblig; ++i) + { A[i] = B[i] * B[i] * B[i] * B[i]; + } } // range dans OUT nblig elements de MTRX pris a partir de l'indice indlig void ATSP::Extrait_seg(double* out, const double* src, uint nblig, uint indlig) { for (uint i = 0; i < nblig; ++i) + { out[i] = src[i + indlig]; + } } // retourne le coefficient de corrélation entre A et B (retourne 999 si paramètre "code" aberrant) @@ -269,17 +292,23 @@ double ATSP::Correlation(double* A, return 999.; // should never happen } - if (Math::Abs(sigma_A) < 1e-4 && Math::Abs(sigma_B) < 1e-4) + if (std::abs(sigma_A) < 1e-4 && std::abs(sigma_B) < 1e-4) + { return 1.; - if (Math::Abs(sigma_A) < 1e-4 || Math::Abs(sigma_B) < 1e-4) + } + if (std::abs(sigma_A) < 1e-4 || std::abs(sigma_B) < 1e-4) + { return 0.; + } double rho = 0.; if (code == 1) { for (uint i = 0; i < nblig; ++i) + { rho += (A[i] - expec_A) * (B[i] - expec_B); + } rho /= nblig; rho /= sigma_A; @@ -290,7 +319,9 @@ double ATSP::Correlation(double* A, // if (code == 0) for (uint i = 0; i < nblig; ++i) + { rho += A[i] * B[i]; + } rho /= nblig; rho -= expec_A * expec_B; @@ -299,9 +330,13 @@ double ATSP::Correlation(double* A, } if (rho > 1) + { rho = 1; + } if (rho < -1) + { rho = -1; + } return rho; } @@ -332,14 +367,18 @@ double ATSP::autocorr_average(int H, int M, double R) for (int i = 1; i < M + 1; ++i) { for (int j = 1 + H; j < M + 1 + H; ++j) + { x += pow(R, abs(j - i)); + } } double y = 0.; for (int i = 1; i < M + 1; ++i) { for (int j = i + 1; j < M + 1; ++j) + { y += pow(R, j - i); + } } y *= 2.; @@ -374,9 +413,13 @@ void ATSP::Analyse_auto(double* A, // check thresholds aum & auc if (aum <= double(0.01)) + { aum = double(0.01); + } if (auc < aum) + { auc = aum; + } // 1 address special cases @@ -400,7 +443,9 @@ void ATSP::Analyse_auto(double* A, { theta = -log(A[nblig - 1]) / double(nblig - 1); if (theta < double(0.0001)) + { theta = 0; + } mu = 1; return; } @@ -436,19 +481,29 @@ void ATSP::Analyse_auto(double* A, { // on trouve une bonne estimation pour TM if (A[l] >= aum && A[l + 1] < aum) + { TM = l; + } // on trouve une bonne estimation pour TC if (A[l] >= auc && A[l + 1] < auc) + { TC = l; + } // on cherchera ensuite une valeur de mu comprise entre 1 et max_mu if (A[l] >= hor && A[l + 1] < hor) + { max_mu = l + 1; + } } if (max_mu > 24) + { max_mu = 24; + } if (max_mu == 0) + { max_mu = 1; + } // both thresholds crossed at the same time @@ -494,9 +549,13 @@ void ATSP::Analyse_auto(double* A, { R = (top + bot) / 2; if (autocorr_average(TM, M, R) >= A[TM]) + { top = R; + } else + { bot = R; + } } // on a converge vers R tq autocorr_average(TM,M,R) = A[TM] @@ -533,6 +592,7 @@ double ATSP::GammaEuler(double z) { g = 6, }; + double x; const double t = z + double(g) + 0.5; double rho; @@ -600,9 +660,9 @@ bool ATSP::Probab_density_funct(double L, C = 0.; D = 1.; - if (Math::Abs(S) < 1e-40) + if (std::abs(S) < 1e-40) { - // double fe = Math::Abs(E); + // double fe = std::abs(E); // S = (fe < 1e-40) ? (1e-4) : (1e-4 / fe); S = 0; } @@ -612,7 +672,9 @@ bool ATSP::Probab_density_funct(double L, case Data::XCast::dtUniform: { if (S < 0.) + { return false; + } // au lieu de prendre simplement C=L et D=U, on procede // par la methode des moments C = (2. * E - 3.4641 * S) / 2.; @@ -628,13 +690,17 @@ bool ATSP::Probab_density_funct(double L, case Data::XCast::dtBeta: { if (U <= L) + { return false; + } C = L; D = U; double V = E - C; double W = D - C; if (S == W) + { return false; + } A = (V / W) * (V / W * (1. - (V / W)) / ((S * S) / (W * W)) - 1.); B = (1. - V / W) * (V / W * (1. - (V / W)) / ((S * S) / (W * W)) - 1.); @@ -644,7 +710,9 @@ bool ATSP::Probab_density_funct(double L, case Data::XCast::dtNormal: { if (S < 0.) + { return false; + } C = 0.; D = 0.; A = E; @@ -655,14 +723,20 @@ bool ATSP::Probab_density_funct(double L, case Data::XCast::dtWeibullShapeA: { if (S < 0.) + { return false; + } if (E == 0 || S == 0) + { return false; + } // pour une loi de weibull de paramètre a>=1, le calage n'est possible que si // S/E < 1 if (S / E > 1.) + { return false; + } double bot = 1.; double top = 50.; @@ -683,9 +757,13 @@ bool ATSP::Probab_density_funct(double L, double niveau = GammaEuler(1. + 2. / a) - g; niveau /= g; if (niveau >= cible) + { bot = a; + } else + { top = a; + } } A = a; B = E / GammaEuler(1. + 1. / a); @@ -697,10 +775,14 @@ bool ATSP::Probab_density_funct(double L, case Data::XCast::dtGammaShapeA: { if (S <= 0.) + { return false; + } if (E == 0.) + { return false; + } C = 0; @@ -723,13 +805,17 @@ bool ATSP::Probab_density_funct(double L, double ATSP::Standard_shrinkage(int M, double R) { if (R < 0.) // ceci ne doit jamais se produire + { R = 0.; + } double x = 0.; for (int i = 1; i < M + 1; ++i) { for (int j = i + 1; j < M + 1; ++j) + { x += pow(R, j - i); + } } x *= 2; diff --git a/src/analyzer/atsp/preflight.cpp b/src/analyzer/atsp/preflight.cpp index fa41b6e681..359d481182 100644 --- a/src/analyzer/atsp/preflight.cpp +++ b/src/analyzer/atsp/preflight.cpp @@ -1,34 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "atsp.h" -#include #include +#include + +#include "atsp.h" + using namespace Yuni; #define SEP Yuni::IO::Separator @@ -59,7 +55,9 @@ bool ATSP::preflight() } } if (error) + { return false; + } } logs.info(); // empty line @@ -73,7 +71,9 @@ bool ATSP::preflight() logs.info() << " The area '" << pArea[i]->name << "' has been removed"; } else + { ++pEnabledAreaCount; + } } // moments @@ -113,10 +113,14 @@ bool ATSP::preflight(const uint areaIndex) // Reading the matrix file for the current area Matrix<> MTRX; if (!MTRX.loadFromCSVFile(info.filename, 1, pMHeight, Matrix<>::optImmediate)) + { return false; + } // Shrinking the matrix if required if (MTRX.width > pTimeseriesCount) + { MTRX.resizeWithoutDataLost(pTimeseriesCount, MTRX.height); + } else { if (MTRX.width < pTimeseriesCount) @@ -180,7 +184,9 @@ bool ATSP::preflight(const uint areaIndex) Retranche_mtrx(SERIE_N, buffer_n, durmois[j], NBS); } else + { (void)::memset(buffer_n, 0, sizeof(buffer_n)); + } // On calcule les coefficients horaires de modulation pour le mois courant { @@ -194,17 +200,25 @@ bool ATSP::preflight(const uint areaIndex) { double d = 0; for (uint m = 0; m < lonmois[j]; ++m) + { d += (buffer_p[24 * m + n] / lonmois[j]); + } if (d > maxabsmnth[j]) + { maxabsmnth[j] = d; + } } if (maxabsmnth[j] == 0) + { maxabsmnth[j] = 1; // should never happen + } for (uint n = 0; n < 24; ++n) { double d = 0; for (uint m = 0; m < lonmois[j]; ++m) + { d += (buffer_p[24 * m + n] / lonmois[j]); + } normratios[j][n] = d / maxabsmnth[j]; // at this point the maximum shape factor // of each month is eqaul to 1 } @@ -217,7 +231,9 @@ bool ATSP::preflight(const uint areaIndex) } } if (maxabsmnth[j] > maxabsyear) + { maxabsyear = maxabsmnth[j]; + } } } // each month @@ -235,7 +251,9 @@ bool ATSP::preflight(const uint areaIndex) hiddenhours[j]++; } else + { hidden_hours_month[n] = 0; + } } } // each month @@ -254,7 +272,9 @@ bool ATSP::preflight(const uint areaIndex) for (uint n = 0; n < 24; ++n) { if (cumul > 0.001) + { normratios[j][n] *= double(24 - hiddenhours[j]) / cumul; + } } } // each month } @@ -267,7 +287,9 @@ bool ATSP::preflight(const uint areaIndex) for (uint n = 0; n < 24; ++n) { if (maxabsyear > 0.001) + { normratios[j][n] *= maxabsmnth[j] / maxabsyear; + } } } // each month } @@ -291,12 +313,16 @@ bool ATSP::preflight(const uint areaIndex) Retranche_mtrx(SERIE_N, buffer_n, durmois[j], NBS); } else + { (void)::memset(buffer_n, 0, sizeof(buffer_n)); + } // buffer_n contient la serie de translation et SERIE_N les donnees à normaliser pStr.clear() << folder << SEP << "translation-m"; if (j < 10) + { pStr << '0'; + } pStr << j << ".txt"; // To reduce the size of each file, and consequently speed-up their loading // we will use the standard matrix of Antares, which perform a lot of @@ -304,7 +330,9 @@ bool ATSP::preflight(const uint areaIndex) mtrxWriter.resize(1, durmois[j]); mtrxWriter.pasteToColumn(0, buffer_n); if (!mtrxWriter.saveToCSVFile(pStr, 3)) + { return false; + } // On calcule les valeurs extrêmes du processus brut Mtrx_bound(minimu_brut[j], maximu_brut[j], SERIE_N, durmois[j], NBS); @@ -328,7 +356,9 @@ bool ATSP::preflight(const uint areaIndex) for (uint m = 0; m < NBS; ++m) { if (ratios[mod] != 0) + { SERIE_N.entry[m][n] /= ratios[mod]; + } } } } @@ -339,11 +369,15 @@ bool ATSP::preflight(const uint areaIndex) { pStr.clear() << folder << SEP << "userfile-m"; if (j < 10) + { pStr << '0'; + } pStr << j << ".txt"; SERIE_N.height = durmois[j]; if (!SERIE_N.saveToCSVFile(pStr, 3)) + { return false; + } SERIE_N.height = 744; // restore the previous value } @@ -364,10 +398,14 @@ bool ATSP::preflight(const uint areaIndex) double variance = varian_global - expect_global * expect_global; if (variance < 0.) + { variance = 0.; // si bruit numerique + } double standard = sqrt(variance); if (standard < double(0.0001)) + { standard = 0; + } // calcul des moments d'ordre 3 et 4 double skewne_global = 0.; @@ -423,7 +461,9 @@ bool ATSP::preflight(const uint areaIndex) moments_centr_net_mois[1] += standard * standard; moments_centr_net_mois[1] *= 24. / (24. - double(hiddenhours[j])); if (moments_centr_net_mois[1] < 0) + { moments_centr_net_mois[1] = 0; + } moments_centr_net_mois[1] = sqrt(moments_centr_net_mois[1]); moments_centr_net_mois[2] = 0; @@ -467,16 +507,22 @@ bool ATSP::preflight(const uint areaIndex) for (uint n = 1; n < PRA; ++n) { if (AUTO_ESTIM[n] < 0.006737947) + { AUTO_ESTIM[n] = exp(-5.); + } } // assessment of theta and mu // ignore HOR if variable type is not "Normal" if (info.distribution != Data::XCast::dtNormal) + { Analyse_auto(AUTO_ESTIM, PRA, AUC, AUM, (double)HOR, stocha[4], stocha[5]); + } else + { Analyse_auto(AUTO_ESTIM, PRA, AUC, AUM, 0, stocha[4], stocha[5]); + } // update of exponential decay parameter theta to remove the contribution of hidden hours if (hiddenhours[j] >= 1 && hiddenhours[j] <= 22) @@ -485,13 +531,15 @@ bool ATSP::preflight(const uint areaIndex) stocha[4] *= (24. - double(hiddenhours[j])); stocha[4] /= (24. - (double(hiddenhours[j]) + 1.)); if (stocha[4] > 1.) + { stocha[4] = 1.; + } stocha[4] = -log(stocha[4]); } // si mu>1 il faut majorer l'ecart-type observe sur les valeurs lissees // pour remonter a l'ecart-type des valeurs des series non-lissees - double standard_majore = (Math::Abs(stocha[5] - 1.) < 1e-6) + double standard_majore = (std::abs(stocha[5] - 1.) < 1e-6) ? standard : standard / Standard_shrinkage((int)stocha[5], exp(-stocha[4])); @@ -544,7 +592,9 @@ bool ATSP::preflight(const uint areaIndex) { auto& out = MTRX[x]; for (uint y = 0; y != 12; ++y) + { out[y] = stocha_values[y][x]; + } } // Override MU coefficients, to have mu [1..23], and not 24 @@ -552,7 +602,9 @@ bool ATSP::preflight(const uint areaIndex) for (uint y = 0; y != 12 /*MTRX.height*/; ++y) { if (mu[y] > 23.f) + { mu[y] = 23.f; + } } logs.info() << " Exporting coefficients"; @@ -577,11 +629,15 @@ bool ATSP::preflight(const uint areaIndex) { pStr.clear() << folder << SEP << "translation-m"; if (m < 10) + { pStr << '0'; + } pStr << m << ".txt"; - if (!MTRX.loadFromCSVFile( - pStr, 1, durmois[m], Matrix<>::optImmediate | Matrix<>::optFixedSize)) + if (!MTRX.loadFromCSVFile(pStr, + 1, + durmois[m], + Matrix<>::optImmediate | Matrix<>::optFixedSize)) { logs.error() << "Impossible to reload " << pStr; continue; @@ -599,7 +655,9 @@ bool ATSP::preflight(const uint areaIndex) pStr.clear() << pStudyFolder << SEP << "input" << SEP << tsName << SEP << "prepro" << SEP << info.name << SEP << "translation.txt"; if (!mtrxWriter.saveToCSVFile(pStr)) + { logs.error() << "Impossible to write " << pStr; + } } // Settings for the TS generator (XCast) @@ -609,7 +667,9 @@ bool ATSP::preflight(const uint areaIndex) << info.name << SEP << "settings.ini"; IO::File::Stream f; if (!f.open(pStr, IO::OpenMode::write | IO::OpenMode::truncate)) + { logs.error() << "Impossible to create " << pStr; + } else { // Example : [general] @@ -620,12 +680,15 @@ bool ATSP::preflight(const uint areaIndex) // f << "[general]" << "\ndistribution = " << Data::XCast::DistributionToNameID(info.distribution) - << "\ncapacity = 1" - << "\nconversion = false"; + << "\ncapacity = 1" << "\nconversion = false"; if (info.rawData) + { f << "\ntranslation = never\n"; + } else + { f << "\ntranslation = before-conversion\n"; + } } } diff --git a/src/analyzer/main.cpp b/src/analyzer/main.cpp index 22b7f37ca7..65d9a81e95 100644 --- a/src/analyzer/main.cpp +++ b/src/analyzer/main.cpp @@ -1,40 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include #include + +#include #include -#include -#include "atsp/atsp.h" -#include #include +#include +#include +#include #include -#include + +#include "atsp/atsp.h" using namespace Yuni; using namespace Antares; @@ -82,7 +78,9 @@ static bool OpenLogFilename(const String& optSettings) nowstr[0] = '\0'; } else + { nowstr[result] = '\0'; + } filename << SEP << "analyzer-" << (const char*)nowstr << ".log"; @@ -109,7 +107,9 @@ int main(int argc, char* argv[]) std::set_new_handler(&NotEnoughMemory); if (not memory.initializeTemporaryFolder()) + { return EXIT_FAILURE; + } // locale InitializeDefaultLocale(); @@ -137,7 +137,9 @@ int main(int argc, char* argv[]) options.addFlag(optVersion, 'v', "version", "Print the version and exit"); if (options(argc, argv) == GetOpt::ReturnCode::error) + { return options.errors() ? 1 : 0; + } if (optVersion) { @@ -153,7 +155,9 @@ int main(int argc, char* argv[]) } if (!OpenLogFilename(optSettings)) + { return 1; + } // Starting ! logs.checkpoint() << "Antares Analyzer v" << Antares::VersionToCString(); @@ -179,7 +183,9 @@ int main(int argc, char* argv[]) atsp.printSummary(); // Prepare data if (atsp.preflight()) + { atsp.computeMonthlyCorrelations(); // monthly correlations + } } } diff --git a/src/antares-deps b/src/antares-deps deleted file mode 160000 index 2788a3a409..0000000000 --- a/src/antares-deps +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2788a3a409f3d2b6a04ab90819f3c61bd6a2b282 diff --git a/src/api/API.cpp b/src/api/API.cpp new file mode 100644 index 0000000000..38e9778eab --- /dev/null +++ b/src/api/API.cpp @@ -0,0 +1,116 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "API.h" +#include "antares/solver/simulation/economy_mode.h" +#include "antares/solver/simulation/adequacy_mode.h" +#include "antares/solver/misc/options.h" +#include "antares/infoCollection/StudyInfoCollector.h" +#include "antares/benchmarking/DurationCollector.h" +#include "antares/exception/LoadingError.hpp" +#include +#include + +namespace Antares::API +{ +SimulationResults APIInternal::run(const IStudyLoader& study_loader) +{ + try { + study_ = study_loader.load(); + } catch (const ::Antares::Error::StudyFolderDoesNotExist& e) { + Antares::API::Error err{.reason = e.what()}; + return { + .simulationPath = "", + .antares_problems = {}, + .error = err + }; + } + return execute(); +} + +/** + * @brief The execute method is used to execute the simulation. + * @return SimulationResults object which contains the results of the simulation. + * + * This method is initialy a copy of Application::execute with some modifications hence the apparent dupllication + */ +SimulationResults APIInternal::execute() const +{ + // study_ == nullptr e.g when the -h flag is given + if (!study_) + { + using namespace std::string_literals; + Antares::API::Error err{.reason = "Couldn't create study"s}; + return {.simulationPath{}, .antares_problems{}, .error = err}; + } + + study_->computePThetaInfForThermalClusters(); + + // Only those two fields are used un simulation + Settings settings; + settings.tsGeneratorsOnly = false; + settings.noOutput = false; + + Benchmarking::DurationCollector durationCollector; + Benchmarking::OptimizationInfo optimizationInfo; + auto ioQueueService = std::make_shared(); + ioQueueService->maximumThreadCount(1); + ioQueueService->start(); + auto resultWriter = Solver::resultWriterFactory( + study_->parameters.resultFormat, study_->folderOutput, ioQueueService, durationCollector); + SimulationObserver simulationObserver; + // Run the simulation + switch (study_->runtime->mode) + { + case Data::SimulationMode::Economy: + case Data::SimulationMode::Expansion: + Solver::runSimulationInEconomicMode(*study_, + settings, + durationCollector, + *resultWriter, + optimizationInfo, + simulationObserver); + break; + case Data::SimulationMode::Adequacy: + Solver::runSimulationInAdequacyMode(*study_, + settings, + durationCollector, + *resultWriter, + optimizationInfo, + simulationObserver); + break; + default: + break; + } + + // Importing Time-Series if asked + study_->importTimeseriesIntoInput(); + + // Stop the display of the progression + study_->progression.stop(); + return + { + .simulationPath = study_->folderOutput.c_str(), + .antares_problems = simulationObserver.acquireLps(), + .error{} + }; +} +} // namespace Antares::API \ No newline at end of file diff --git a/src/api/CMakeLists.txt b/src/api/CMakeLists.txt new file mode 100644 index 0000000000..109c640578 --- /dev/null +++ b/src/api/CMakeLists.txt @@ -0,0 +1,42 @@ +add_library(solver_api) +add_library(Antares::solver_api ALIAS solver_api) + +set(PUBLIC_HEADERS + include/antares/api/SimulationResults.h + include/antares/api/solver.h +) + +set(PRIVATE_HEADERS + private/API.h + private/SimulationObserver.h +) + +target_sources(solver_api + PRIVATE + solver.cpp + API.cpp + SimulationObserver.cpp + SimulationResults.cpp + ${PUBLIC_HEADERS} + ${PRIVATE_HEADERS} +) + +target_include_directories(solver_api + PUBLIC + $ + PRIVATE + $ +) + +target_link_libraries(solver_api + PRIVATE + Antares::study + Antares::study-loader + Antares::file-tree-study-loader + antares-solver-simulation + PUBLIC + Antares::lps +) +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/api/SimulationObserver.cpp b/src/api/SimulationObserver.cpp new file mode 100644 index 0000000000..7842ce8099 --- /dev/null +++ b/src/api/SimulationObserver.cpp @@ -0,0 +1,73 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "SimulationObserver.h" + +#include "antares/solver/optimisation/HebdoProblemToLpsTranslator.h" + +namespace Antares::API +{ +namespace +{ +auto translate(const PROBLEME_HEBDO& problemeHebdo, + std::string_view name, + const Solver::HebdoProblemToLpsTranslator& translator, + const unsigned int year, + const unsigned int week) +{ + auto weekly_data = translator.translate(problemeHebdo.ProblemeAResoudre.get(), name); + Solver::ConstantDataFromAntares common_data; + if (year == 1 && week == 1) + { + common_data = translator.commonProblemData(problemeHebdo.ProblemeAResoudre.get()); + } + return std::make_pair(common_data, weekly_data); +} +} // namespace + +void SimulationObserver::notifyHebdoProblem(const PROBLEME_HEBDO& problemeHebdo, + int optimizationNumber, + std::string_view name) +{ + if (optimizationNumber != 1) + { + return; // We only care about first optimization + } + Solver::HebdoProblemToLpsTranslator translator; + const unsigned int year = problemeHebdo.year + 1; + const unsigned int week = problemeHebdo.weekInTheYear + 1; + // common_data and weekly_data computed before the mutex lock to prevent blocking the thread + auto [common_data, weekly_data] = translate(problemeHebdo, name, translator, year, week); + std::lock_guard lock(mutex_); + if (year == 1 && week == 1) + { + lps_.setConstantData(common_data); + } + lps_.addWeeklyData({year, week}, weekly_data); +} + +Solver::LpsFromAntares&& SimulationObserver::acquireLps() noexcept +{ + std::lock_guard lock(mutex_); + return std::move(lps_); +} +} // namespace Antares::API diff --git a/src/api/SimulationResults.cpp b/src/api/SimulationResults.cpp new file mode 100644 index 0000000000..63c5127a49 --- /dev/null +++ b/src/api/SimulationResults.cpp @@ -0,0 +1,22 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/api/SimulationResults.h" diff --git a/src/api/include/antares/api/SimulationResults.h b/src/api/include/antares/api/SimulationResults.h new file mode 100644 index 0000000000..5a5e93982a --- /dev/null +++ b/src/api/include/antares/api/SimulationResults.h @@ -0,0 +1,62 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include +#include +#include +#include "antares/solver/lps/LpsFromAntares.h" + +namespace Antares::API +{ +/** + * @struct Error + * @brief The Error structure is used to represent an error that occurred during the simulation. + */ +struct Error { + /** + * @brief The reason for the error. + */ + std::string reason; +}; + +/** + * @struct SimulationResults + * @brief The SimulationResults structure is used to represent the results of a simulation. + * @details It contains the path to the simulation, weekly problems, and an optional error. + */ +struct [[nodiscard("Contains results and potential error")]] SimulationResults +{ + /** + * @brief The path to the simulation (output). + */ + std::filesystem::path simulationPath; + /** + * @brief weekly problems + */ + Antares::Solver::LpsFromAntares antares_problems; + /** + * @brief An optional error that occurred during the simulation. + */ + std::optional error; +}; + +} \ No newline at end of file diff --git a/src/api/include/antares/api/solver.h b/src/api/include/antares/api/solver.h new file mode 100644 index 0000000000..d016a9a08a --- /dev/null +++ b/src/api/include/antares/api/solver.h @@ -0,0 +1,35 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "SimulationResults.h" + +namespace Antares::API +{ +/** + * @brief The PerformSimulation function is used to perform a simulation. + * @param study_path The path to the study to be simulated. + * @return SimulationResults object which contains the results of the simulation. + * @exception noexcept This function does not throw exceptions. + */ +SimulationResults PerformSimulation(const std::filesystem::path& study_path) noexcept; +} // namespace Antares::API diff --git a/src/api/private/API.h b/src/api/private/API.h new file mode 100644 index 0000000000..91f8a4e2d3 --- /dev/null +++ b/src/api/private/API.h @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include + +#include +#include "antares/api/SimulationResults.h" + +namespace Antares::Data +{ +class Study; +} + +namespace Antares::API +{ + +/** + * @class APIInternal + * @brief The APIInternal class is used to run simulations. + */ +class APIInternal +{ +public: + /** + * @brief The run method is used to run the simulation. + * @param study_loader A pointer to an IStudyLoader object. The IStudyLoader object is used to + * load the study that will be simulated. + * @return SimulationResults object which contains the results of the simulation. + */ + SimulationResults run(const IStudyLoader& study_loader); + +private: + std::shared_ptr study_; + SimulationResults execute() const; +}; + +} // namespace Antares::API diff --git a/src/api/private/SimulationObserver.h b/src/api/private/SimulationObserver.h new file mode 100644 index 0000000000..f2d78fc4eb --- /dev/null +++ b/src/api/private/SimulationObserver.h @@ -0,0 +1,61 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include +#include + +namespace Antares::API +{ + +/** + * @class SimulationObserver + * @brief The SimulationObserver class is used to observe the simulation. + * @details It inherits from the ISimulationObserver interface and overrides the notifyHebdoProblem + * method. + */ +class SimulationObserver: public Solver::Simulation::ISimulationObserver +{ +public: + /** + * @brief Used to notify of a solver HEBDO_PROBLEM. + * HEBDO_PROBLEM is assumed to be properly constructed and valid in order to build + * LpsFromAntares properly + * @param problemeHebdo A pointer to a PROBLEME_HEBDO object representing the problem. + * @param optimizationNumber The number of the optimization. + * @param name The name of the problem. + */ + void notifyHebdoProblem(const PROBLEME_HEBDO& problemeHebdo, + int optimizationNumber, + std::string_view name) override; + + /** + * @brief The acquireLps method is used to take ownership of Antares problems. + * @return An LpsFromAntares object containing the linear programming problems. + */ + Solver::LpsFromAntares&& acquireLps() noexcept; + +private: + Solver::LpsFromAntares lps_; + std::mutex mutex_; +}; + +} // namespace Antares::API diff --git a/src/api/solver.cpp b/src/api/solver.cpp new file mode 100644 index 0000000000..6e2f7068ea --- /dev/null +++ b/src/api/solver.cpp @@ -0,0 +1,46 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include +#include "antares/file-tree-study-loader/FileTreeStudyLoader.h" +#include "antares/study-loader/IStudyLoader.h" + +#include "private/API.h" + +namespace Antares::API +{ + +SimulationResults PerformSimulation(const std::filesystem::path& study_path) noexcept +{ + try + { + APIInternal api; + FileTreeStudyLoader study_loader(study_path); + return api.run(study_loader); + } + catch (const std::exception& e) + { + Antares::API::Error err{.reason = e.what()}; + return SimulationResults{.simulationPath = study_path, .antares_problems{}, .error = err}; + } +} + +} // namespace Antares::API diff --git a/src/api_client_example/CMakeLists.txt b/src/api_client_example/CMakeLists.txt new file mode 100644 index 0000000000..570ee9341b --- /dev/null +++ b/src/api_client_example/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.5) + +PROJECT(API_client) + +set(CMAKE_CXX_STANDARD 20) + +add_subdirectory(src) + +include(CTest) +if (BUILD_TESTING) + add_subdirectory(tests) +endif () \ No newline at end of file diff --git a/src/api_client_example/README.md b/src/api_client_example/README.md new file mode 100644 index 0000000000..151b1d346b --- /dev/null +++ b/src/api_client_example/README.md @@ -0,0 +1,3 @@ +Client for antares solver API + +To demonstrate as much capabilities as possible this client should stay stand alone this mean not added as a sub_directory for cmake diff --git a/src/api_client_example/src/API_client.cpp b/src/api_client_example/src/API_client.cpp new file mode 100644 index 0000000000..6489806c51 --- /dev/null +++ b/src/api_client_example/src/API_client.cpp @@ -0,0 +1,30 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + + +#include "API_client.h" + +#include + +Antares::API::SimulationResults solve(std::filesystem::path study_path) { + return Antares::API::PerformSimulation(std::move(study_path)); +} + diff --git a/src/api_client_example/src/API_client.h b/src/api_client_example/src/API_client.h new file mode 100644 index 0000000000..5d8500649e --- /dev/null +++ b/src/api_client_example/src/API_client.h @@ -0,0 +1,28 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include +#include + +Antares::API::SimulationResults solve(std::filesystem::path study_path); diff --git a/src/api_client_example/src/CMakeLists.txt b/src/api_client_example/src/CMakeLists.txt new file mode 100644 index 0000000000..55ebb33579 --- /dev/null +++ b/src/api_client_example/src/CMakeLists.txt @@ -0,0 +1,14 @@ +add_library(API_client) + +target_sources(API_client + PRIVATE + API_client.cpp + API_client.h +) + +find_package(Antares REQUIRED) +target_link_libraries(API_client PUBLIC Antares::solver_api) +target_include_directories(API_client + PUBLIC + $ +) \ No newline at end of file diff --git a/src/api_client_example/tests/CMakeLists.txt b/src/api_client_example/tests/CMakeLists.txt new file mode 100644 index 0000000000..1fc9c3cc89 --- /dev/null +++ b/src/api_client_example/tests/CMakeLists.txt @@ -0,0 +1,17 @@ +find_package(Boost COMPONENTS unit_test_framework REQUIRED) + +add_executable(test_client) + +target_sources(test_client + PRIVATE + test.cpp +) + +target_link_libraries(test_client + PRIVATE + API_client + Boost::unit_test_framework +) + +add_test(NAME testclient COMMAND test_client) +set_property(TEST testclient PROPERTY LABELS integ) \ No newline at end of file diff --git a/src/api_client_example/tests/test.cpp b/src/api_client_example/tests/test.cpp new file mode 100644 index 0000000000..4adee7bfd6 --- /dev/null +++ b/src/api_client_example/tests/test.cpp @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test_client_api + +#include +#include "API_client.h" + +BOOST_AUTO_TEST_CASE(test_run) { + auto results = solve("dummy_study_test_client_api"); + BOOST_CHECK(results.error); + BOOST_CHECK(!results.error->reason.empty()); + auto c = results.error->reason; + std::cout << c << std::endl; + BOOST_CHECK(results.error->reason.find("Study") != std::string::npos); + BOOST_CHECK(results.error->reason.find("folder") != std::string::npos); + BOOST_CHECK(results.error->reason.find("not") != std::string::npos); + BOOST_CHECK(results.error->reason.find("exist") != std::string::npos); +} \ No newline at end of file diff --git a/src/cmake/changelog.cmake b/src/cmake/changelog.cmake index 5f62c40077..1164af0ed1 100644 --- a/src/cmake/changelog.cmake +++ b/src/cmake/changelog.cmake @@ -1,4 +1,4 @@ # Copy the changelog -file(READ "../docs/CHANGELOG.md" changelog_content) +file(READ "../docs/developer-guide/CHANGELOG.md" changelog_content) file(WRITE "distrib/changelog.txt" "${changelog_content}") diff --git a/src/cmake/common-settings.cmake b/src/cmake/common-settings.cmake index fc34d0a780..b659a5f46c 100644 --- a/src/cmake/common-settings.cmake +++ b/src/cmake/common-settings.cmake @@ -1,7 +1,7 @@ # # Common FLAGS for all compilers # -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(COMMON_GCC_FLAGS "-Wall -W -Wextra -Wfatal-errors") if (NOT WIN32) @@ -10,7 +10,7 @@ if (NOT WIN32) set(COMMON_GCC_FLAGS "${COMMON_GCC_FLAGS} -pipe -msse -msse2 -Wunused-but-set-variable -Wunused-but-set-parameter") set(COMMON_GCC_FLAGS "${COMMON_GCC_FLAGS} -Werror=return-type") endif() -set(COMMON_MSVC_FLAGS "/W3 /MP4 /Zi ") +set(COMMON_MSVC_FLAGS "/W3 /MP4") set(COMMON_MSVC_FLAGS "${COMMON_MSVC_FLAGS} /we4715 /we4716") #adding no return or no return for all code paths as errors set(ADDITIONAL_C_FLAGS " -Wconversion -Wmissing-prototypes -Wstrict-prototypes") set(ADDITIONAL_C_FLAGS "${ADDITIONAL_C_FLAGS} -Wmissing-noreturn -Wpacked -Wredundant-decls -Wbad-function-cast -W -Wcast-align -Wcast-qual -Wsign-compare -fno-exceptions -Wdeclaration-after-statement") @@ -24,7 +24,7 @@ macro(EMBED_MANIFEST manifestfile target) if(MSVC AND NOT MSVC9) message(STATUS "{antares} :: adding rule for manifest ${manifestfile}") set(ANTARES_UI_BIN_TARGET "Debug\\") - if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") + if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(ANTARES_UI_BIN_TARGET "Release\\") endif() @@ -42,7 +42,7 @@ endmacro() # # Ex: cmake . -DCMAKE_BUILD_TYPE=release # -if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") +if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") # # Build Configuration: Release @@ -61,12 +61,6 @@ if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "t if (NOT MSVC) set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -std=c99") endif() - - if("${CMAKE_BUILD_TYPE}" STREQUAL "tuning") - set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pg --no-inline") - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -pg --no-inline") - endif("${CMAKE_BUILD_TYPE}" STREQUAL "tuning") - else() # @@ -105,23 +99,21 @@ endif() if(MSVC) - #Compile option must be updated if VPCKG static is used (can't mix different compile option) - if("${VCPKG_TARGET_TRIPLET}" STREQUAL "x64-windows-static" OR "${VCPKG_TARGET_TRIPLET}" STREQUAL "x86-windows-static") - set(CMAKE_C_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MTd /GR /Ot /Od /EHsc /RTC1") - set(CMAKE_CXX_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MTd /GR /Ot /Od /EHsc /RTC1 /fp:except") - else() - set(CMAKE_C_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MDd /GR /Ot /Od /EHsc /RTC1") - set(CMAKE_CXX_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MDd /GR /Ot /Od /EHsc /RTC1 /fp:except") - endif() + set(CMAKE_C_FLAGS "${COMMON_MSVC_FLAGS}") + set(CMAKE_CXX_FLAGS "${COMMON_MSVC_FLAGS}") + # If other libraries have been linked statically with C runtime, we need to keep consistent with it if("${VCPKG_TARGET_TRIPLET}" STREQUAL "x64-windows-static" OR "${VCPKG_TARGET_TRIPLET}" STREQUAL "x86-windows-static") - set(CMAKE_C_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MTd /GR /Ot /Od /EHsc /RTC1") - set(CMAKE_CXX_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MTd /GR /Ot /Od /EHsc /RTC1 /fp:except") + set(CRT_LIBRARY_DEBUG "/MTd") + set(CRT_LIBRARY_RELEASE "/MT") else() - set(CMAKE_C_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MDd /GR /Ot /Od /EHsc /RTC1") - set(CMAKE_CXX_FLAGS_DEBUG "${COMMON_MSVC_FLAGS} /MDd /GR /Ot /Od /EHsc /RTC1 /fp:except") + set(CRT_LIBRARY_DEBUG "/MDd") + set(CRT_LIBRARY_RELEASE "/MD") endif() + set(CMAKE_C_FLAGS_DEBUG "${CRT_LIBRARY_DEBUG} /Zi /GR /Ot /Od /EHsc /RTC1") + set(CMAKE_CXX_FLAGS_DEBUG "${CRT_LIBRARY_DEBUG} /Zi /GR /Ot /Od /EHsc /RTC1 /fp:except") + # RELEASE set(CMAKE_EXE_LINKER_FLAGS_RELEASE) set(MSVC_RELEASE_FLAGS) @@ -141,14 +133,9 @@ if(MSVC) set(MSVC_RELEASE_FLAGS "${MSVC_RELEASE_FLAGS} /GS-") # Intrinsic functions set(MSVC_RELEASE_FLAGS "${MSVC_RELEASE_FLAGS} /Oi") + # C runtime library + set(MSVC_RELEASE_FLAGS "${MSVC_RELEASE_FLAGS} ${CRT_LIBRARY_RELEASE}") - # Multithreaded DLL - #Compile option must be updated if VPCKG static is used (can't mix different compile option) - if("${VCPKG_TARGET_TRIPLET}" STREQUAL "x64-windows-static" OR "${VCPKG_TARGET_TRIPLET}" STREQUAL "x86-windows-static") - set(MSVC_RELEASE_FLAGS "${MSVC_RELEASE_FLAGS} /MT") - else() - set(MSVC_RELEASE_FLAGS "${MSVC_RELEASE_FLAGS} /MD") - endif() # linker: Link time code generation #set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG") @@ -165,8 +152,8 @@ if(MSVC) # Remove symbols set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /OPT:REF") - set(CMAKE_CXX_FLAGS_RELEASE "${COMMON_MSVC_FLAGS} ${MSVC_RELEASE_FLAGS} /EHsc") - set(CMAKE_C_FLAGS_RELEASE "${COMMON_MSVC_FLAGS} ${MSVC_RELEASE_FLAGS} /EHsc") + set(CMAKE_CXX_FLAGS_RELEASE "${MSVC_RELEASE_FLAGS} /EHsc") + set(CMAKE_C_FLAGS_RELEASE "${MSVC_RELEASE_FLAGS} /EHsc") #SET(CMAKE_EXE_LINKER_FLAGS_DEBUG "/debug /VERSION:${ANTARES_VERSION_HI}.${ANTARES_VERSION_LO}") @@ -216,7 +203,7 @@ endmacro() macro(executable_strip TARGET) - if("${CMAKE_BUILD_TYPE}" STREQUAL "release") + if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") if(NOT MSVC) if(WIN32) add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND ${CMAKE_STRIP} $) @@ -226,14 +213,3 @@ macro(executable_strip TARGET) endif() endif() endmacro() - -if("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "tuning") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_RELEASE}") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS_RELEASE}") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") -else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_DEBUG} ${COVERAGE_CXX_FLAGS}") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS_DEBUG} ${COVERAGE_CXX_FLAGS}") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS_DEBUG} ${COVERAGE_LINKER_FLAGS}") -endif() - diff --git a/src/cmake/utils.cmake b/src/cmake/utils.cmake index b470a700fc..3e3aeb7e20 100644 --- a/src/cmake/utils.cmake +++ b/src/cmake/utils.cmake @@ -1,10 +1,8 @@ macro(copy_dependency deps target) - if("${CMAKE_BUILD_TYPE}" STREQUAL "release") - + if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") get_target_property( DEP_SHARED_LIB_PATH ${deps} IMPORTED_LOCATION_RELEASE ) else() - get_target_property( DEP_SHARED_LIB_PATH ${deps} IMPORTED_LOCATION_DEBUG ) endif() diff --git a/src/cmake/wxWidgets/FindwxWidgets.cmake b/src/cmake/wxWidgets/FindwxWidgets.cmake index dea003dce6..c174be3ed7 100644 --- a/src/cmake/wxWidgets/FindwxWidgets.cmake +++ b/src/cmake/wxWidgets/FindwxWidgets.cmake @@ -820,7 +820,6 @@ else() find_program(wxWidgets_CONFIG_EXECUTABLE NAMES $ENV{WX_CONFIG} wx-config wx-config-3.1 wx-config-3.0 wx-config-2.9 wx-config-2.8 DOC "Location of wxWidgets library configuration provider binary (wx-config)." - ONLY_CMAKE_FIND_ROOT_PATH ) if(wxWidgets_CONFIG_EXECUTABLE) diff --git a/src/cmake_clean.sh b/src/cmake_clean.sh deleted file mode 100644 index 69244d59a2..0000000000 --- a/src/cmake_clean.sh +++ /dev/null @@ -1,6 +0,0 @@ -#! /bin/sh - -find -name 'Makefile' -type f -exec rm -rf {} \+ -find -name 'CMakeFiles' -type d -exec rm -rf {} \+ -find -name 'CMakeCache.txt' -type f -exec rm -f {} \+ -find -name 'cmake_install.cmake' -type f -exec rm -f {} \+ diff --git a/src/config.h.cmake b/src/config.h.cmake deleted file mode 100644 index 2ef09b0d3d..0000000000 --- a/src/config.h.cmake +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef __ANTARES_CONFIG_H__ -# define __ANTARES_CONFIG_H__ - - -//! The Hi version -# define ANTARES_VERSION_HI @ANTARES_VERSION_HI@ -//! The Lo version -# define ANTARES_VERSION_LO @ANTARES_VERSION_LO@ -//! Build (Revision) of Antares -# define ANTARES_VERSION_BUILD @ANTARES_VERSION_REVISION@ -//! Canonical version -# define ANTARES_VERSION "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@" -//! Date of publication -# define ANTARES_VERSION_YEAR @ANTARES_VERSION_YEAR@ - -//! Version in CString format -# define ANTARES_VERSION_STR "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@@ANTARES_VERSION_TAG@" - -//! Version + Publisher -# define ANTARES_VERSION_PUB_STR "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@ (@ANTARES_PUBLISHER@)" - - -# define ANTARES_VERSION_BUILD_DATE __DATE__ - -//! The Publisher -# define ANTARES_PUBLISHER "@ANTARES_PUBLISHER@" -//! The Website for RTE -# define ANTARES_WEBSITE "@ANTARES_WEBSITE@" -//! URL for the online documentation -#define ANTARES_ONLINE_DOC "@ANTARES_ONLINE_DOC@" - -// ---------------------------------------------------------------------------- - -//! Beta version -#cmakedefine ANTARES_BETA @ANTARES_BETA@ - -//! RC version -#cmakedefine ANTARES_RC @ANTARES_RC@ - -//! git revision (SHA-1) -#define GIT_SHA1_SHORT_STRING "@GIT_SHA1_SHORT@" - -#endif // __ANTARES_CONFIG_H__ - diff --git a/src/config/CMakeLists.txt b/src/config/CMakeLists.txt new file mode 100644 index 0000000000..6eaaaf7e3c --- /dev/null +++ b/src/config/CMakeLists.txt @@ -0,0 +1,21 @@ +set(PROJ antares-config-lib) +set(HEADERS + include/antares/config/config.h +) +set(SRC_CONFIG + ${HEADERS} + config.cpp +) +source_group("config" FILES ${SRC_CONFIG}) + +add_library(${PROJ} ${SRC_CONFIG}) #Memory conflict with absl memory when building deps https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/1589 +add_library(Antares::config ALIAS ${PROJ}) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/config/config.cpp b/src/config/config.cpp new file mode 100644 index 0000000000..43f71f9d66 --- /dev/null +++ b/src/config/config.cpp @@ -0,0 +1,22 @@ +// /* +// ** Copyright 2007-2024, RTE (https://www.rte-france.com) +// ** See AUTHORS.txt +// ** SPDX-License-Identifier: MPL-2.0 +// ** This file is part of Antares-Simulator, +// ** Adequacy and Performance assessment for interconnected energy networks. +// ** +// ** Antares_Simulator is free software: you can redistribute it and/or modify +// ** it under the terms of the Mozilla Public Licence 2.0 as published by +// ** the Mozilla Foundation, either version 2 of the License, or +// ** (at your option) any later version. +// ** +// ** Antares_Simulator 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 +// ** Mozilla Public Licence 2.0 for more details. +// ** +// ** You should have received a copy of the Mozilla Public Licence 2.0 +// ** along with Antares_Simulator. If not, see . +// * + +#include "antares/config/config.h" diff --git a/src/config/config.h.in b/src/config/config.h.in new file mode 100644 index 0000000000..2d89f6203b --- /dev/null +++ b/src/config/config.h.in @@ -0,0 +1,44 @@ +#ifndef __ANTARES_CONFIG_H__ +# define __ANTARES_CONFIG_H__ + + +//! The Hi version +# define ANTARES_VERSION_HI @ANTARES_VERSION_HI@ +//! The Lo version +# define ANTARES_VERSION_LO @ANTARES_VERSION_LO@ +//! Build (Revision) of Antares +# define ANTARES_VERSION_BUILD @ANTARES_VERSION_REVISION@ +//! Canonical version +# define ANTARES_VERSION "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@" +//! Date of publication +# define ANTARES_VERSION_YEAR @ANTARES_VERSION_YEAR@ + +//! Version in CString format +# define ANTARES_VERSION_STR "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@@ANTARES_VERSION_TAG@" + +//! Version + Publisher +# define ANTARES_VERSION_PUB_STR "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@ (@ANTARES_PUBLISHER@)" + + +# define ANTARES_VERSION_BUILD_DATE __DATE__ + +//! The Publisher +# define ANTARES_PUBLISHER "@ANTARES_PUBLISHER@" +//! The Website for RTE +# define ANTARES_WEBSITE "@ANTARES_WEBSITE@" +//! URL for the online documentation +#define ANTARES_ONLINE_DOC "@ANTARES_ONLINE_DOC@" + +// ---------------------------------------------------------------------------- + +//! Beta version +#cmakedefine ANTARES_BETA @ANTARES_BETA@ + +//! RC version +#cmakedefine ANTARES_RC @ANTARES_RC@ + +//! git revision (SHA-1) +#define GIT_SHA1_SHORT_STRING "@GIT_SHA1_SHORT@" + +#endif // __ANTARES_CONFIG_H__ + diff --git a/src/distrib/unix/rpm/create-rpms.sh b/src/distrib/unix/rpm/create-rpms.sh index a70f0f8aa8..ada2404fc9 100755 --- a/src/distrib/unix/rpm/create-rpms.sh +++ b/src/distrib/unix/rpm/create-rpms.sh @@ -194,23 +194,23 @@ main() "${antares_publisher}" \ "${antares_website}" pkg_cwd "/usr/bin" - pkg_add_exec "solver/antares-${ver}-solver" - pkg_add_exec "solver/antares-${ver}-solver-swap" - pkg_add_exec "analyzer/antares-${ver}-analyzer" - pkg_add_exec "tools/finder/antares-${ver}-study-finder" - pkg_add_exec "tools/batchrun/antares-${ver}-batchrun" - pkg_add_exec "tools/config/antares-${ver}-config" - pkg_add_exec "tools/updater/antares-${ver}-study-updater" + pkg_add_exec "solver/antares-solver" + pkg_add_exec "solver/antares-solver-swap" + pkg_add_exec "analyzer/antares-analyzer" + pkg_add_exec "tools/finder/antares-study-finder" + pkg_add_exec "tools/batchrun/antares-batchrun" + pkg_add_exec "tools/config/antares-config" + pkg_add_exec "tools/updater/antares-study-updater" pkg_cwd "/etc/antares/pkgs" - echo "/usr/bin/antares-${ver}-solver" > "${root}/pkginfo-solver" - pkg_add_file "distrib/unix/rpm/pkginfo-solver" "solver-${ver}" - echo "/usr/bin/antares-${ver}-solver-swap" > "${root}/pkginfo-solver-swap" - pkg_add_file "distrib/unix/rpm/pkginfo-solver-swap" "solver-swap-${ver}" - echo "/usr/bin/antares-${ver}-analyzer" > "${root}/pkginfo-analyzer" - pkg_add_file "distrib/unix/rpm/pkginfo-analyzer" "analyzer-${ver}" - echo "/usr/bin/antares-${ver}-config" > "${root}/pkginfo-config" - pkg_add_file "distrib/unix/rpm/pkginfo-config" "config-${ver}" + echo "/usr/bin/antares-solver" > "${root}/pkginfo-solver" + pkg_add_file "distrib/unix/rpm/pkginfo-solver" "solver" + echo "/usr/bin/antares-solver-swap" > "${root}/pkginfo-solver-swap" + pkg_add_file "distrib/unix/rpm/pkginfo-solver-swap" "solver-swap" + echo "/usr/bin/antares-analyzer" > "${root}/pkginfo-analyzer" + pkg_add_file "distrib/unix/rpm/pkginfo-analyzer" "analyzer" + echo "/usr/bin/antares-config" > "${root}/pkginfo-config" + pkg_add_file "distrib/unix/rpm/pkginfo-config" "config" pkg_build diff --git a/src/distrib/win32/NSIS.template.in b/src/distrib/win32/NSIS.template.in index 90753b1f71..e9aed605af 100644 --- a/src/distrib/win32/NSIS.template.in +++ b/src/distrib/win32/NSIS.template.in @@ -32,7 +32,7 @@ BrandingText " Antares_Simulator for Windows " -!define ANTARES_BIN "antares-${CMAKE_SIMPLE_VERSION}-ui-simulator.exe" +!define ANTARES_BIN "antares-ui-simulator.exe" @@ -290,21 +290,21 @@ ${MementoSection} "$(LngCoreFiles)" SecCore ; !insertmacro AppendCoreFiles ${SetOutPath} "$INSTDIR\bin" - ${File} "${ANTARES_BUILD_DIR}\ui\simulator\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-ui-simulator.exe" + ${File} "${ANTARES_BUILD_DIR}\ui\simulator\${TARGET}" "antares-ui-simulator.exe" ;.ddl are available only with shared dependencies link FileOptionnal used ${FileOptionnal} "${ANTARES_BUILD_DIR}\ui\simulator\${TARGET}" "*.dll" - ${File} "${ANTARES_BUILD_DIR}\solver\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-solver.exe" + ${File} "${ANTARES_BUILD_DIR}\solver\${TARGET}" "antares-solver.exe" ${FileOptionnal} "${ANTARES_BUILD_DIR}\solver\${TARGET}" "*.dll" - ${File} "${ANTARES_BUILD_DIR}\analyzer\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-analyzer.exe" - ${File} "${ANTARES_BUILD_DIR}\tools\yby-aggregator\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-ybyaggregator.exe" - ${File} "${ANTARES_BUILD_DIR}\tools\batchrun\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-batchrun.exe" - ${File} "${ANTARES_BUILD_DIR}\tools\finder\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-study-finder.exe" - ${File} "${ANTARES_BUILD_DIR}\tools\updater\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-study-updater.exe" - ${File} "${ANTARES_BUILD_DIR}\tools\cleaner\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-study-cleaner.exe" - ${File} "${ANTARES_BUILD_DIR}\tools\config\${TARGET}" "antares-${CMAKE_SIMPLE_VERSION}-config.exe" + ${File} "${ANTARES_BUILD_DIR}\analyzer\${TARGET}" "antares-analyzer.exe" + ${File} "${ANTARES_BUILD_DIR}\tools\yby-aggregator\${TARGET}" "antares-ybyaggregator.exe" + ${File} "${ANTARES_BUILD_DIR}\tools\batchrun\${TARGET}" "antares-batchrun.exe" + ${File} "${ANTARES_BUILD_DIR}\tools\finder\${TARGET}" "antares-study-finder.exe" + ${File} "${ANTARES_BUILD_DIR}\tools\updater\${TARGET}" "antares-study-updater.exe" + ${File} "${ANTARES_BUILD_DIR}\tools\ts-generator\${TARGET}" "antares-ts-generator.exe" + ${File} "${ANTARES_BUILD_DIR}\tools\config\${TARGET}" "antares-config.exe" ${File} "${ANTARES_BUILD_DIR}\ui\simulator\resources\icons" "study.ico" ;Add system runtime libs (defined in src/CMakeList.txt) @@ -343,7 +343,7 @@ ${MementoSection} "$(LngCoreFiles)" SecCore ${registerExtension} "$INSTDIR\bin\${ANTARES_BIN}" ".antares" "Antares Study ${CMAKE_SIMPLE_VERSION}" ${registerExtension} "$INSTDIR\bin\${ANTARES_BIN}" ".antares-output" "Antares Study Results ${CMAKE_SIMPLE_VERSION}" - CreateShortCut "$INSTDIR\antares-${CMAKE_SIMPLE_VERSION}-ui-simulator.lnk" "$INSTDIR\bin\${ANTARES_BIN}" "" "" + CreateShortCut "$INSTDIR\antares-ui-simulator.lnk" "$INSTDIR\bin\${ANTARES_BIN}" "" "" ${Mementosectionend} @@ -533,7 +533,7 @@ section Uninstall delete "$INSTDIR\${UninstLog}" delete "$INSTDIR\bin\${ANTARES_BIN}" - delete "$INSTDIR\antares-${CMAKE_SIMPLE_VERSION}-ui-simulator.lnk" + delete "$INSTDIR\antares-ui-simulator.lnk" delete "$SMPROGRAMS\RTE Antares ${PRODUCT_VERSION}\Antares Simulator ${PRODUCT_VERSION}.lnk" delete "$INSTDIR\Documentation\Data Organizer reference guide (PDF).lnk" delete "$SMPROGRAMS\RTE Antares ${PRODUCT_VERSION}\Documentation\Data Organizer reference guide (PDF).lnk" diff --git a/src/distrib/win32/sourcefiles.inc.nsh b/src/distrib/win32/sourcefiles.inc.nsh index 29db79dc43..ddec5c9c68 100644 --- a/src/distrib/win32/sourcefiles.inc.nsh +++ b/src/distrib/win32/sourcefiles.inc.nsh @@ -9,7 +9,6 @@ File ${ANTARES_SRC_DIR}\..\COPYING.txt File ${ANTARES_SRC_DIR}\..\NEWS.md File ${ANTARES_SRC_DIR}\..\ROADMAP.txt File ${ANTARES_SRC_DIR}\..\THANKS.txt -File ${ANTARES_SRC_DIR}\..\INSTALL.md File ${ANTARES_SRC_DIR}\..\README.md ${SetOutPath} "$INSTDIR\Sources\resources" diff --git a/src/ext/yuni/src/cmake/common-settings.cmake b/src/ext/yuni/src/cmake/common-settings.cmake index 9c8410ad3b..d92357ebde 100644 --- a/src/ext/yuni/src/cmake/common-settings.cmake +++ b/src/ext/yuni/src/cmake/common-settings.cmake @@ -12,7 +12,7 @@ include(CheckCXXCompilerFlag) set_property(GLOBAL PROPERTY USE_FOLDERS true) -if ("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "RELEASE") +if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(YUNI_) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_DEBUG}") @@ -305,7 +305,7 @@ if(NOT "${YUNI_CXX_FLAGS_OVERRIDE_ADD_RELWITHDEBINFO}" STREQUAL "") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} ${YUNI_CXX_FLAGS_OVERRIDE_ADD_RELWITHDEBINFO}") endif() -if ("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "RELEASE") +if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_RELEASE}") else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_DEBUG}") diff --git a/src/ext/yuni/src/cmake/target.cmake b/src/ext/yuni/src/cmake/target.cmake index b0e23cfff0..3f67bfc489 100644 --- a/src/ext/yuni/src/cmake/target.cmake +++ b/src/ext/yuni/src/cmake/target.cmake @@ -24,8 +24,8 @@ if(NO_BUILD_TYPE) endif() endif() -string(COMPARE EQUAL "${CMAKE_BUILD_TYPE}" "debug" BUILD_TYPE_IS_DEBUG) -string(COMPARE EQUAL "${CMAKE_BUILD_TYPE}" "release" BUILD_TYPE_IS_RELEASE) +string(COMPARE EQUAL "${CMAKE_BUILD_TYPE}" "Debug" BUILD_TYPE_IS_DEBUG) +string(COMPARE EQUAL "${CMAKE_BUILD_TYPE}" "Release" BUILD_TYPE_IS_RELEASE) if(NOT BUILD_TYPE_IS_DEBUG AND NOT BUILD_TYPE_IS_RELEASE) set(CMAKE_BUILD_TYPE "debug") endif() diff --git a/src/ext/yuni/src/tools/yuni-config/program.cpp b/src/ext/yuni/src/tools/yuni-config/program.cpp index 1408172c9b..a4378bf584 100644 --- a/src/ext/yuni/src/tools/yuni-config/program.cpp +++ b/src/ext/yuni/src/tools/yuni-config/program.cpp @@ -148,14 +148,14 @@ void LibConfigProgram::findRootPath(const char* a0) const String argv0 = a0; if (IO::IsAbsolute(argv0)) { - IO::ExtractFilePath(pRootPath, argv0); + IO::parent_path(pRootPath, argv0); } else { IO::Directory::Current::Get(pRootPath); pRootPath << IO::Separator; String t; - IO::ExtractFilePath(t, argv0); + IO::parent_path(t, argv0); pRootPath += t; pRootPath.removeTrailingSlash(); } diff --git a/src/ext/yuni/src/yuni/CMakeLists.txt b/src/ext/yuni/src/yuni/CMakeLists.txt index 758a906e5c..5914a15a3c 100644 --- a/src/ext/yuni/src/yuni/CMakeLists.txt +++ b/src/ext/yuni/src/yuni/CMakeLists.txt @@ -31,7 +31,7 @@ include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/common-settings.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules.cmake") -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) if(YUNI_MODULE_CORE) # The header yuni.h must be available diff --git a/src/ext/yuni/src/yuni/cmake/core/core.cmake b/src/ext/yuni/src/yuni/cmake/core/core.cmake index 7f18ad44db..72d9610368 100644 --- a/src/ext/yuni/src/yuni/cmake/core/core.cmake +++ b/src/ext/yuni/src/yuni/cmake/core/core.cmake @@ -233,8 +233,6 @@ add_library(yuni-static-core STATIC core/process/program/process-info.hxx core/process/program/windows.inc.hpp core/process/program/unix.inc.hpp - core/process/rename.cpp - core/process/rename.h core/process.h core/quaternion.h core/rect2D.h @@ -508,6 +506,7 @@ install(FILES doxygen.h platform.h yuni.h + string.h COMPONENT ${YUNICOMPONENT_CORE} DESTINATION include/yuni ) diff --git a/src/ext/yuni/src/yuni/cmake/parser/importer.cpp b/src/ext/yuni/src/yuni/cmake/parser/importer.cpp index f806478717..83ef67e7b6 100644 --- a/src/ext/yuni/src/yuni/cmake/parser/importer.cpp +++ b/src/ext/yuni/src/yuni/cmake/parser/importer.cpp @@ -60,7 +60,7 @@ int main(int argc, char* argv[]) } String targetFolder; - IO::ExtractFilePath(targetFolder, targetfile); + IO::parent_path(targetFolder, targetfile); String tmplcontent; diff --git a/src/ext/yuni/src/yuni/core/any/any.cpp b/src/ext/yuni/src/yuni/core/any/any.cpp index 47017ed8d1..36e2257c32 100644 --- a/src/ext/yuni/src/yuni/core/any/any.cpp +++ b/src/ext/yuni/src/yuni/core/any/any.cpp @@ -16,7 +16,7 @@ namespace Yuni Any::Any() { pTable = Private::Any::Table::Get(); - pObject = NULL; + pObject = nullptr; } Any::Any(const Any& rhs) @@ -59,7 +59,7 @@ void Any::reset() { pTable->staticDelete(&pObject); pTable = Private::Any::Table::Get(); - pObject = NULL; + pObject = nullptr; } } diff --git a/src/ext/yuni/src/yuni/core/atomic/int.hxx b/src/ext/yuni/src/yuni/core/atomic/int.hxx index 769fa74a4d..0ee6dd00aa 100644 --- a/src/ext/yuni/src/yuni/core/atomic/int.hxx +++ b/src/ext/yuni/src/yuni/core/atomic/int.hxx @@ -90,13 +90,13 @@ inline Int::operator ScalarType() const template class TP> inline typename Int::ScalarType Int::operator++() { - return (threadSafe) ? Private::AtomicImpl::Operator::Increment(*this) : (++pValue); + return Private::AtomicImpl::Operator::Increment(*this); } template class TP> inline typename Int::ScalarType Int::operator--() { - return (threadSafe) ? Private::AtomicImpl::Operator::Decrement(*this) : (--pValue); + return Private::AtomicImpl::Operator::Decrement(*this); } template class TP> diff --git a/src/ext/yuni/src/yuni/core/bind/bind.h.generator.commonstypes.hpp b/src/ext/yuni/src/yuni/core/bind/bind.h.generator.commonstypes.hpp deleted file mode 100644 index 4d45fa7486..0000000000 --- a/src/ext/yuni/src/yuni/core/bind/bind.h.generator.commonstypes.hpp +++ /dev/null @@ -1,81 +0,0 @@ - //! The most suitable smartptr for the class - typedef SmartPtr Ptr; - - //! Pointer-to-function - typedef R (*FunctionType)(<%=generator.list(i)%>); - //! The type of the return value - typedef R ReturnType; - - /*! - ** \brief Pointer-to-member of any Class - ** \tparam C Any class - */ - template - struct PointerToMember final - { - //! Mere type for C - typedef typename Static::Remove::All::Type Class; - //! Type for a pointer-to-member - typedef R (Class::*Type)(<%=generator.list(i)%>); - //! Type for a const pointer-to-member - typedef R (Class::*ConstType)(<%=generator.list(i)%>) const; - }; - enum - { - //! The number of arguments - argumentCount = <%=i%>, - }; - enum - { - //! A non-zero value if the prototype has a return value (!= void) - hasReturnValue = Static::Type::StrictlyEqual::No, - }; - - /*! - ** \brief Type of each argument by their index - ** - ** The typedef Type is always valid, even if the argument does not exist. - ** If this case, the type will be the empty class Yuni::None. You may - ** use `argumentCount` to know exactly the number of arguments. - ** \tparam I Index of the argument (zero-based) - */ - template - struct Argument final - { - //! Type of the argument at position I (zero-based) - typedef typename Private::BindImpl::Argument),I>::Type Type; - }; - - /*! - ** \brief Types when an additional user data is present - ** \tparam U Type for the additional user data - */ - template - struct WithUserData final - { - //! The most suitable type as a parameter - typedef typename Private::BindImpl::Parameter::Type ParameterType; - - enum - { - //! The number of arguments - argumentCount = <%=i%> + 1, // original count + userdata - }; - //! A pointer-to-function - typedef R (*FunctionType)(<%=generator.list(i,'A', "", ", ")%>U); - - /*! - ** \brief Type of each argument by their index - ** - ** The typedef Type is always valid, even if the argument does not exist. - ** If this case, the type will be the empty class Yuni::None. You may - ** use `argumentCount` to know exactly the number of arguments. - ** \tparam I Index of the argument (zero-based) - */ - template - struct Argument final - { - //! Type of the argument at position I - typedef typename Private::BindImpl::ArgumentU),I>::Type Type; - }; - }; // class WithUserData diff --git a/src/ext/yuni/src/yuni/core/bind/bind.h.generator.hpp b/src/ext/yuni/src/yuni/core/bind/bind.h.generator.hpp deleted file mode 100644 index a98be93ef3..0000000000 --- a/src/ext/yuni/src/yuni/core/bind/bind.h.generator.hpp +++ /dev/null @@ -1,514 +0,0 @@ -/* -** YUNI's default license is the GNU Lesser Public License (LGPL), with some -** exclusions (see below). This basically means that you can get the full source -** code for nothing, so long as you adhere to a few rules. -** -** Under the LGPL you may use YUNI for any purpose you wish, and modify it if you -** require, as long as you: -** -** Pass on the (modified) YUNI source code with your software, with original -** copyrights intact : -** * If you distribute electronically, the source can be a separate download -** (either from your own site if you modified YUNI, or to the official YUNI -** website if you used an unmodified version) – just include a link in your -** documentation -** * If you distribute physical media, the YUNI source that you used to build -** your application should be included on that media -** Make it clear where you have customised it. -** -** In addition to the LGPL license text, the following exceptions / clarifications -** to the LGPL conditions apply to YUNI: -** -** * Making modifications to YUNI configuration files, build scripts and -** configuration headers such as yuni/platform.h in order to create a -** customised build setup of YUNI with the otherwise unmodified source code, -** does not constitute a derived work -** * Building against YUNI headers which have inlined code does not constitute a -** derived work -** * Code which subclasses YUNI classes outside of the YUNI libraries does not -** form a derived work -** * Statically linking the YUNI libraries into a user application does not make -** the user application a derived work. -** * Using source code obsfucation on the YUNI source code when distributing it -** is not permitted. -** As per the terms of the LGPL, a "derived work" is one for which you have to -** distribute source code for, so when the clauses above define something as not -** a derived work, it means you don't have to distribute source code for it. -** However, the original YUNI source code with all modifications must always be -** made available. -*/ -#pragma once -#include "../../yuni.h" -#include "../../thread/policy.h" -#include "../static/types.h" -#include "../static/assert.h" -#include "../static/remove.h" -#include "../smartptr.h" -#include "traits.h" -#include "../dynamiclibrary/symbol.h" -#include "fwd.h" - - -<% -require File.dirname(__FILE__) + '/../../../tools/generators/commons.rb' -generator = Generator.new() -%> -<%=generator.thisHeaderHasBeenGenerated("bind.h.generator.hpp")%> - - -namespace Yuni -{ - - /*! - ** \brief A delegate implementation - ** \ingroup Events - ** - ** How to bind a mere function : - ** \code - ** #include - ** #include - ** - ** static int Foo(int value) - ** { - ** std::cout << "Foo: " << value << std::endl; - ** return 0; - ** } - ** - ** int main() - ** { - ** Yuni::Bind callback; - ** callback.bind(&Foo); - ** callback(42); - ** callback(61); - ** callback(-1) - ** return 0; - ** } - ** \endcode - ** - ** How to bind a member of an object : - ** \code - ** #include - ** #include - ** - ** class Foo - ** { - ** public: - ** int bar(int value) - ** { - ** std::cout << "Foo::bar : " << value << std::endl; - ** return 0; - ** } - ** int bar2(int value) - ** { - ** std::cout << "Foo::bar2 : " << value << std::endl; - ** return 0; - ** } - ** }; - ** - ** int main() - ** { - ** Foo foo; - ** Yuni::Bind callback; - ** callback.bind(foo, &Foo::bar); - ** callback(42); - ** callback(61); - ** callback(-1) - ** callback.bind(foo, &Foo::bar2); - ** callback(42); - ** callback(61); - ** callback(-1) - ** return 0; - ** } - ** \endcode - ** - ** This class is thread-safe, this is guaranteed by the use of smartptr. - ** - ** \note This class does not take care of deleted objects. It is the responsibility - ** of the user to unbind the delegate before the linked object is delete and/or - ** to not invoke the delegate when the object does not exist. - ** - ** \note It is safe to provide a null pointer when binding the delegate - ** \note It is always safe to invoke the delegate when unbound. - ** - ** \tparam P The prototype of the targetted function/member - */ - template - class YUNI_DECL Bind; - - - - - - - - - - - // - // --- Specializations for Bind<> --- - // - - -<% -(0..(generator.argumentCount)).each do |i| -[ ["class R" + generator.templateParameterList(i), "R ("+generator.list(i) + ")", "void"], - ["class R" + generator.templateParameterList(i), "R (*)(" + generator.list(i) + ")", "void"], - ["class ClassT, class R" + generator.templateParameterList(i), "R (ClassT::*)(" + generator.list(i) + ")", "ClassT"] ].each do |tmpl| -%> - - /* - ** \brief Bind to a function/member with <%=generator.xArgumentsToStr(i)%> (Specialization) - */ - template<<%=tmpl[0]%>> - class YUNI_DECL Bind<<%=tmpl[1]%>, <%=tmpl[2]%>> final - { - public: - //! The Bind Type - typedef Bind<<%=tmpl[1]%>, <%=tmpl[2]%>> Type; - //! The Bind Type - typedef Bind<<%=tmpl[1]%>, <%=tmpl[2]%>> BindType; - -<%=generator.include("yuni/core/bind/bind.h.generator.commonstypes.hpp", i) %> - - public: - /*! - ** \brief Instanciate a Yuni::Bind from an exported symbol from a dynamic library - ** \param symbol A symbol from a shared library - ** \return A new bind - */ - static BindType FromSymbol(const Yuni::DynamicLibrary::Symbol& symbol); - - - public: - //! \name Constructor & Destructor - //@{ - //! Default Constructor - Bind(); - - //! Copy constructor - Bind(const Bind& rhs); - # ifdef YUNI_HAS_CPP_MOVE - //! Move constructor - Bind(Bind&& rhs); - # endif - - /*! - ** \brief Constructor, from a pointer-to-method - ** - ** \param c A pointer to an object (can be null) - ** \param member A pointer-to-member - */ - template Bind(C* c, R (C::*member)(<%=generator.list(i)%>)); - - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - /*! - ** \brief Constructor from a functor, most likely a lambda - ** \param functor A functor - */ - template Bind(C&& functor); - # else - /*! - ** \brief Constructor from a pointer-to-function - ** \param pointer A pointer-to-function - */ - Bind(R (*pointer)(<%=generator.list(i)%>)); - # endif - //@} - - - //! \name Bind - //@{ - /*! - ** \brief Bind to a function - ** - ** \param pointer A pointer-to-function - */ - void bind(R (*pointer)(<%=generator.list(i)%>)); - - /*! - ** \brief Bind to a function with a custom and persistent user data - ** - ** \tparam U The type of the user data - ** \param pointer A pointer-to-function - ** \param userdata The userdata that will be copied and stored - */ - template - void bind(R (*pointer)(<%=generator.list(i,'A', "", ", ")%>U), typename WithUserData::ParameterType userdata); - - /*! - ** \brief Bind to an object member - ** - ** \tparam C Any class - ** \param c A pointer to an object (can be null) - ** \param member A pointer-to-member - */ - template void bind(C* c, R (C::*member)(<%=generator.list(i)%>)); - - /*! - ** \brief Bind to an object member - ** - ** \tparam C Any smartptr - ** \param c A pointer to an object (can be null) - ** \param member A pointer-to-member - */ - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - void bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i)%>)); - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - void bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i)%>) const); - - /*! - ** \brief Bind to a const object member - ** - ** \tparam C Any class - ** \param c A pointer to an object (can be null) - ** \param member A pointer-to-member - */ - template void bind(const C* c, R (C::*member)(<%=generator.list(i)%>) const); - - /*! - ** \brief Bind to an object member with a custom and persistent user data - ** - ** \tparam U The type of the user data - ** \tparam C Any class - ** \param c A pointer to an object (can be null) - ** \param member A pointer-to-member - ** \param userdata User data - */ - template - void bind(C* c, R (C::*member)(<%=generator.list(i,'A', "", ", ")%>U), typename WithUserData::ParameterType userdata); - template - void bind(const C* c, R (C::*member)(<%=generator.list(i,'A', "", ", ")%>U) const, typename WithUserData::ParameterType userdata); - - /*! - ** \brief Bind to an object member with a custom and persistent user data - ** - ** \tparam C Any smartptr - ** \param c A pointer to an object (can be null) - ** \param member A pointer-to-member - ** \param userdata User data - */ - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - void bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i,'A', "", ", ")%>U), - typename WithUserData::ParameterType userdata); - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - void bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i,'A', "", ", ")%>U) const, - typename WithUserData::ParameterType userdata); - - - /*! - ** \brief Bind from another Bind object - */ - void bind(const Bind& rhs); - - /*! - ** \brief Bind from a library symbol - ** - ** \param symbol A symbol from a dynamic library - */ - void bindFromSymbol(const Yuni::DynamicLibrary::Symbol& symbol); - - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - /*! - ** \brief Bind from a functor, most likely a lambda - */ - template void bind(C&& functor); - # endif - - //@} // Bind - - - //! \name Unbind - //@{ - /*! - ** \brief Unbind - ** - ** It is safe to call this method several times - */ - void unbind(); - - //! \see unbind - void clear(); - - //! Get if the object is binded - bool empty() const; - //@} - - - //! \name Invoke - //@{ - /*! - ** \brief Invoke the delegate - ** - ** The operator () can be used instead. - */ - R invoke(<%=generator.variableList(i)%>) const; - - /*! - ** \brief Invoke the bind using a getter for the arguments. - ** - ** Nothing will happen if the pointer is null - ** However, the returned value may not be what we shall expect - ** (the default constructor of the returned type is used in this case). - ** - ** \param userdata Some user data - */ - template class ArgGetterT> - R callWithArgumentGetter(UserTypeT userdata) const; - //@} - - - //! \name Print - //@{ - /*! - ** \brief Print the value to the std::ostream - ** - ** \param out A stream used to write output - */ - void print(std::ostream& out) const; - //@} - - - //! \name Inheritance - //@{ - /*! - ** \brief Get the raw pointer to the binded object (if any) - ** - ** If bound to a class, the return value will never be null. There is no way - ** to know statically the type of the object. - ** \warning It is the responsability to the user to use this method with care - ** - ** \return A non-null pointer if bound to a class - */ - const void* object() const; - - //! Get if the attached class is a descendant of 'IEventObserverBase' - bool isDescendantOfIEventObserverBase() const; - //! Get if the attached class is a real descendant of 'IEventObserverBase' - bool isDescendantOf(const IEventObserverBase* obj) const; - - /*! - ** \brief Get the pointer to the binded object (if any) cast into IEventObserverBase - ** - ** \warning This method should never be used by the user - ** \return A non-null pointer if bound to a class - */ - const IEventObserverBase* observerBaseObject() const; - //@} - - - //! \name Operators - //@{ - //! Get if the object is binded - bool operator ! () const; - /*! - ** \brief Invoke the delegate - ** \see invoke() - */ - R operator () (<%=generator.variableList(i)%>) const; - //! Assignment with another Bind object - Bind& operator = (const Bind& rhs); - # ifdef YUNI_HAS_CPP_MOVE - //! Assignment move - Bind& operator = (Bind&& symbol); - # endif - //! Assignment with a pointer-to-function - Bind& operator = (R (*pointer)(<%=generator.list(i)%>)); - //! Assignment with a library symbol - Bind& operator = (const Yuni::DynamicLibrary::Symbol& symbol); - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - //! Assignment from a functor, most likely a lambda - template Bind& operator = (C&& functor); - # endif - - //! Comparison with a pointer-to-function - bool operator == (R (*pointer)(<%=generator.list(i)%>)) const; - //! Comparison with a pointer-to-object - template bool operator == (const U* object) const; - //@} - - private: - //! Empty callback when not binded (returns a default value) - R emptyCallback(<%=generator.list(i)%>); - //! Empty callback when not binded (returns void) - void emptyCallbackReturnsVoid(<%=generator.list(i)%>); - - private: - //! The holder type - typedef Private::BindImpl::IPointer)> IHolder; - - /*! - ** \brief Pointer to function/member - ** \internal The smartptr is used to guarantee the thread-safety, and to avoid - ** expensive copies - */ - SmartPtr pHolder; - - template friend struct Yuni::Private::BindImpl::MoveConstructor; - - }; // class Bind)> - - - - -<% end end %> - - - - - - - -} // namespace Yuni - -#include "bind.hxx" - - - - - -template -inline std::ostream& operator << (std::ostream& out, const Yuni::Bind& rhs) -{ - rhs.print(out); - return out; -} - - -// Comparison with any pointer-to-object -template -inline bool operator == (const U* object, const Yuni::Bind& bind) -{ - return (bind == object); -} - -// Comparison with any pointer-to-object -template -inline bool operator != (const U* object, const Yuni::Bind& bind) -{ - return (bind != object); -} - - -<% (0..(generator.argumentCount)).each do |i| %> -template> -inline bool operator == (R (*pointer)(<%=generator.list(i)%>), const Yuni::Bind& bind) -{ - return (bind == pointer); -} - -template> -inline bool operator != (R (*pointer)(<%=generator.list(i)%>), const Yuni::Bind& bind) -{ - return (bind != pointer); -} - - -<% end %> diff --git a/src/ext/yuni/src/yuni/core/bind/bind.hxx.generator.hpp b/src/ext/yuni/src/yuni/core/bind/bind.hxx.generator.hpp deleted file mode 100644 index fb69564faa..0000000000 --- a/src/ext/yuni/src/yuni/core/bind/bind.hxx.generator.hpp +++ /dev/null @@ -1,547 +0,0 @@ -/* -** YUNI's default license is the GNU Lesser Public License (LGPL), with some -** exclusions (see below). This basically means that you can get the full source -** code for nothing, so long as you adhere to a few rules. -** -** Under the LGPL you may use YUNI for any purpose you wish, and modify it if you -** require, as long as you: -** -** Pass on the (modified) YUNI source code with your software, with original -** copyrights intact : -** * If you distribute electronically, the source can be a separate download -** (either from your own site if you modified YUNI, or to the official YUNI -** website if you used an unmodified version) – just include a link in your -** documentation -** * If you distribute physical media, the YUNI source that you used to build -** your application should be included on that media -** Make it clear where you have customised it. -** -** In addition to the LGPL license text, the following exceptions / clarifications -** to the LGPL conditions apply to YUNI: -** -** * Making modifications to YUNI configuration files, build scripts and -** configuration headers such as yuni/platform.h in order to create a -** customised build setup of YUNI with the otherwise unmodified source code, -** does not constitute a derived work -** * Building against YUNI headers which have inlined code does not constitute a -** derived work -** * Code which subclasses YUNI classes outside of the YUNI libraries does not -** form a derived work -** * Statically linking the YUNI libraries into a user application does not make -** the user application a derived work. -** * Using source code obsfucation on the YUNI source code when distributing it -** is not permitted. -** As per the terms of the LGPL, a "derived work" is one for which you have to -** distribute source code for, so when the clauses above define something as not -** a derived work, it means you don't have to distribute source code for it. -** However, the original YUNI source code with all modifications must always be -** made available. -*/ -#pragma once -#include "bind.h" - - - -<% -require File.dirname(__FILE__) + '/../../../tools/generators/commons.rb' -generator = Generator.new() -%> -<%=generator.thisHeaderHasBeenGenerated("bind.hxx.generator.hpp")%> - - - - -namespace Yuni -{ - - -<% -(0..(generator.argumentCount)).each do |i| -[ ["class R" + generator.templateParameterList(i), "R ("+generator.list(i) + ")", "void"], - ["class R" + generator.templateParameterList(i), "R (*)(" + generator.list(i) + ")", "void"], - ["class ClassT, class R" + generator.templateParameterList(i), "R (ClassT::*)(" + generator.list(i) + ")", "ClassT"] ].each do |tmpl| - -%> - - // Constructor - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::Bind() - : pHolder(new Private::BindImpl::None)>()) // unbind - {} - - // Constructor - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::Bind(const Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& rhs) : - pHolder(rhs.pHolder) - {} - - # ifdef YUNI_HAS_CPP_MOVE - // Move Constructor - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::Bind(Bind&& rhs) - { - // \important VS may call the other constructor `C&&`... - pHolder.swap(rhs.pHolder); - } - # endif - - // Constructor - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>> - Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::FromSymbol(const Yuni::DynamicLibrary::Symbol& symbol) - { - BindType result; - result.bindFromSymbol(symbol); - return result; - } - - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - // Constructor from a functor - template<<%=tmpl[0]%>> - template - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::Bind(C&& functor) - { - // When moving a bind (instead of copying it), it seems that Visual Studio might call - // this constructor instead of `Bind&&` (works as expected with gcc and clang) - if (Static::Type::Equal::Yes) // moving Bind&& -> Bind&& - { - // instanciating the swap method only when the type requires it - Yuni::Private::BindImpl::MoveConstructor::Yes>::SwapBind(pHolder, functor); - } - else - pHolder = new Private::BindImpl::BoundWithFunctor)>(std::forward(functor)); - } - - # else - - // Constructor: Pointer-to-function - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::Bind(R (*pointer)(<%=generator.list(i)%>)) - { - bind(pointer); - } - - # endif - - // Constructor: pointer-to-member - template<<%=tmpl[0]%>> - template - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::Bind(C* c, R (C::*member)(<%=generator.list(i)%>)) - { - bind(c, member); - } - - - - - // Bind: Pointer-to-function - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(R (*pointer)(<%=generator.list(i)%>)) - { - pHolder = new Private::BindImpl::BoundWithFunction)>(pointer); - } - - - // Bind: Pointer-to-function (from a library symbol) - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bindFromSymbol(const Yuni::DynamicLibrary::Symbol& symbol) - { - if (symbol.valid()) - { - pHolder = new Private::BindImpl::BoundWithFunction)>( - reinterpret_cast(symbol.ptr())); - } - else - unbind(); - } - - // Bind: Pointer-to-function + user data - template<<%=tmpl[0]%>> - template - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(R (*pointer)(<%=generator.list(i, "A", "", ", ")%>U), - typename Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::template WithUserData::ParameterType userdata) - { - pHolder = new Private::BindImpl::BoundWithFunctionAndUserData - ::ParameterType, R (<%=generator.list(i, "A", "", ", ")%>U)>(pointer, userdata); - } - - - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - // Bind: functor - template<<%=tmpl[0]%>> - template - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(C&& functor) - { - // When moving a bind (instead of copying it), it seems that Visual Studio might call - // this constructor instead of `Bind&&` (works as expected with gcc and clang) - if (Static::Type::Equal::Yes) // moving Bind&& -> Bind&& - { - // instanciating the swap method only when the type requires it - Yuni::Private::BindImpl::MoveConstructor::Yes>::SwapBind(pHolder, functor); - } - else - pHolder = new Private::BindImpl::BoundWithFunctor)>(std::forward(functor)); - } - # endif - - - // Bind: pointer-to-member - template<<%=tmpl[0]%>> - template - void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(C* c, R (C::*member)(<%=generator.list(i)%>)) - { - if (c) - { - // The object is not null, go ahead - // Assigning a new bind - pHolder = new Private::BindImpl::BoundWithMember)>(c, member); - } - else - // The object is null, we should unbind - unbind(); - } - - - // Bind: pointer-to-member const - template<<%=tmpl[0]%>> - template - void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const C* c, R (C::*member)(<%=generator.list(i)%>) const) - { - if (c) - { - // The object is not null, go ahead - // Assigning a new bind - typedef R (C::*MemberType)(<%=generator.list(i)%>); - pHolder = new Private::BindImpl::BoundWithMember)> - (const_cast(c), reinterpret_cast(member)); - } - else - // The object is null, we should unbind - unbind(); - } - - - // Bind: pointer-to-member const - template<<%=tmpl[0]%>> - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - inline void - Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i)%>)) - { - if (!(!c)) - { - // The object is not null, go ahead - // Assigning a new bind - typedef R (C::*MemberType)(<%=generator.list(i)%>); - typedef SmartPtr PtrT; - pHolder = new Private::BindImpl::BoundWithSmartPtrMember)> - (c, reinterpret_cast(member)); - } - else - // The object is null, we should unbind - unbind(); - } - - - // Bind: pointer-to-member const - template<<%=tmpl[0]%>> - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - inline void - Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i)%>) const) - { - if (!(!c)) - { - // The object is not null, go ahead - // Assigning a new bind - typedef R (C::*MemberType)(<%=generator.list(i)%>); - typedef SmartPtr PtrT; - pHolder = new Private::BindImpl::BoundWithSmartPtrMember)> - (c, reinterpret_cast(member)); - } - else - // The object is null, we should unbind - unbind(); - } - - - // Bind: pointer-to-member const - template<<%=tmpl[0]%>> - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - inline void - Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i,"A", "", ", ")%>U), - typename Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::template WithUserData::ParameterType userdata) - { - if (!(!c)) - { - // The object is not null, go ahead - // Assigning a new bind - typedef SmartPtr PtrT; - pHolder = new Private::BindImpl::BoundWithSmartPtrMemberAndUserData< - typename WithUserData::ParameterType, PtrT, R(<%=generator.list(i,"A","",", ")%>U)> - (c, member, userdata); - } - else - // The object is null, we should unbind - unbind(); - } - - - // Bind: pointer-to-member const - template<<%=tmpl[0]%>> - template class OwspP, template class ChckP, class ConvP, - template class StorP, template class ConsP> - inline void - Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const SmartPtr& c, R (C::*member)(<%=generator.list(i,"A", "", ", ")%>U) const, - typename Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::template WithUserData::ParameterType userdata) - { - if (!(!c)) - { - // The object is not null, go ahead - // Assigning a new bind - typedef SmartPtr PtrT; - pHolder = new Private::BindImpl::BoundWithSmartPtrMemberAndUserData< - typename WithUserData::ParameterType, PtrT, R(<%=generator.list(i,"A","",", ")%>U)> - (c, member, userdata); - } - else - // The object is null, we should unbind - unbind(); - } - - - template<<%=tmpl[0]%>> - template - void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(C* c, R (C::*member)(<%=generator.list(i,"A","",", ")%>U), - typename Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::template WithUserData::ParameterType userdata) - { - if (c) - { - // The object is not null, go ahead - // Assigning a new bind - pHolder = new Private::BindImpl::BoundWithMemberAndUserData< - typename WithUserData::ParameterType,C, R(<%=generator.list(i,"A","",", ")%>U)> - (c, member, userdata); - } - else - // The object is null, we should unbind - unbind(); - } - - - template<<%=tmpl[0]%>> - template - void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const C* c, R (C::*member)(<%=generator.list(i,"A","",", ")%>U) const, - typename Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::template WithUserData::ParameterType userdata) - { - if (c) - { - // The object is not null, go ahead - // Assigning a new bind - typedef R (C::*MemberType)(<%=generator.list(i,"A","",", ")%>U); - pHolder = new Private::BindImpl::BoundWithMemberAndUserData< - typename WithUserData::ParameterType,C, R(<%=generator.list(i,"A","",", ")%>U)> - (const_cast(c), reinterpret_cast(member), userdata); - } - else - // The object is null, we should unbind - unbind(); - } - - - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::bind(const Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& rhs) - { - // Inc the reference count - pHolder = rhs.pHolder; - } - - - // Bind: unbind - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::unbind() - { - pHolder = new Private::BindImpl::None)>(); // unbind - } - - - // Bind: unbind - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::clear() - { - unbind(); - } - - - template<<%=tmpl[0]%>> - inline bool Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::empty() const - { - return pHolder->empty(); - } - - - template<<%=tmpl[0]%>> - template class ArgGetterT> - inline R - Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::callWithArgumentGetter(UserTypeT userdata) const - { - (void) userdata; - return invoke(<%= - ret = '' - (0..i-1).each do |j| - if j > 0 - ret += ', ' - end - if ((j + 1).modulo(2) == 0) - ret += "\n\t\t\t\t" - end - - ret += "ArgGetterT::Get(userdata, " + j.to_s + ")" - end - ret %>); - } - - - - - template<<%=tmpl[0]%>> - inline R Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::invoke(<%=generator.variableList(i)%>) const - { - return pHolder->invoke(<%=generator.list(i,'a')%>); - } - - - template<<%=tmpl[0]%>> - inline bool Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator ! () const - { - return empty(); - } - - - template<<%=tmpl[0]%>> - inline R Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator () (<%=generator.variableList(i)%>) const - { - return pHolder->invoke(<%=generator.list(i,'a')%>); - } - - - template<<%=tmpl[0]%>> - inline R Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::emptyCallback(<%=generator.list(i,"A")%>) - { - return R(); - } - - template<<%=tmpl[0]%>> - inline const void* Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::object() const - { - return pHolder->object(); - } - - template<<%=tmpl[0]%>> - inline const IEventObserverBase* Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::observerBaseObject() const - { - return pHolder->observerBaseObject(); - } - - template<<%=tmpl[0]%>> - inline bool Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::isDescendantOf(const IEventObserverBase* obj) const - { - return pHolder->isDescendantOf(obj); - } - - template<<%=tmpl[0]%>> - inline bool Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::isDescendantOfIEventObserverBase() const - { - return pHolder->isDescendantOfIEventObserverBase(); - } - - - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::print(std::ostream& out) const - { - return pHolder->print(out); - } - - - - template<<%=tmpl[0]%>> - inline void Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::emptyCallbackReturnsVoid(<%=generator.list(i,"A")%>) - { - /* Do nothing */ - } - - - - - - - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator = (R (*pointer)(<%=generator.list(i)%>)) - { - bind(pointer); - return *this; - } - - - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator = (const Yuni::DynamicLibrary::Symbol& symbol) - { - bind(symbol); - return *this; - } - - - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator = (const Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& rhs) - { - // Inc the reference count - pHolder = rhs.pHolder; - return *this; - } - - - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - template<<%=tmpl[0]%>> - template - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator = (C&& functor) - { - // Inc the reference count - pHolder = new Private::BindImpl::BoundWithFunctor)>(std::forward(functor)); - return *this; - } - # endif - - - # ifdef YUNI_HAS_CPP_MOVE - template<<%=tmpl[0]%>> - inline Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>& Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator = (Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>&& rhs) - { - pHolder.swap(rhs.pHolder); - return *this; - } - # endif - - template<<%=tmpl[0]%>> - inline bool Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator == (R (*pointer)(<%=generator.list(i)%>)) const - { - return pHolder->compareWithPointerToFunction(pointer); - } - - template<<%=tmpl[0]%>> - template - inline bool Bind<<%=tmpl[1]%>, <%=tmpl[2]%>>::operator == (const U* object) const - { - return pHolder->compareWithPointerToObject(static_cast(object)); - } - - - - -<% end end %> - -} // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/bind/traits.h.generator.hpp b/src/ext/yuni/src/yuni/core/bind/traits.h.generator.hpp deleted file mode 100644 index 5da84e3c29..0000000000 --- a/src/ext/yuni/src/yuni/core/bind/traits.h.generator.hpp +++ /dev/null @@ -1,805 +0,0 @@ -/* -** YUNI's default license is the GNU Lesser Public License (LGPL), with some -** exclusions (see below). This basically means that you can get the full source -** code for nothing, so long as you adhere to a few rules. -** -** Under the LGPL you may use YUNI for any purpose you wish, and modify it if you -** require, as long as you: -** -** Pass on the (modified) YUNI source code with your software, with original -** copyrights intact : -** * If you distribute electronically, the source can be a separate download -** (either from your own site if you modified YUNI, or to the official YUNI -** website if you used an unmodified version) – just include a link in your -** documentation -** * If you distribute physical media, the YUNI source that you used to build -** your application should be included on that media -** Make it clear where you have customised it. -** -** In addition to the LGPL license text, the following exceptions / clarifications -** to the LGPL conditions apply to YUNI: -** -** * Making modifications to YUNI configuration files, build scripts and -** configuration headers such as yuni/platform.h in order to create a -** customised build setup of YUNI with the otherwise unmodified source code, -** does not constitute a derived work -** * Building against YUNI headers which have inlined code does not constitute a -** derived work -** * Code which subclasses YUNI classes outside of the YUNI libraries does not -** form a derived work -** * Statically linking the YUNI libraries into a user application does not make -** the user application a derived work. -** * Using source code obsfucation on the YUNI source code when distributing it -** is not permitted. -** As per the terms of the LGPL, a "derived work" is one for which you have to -** distribute source code for, so when the clauses above define something as not -** a derived work, it means you don't have to distribute source code for it. -** However, the original YUNI source code with all modifications must always be -** made available. -*/ -#pragma once -<% -require File.dirname(__FILE__) + '/../../../tools/generators/commons.rb' -generator = Generator.new() -%> -<%=generator.thisHeaderHasBeenGenerated("traits.h.generator.hpp")%> -#include "../event/interfaces.h" -#include "../static/inherit.h" -#include "../static/dynamiccast.h" - - - - -namespace Yuni -{ - - // Forward declaration - template class Bind; - - -} // namespace Yuni - -namespace Yuni -{ -namespace Private -{ -namespace BindImpl -{ - - - // Forward declarations for classes which will hold informations about the - // targetted function or member - - /*! - ** \brief Interface - ** - ** \tparam P The prototype of the function/member - */ - template class IPointer; - - /*! - ** \brief Dummy implementation, does nothing, used by unbind - ** - ** \tparam P The prototype of the function/member - */ - template class None; - - /*! - ** \brief Binding with a function - ** - ** \tparam P The prototype of the member - */ - template class BoundWithFunction; - - # ifdef YUNI_HAS_CPP_BIND_LAMBDA - /*! - ** \brief Binding with a functor - ** - ** \tparam C The type of the functor - ** \tparam P The prototype of the member - */ - template class BoundWithFunctor; - # endif - - /*! - ** \brief Binding with a function - ** - ** \tparam U Type of the user data - ** \tparam P The prototype of the member - */ - template class BoundWithFunctionAndUserData; - - /*! - ** \brief Binding with a member - ** - ** \tparam C Any class - ** \tparam P The prototype of the member - */ - template class BoundWithMember; - - /*! - ** \brief Binding with a member and a user data - ** - ** \tparam U Type of the user data - ** \tparam C Any class - ** \tparam P The prototype of the member - */ - template class BoundWithMemberAndUserData; - - - /*! - ** \brief Binding with a member - ** - ** \tparam C Any class - ** \tparam P The prototype of the member - */ - template class BoundWithSmartPtrMember; - - /*! - ** \brief Binding with a member and a user data - ** - ** \tparam U Type of the user data - ** \tparam C Any class - ** \tparam P The prototype of the member - */ - template class BoundWithSmartPtrMemberAndUserData; - - - - - - /*! - ** \brief Helper to determine the type of an argument from its index - ** - ** \tparam P The prototype of a function/member - ** \tparam I The index of the argument (zero-based) - */ - template - struct Argument - { - // By default the argument does not exist, but we provide a valid type anyway - typedef Yuni::None Type; - }; - - - // There is no need for a partial specialization when the prototype does not - // have any argument. `Yuni::None` will always be returned -<% (1..generator.argumentCount).each do |i| %> - - // Partial Specialization when the prototype has <%=generator.xArgumentsToStr(i)%> -<% (0..i-1).each do |j| %> // Argument <%=j%> - template> - struct Argument), <%=j%>> { typedef A<%=j%> Type; }; -<% end end %> - - - - template - struct Parameter - { - typedef const - typename Static::Remove::Const< typename Static::Remove::RefOnly::Type>::Type - & Type; - }; - - - template - struct Parameter - { - typedef const T* Type; - }; - - template - struct Parameter - { - typedef T* Type; - }; - - template - struct Parameter - { - typedef const T* Type; - }; - - template - struct Parameter - { - typedef T* Type; - }; - - template - struct Parameter - { - typedef const T& Type; - }; - - template - struct Parameter - { - typedef const T& Type; - }; - - - - - - - - // class IPointer -<% (0..generator.argumentCount-1).each do |i| %> - template> - class IPointer)> - { - public: - //! Destructor - virtual ~IPointer() {} - //! Invoke the delegate - virtual R invoke(<%=generator.variableList(i)%>) const = 0; - - //! Get if the object is binded - virtual bool empty() const { return false; } - - //! Get the pointer to object - virtual const void* object() const = 0; - - //! Get the pointer to object cast into IEventObserverBase - virtual const IEventObserverBase* observerBaseObject() const = 0; - - //! Get if the attached class is a descendant of 'IEventObserverBase' - virtual bool isDescendantOf(const IEventObserverBase* obj) const = 0; - - //! Get if the attached class is a descendant of 'IEventObserverBase' - virtual bool isDescendantOfIEventObserverBase() const = 0; - - //! Compare with a mere pointer-to-function - virtual bool compareWithPointerToFunction(R (*pointer)(<%=generator.list(i)%>)) const = 0; - //! Compare with a pointer-to-object - virtual bool compareWithPointerToObject(const void* object) const = 0; - - }; -<% end %> - - - - // class Void - -<% (0..generator.argumentCount-1).each do |i| %> - template> - class None)> final : - public IPointer)> - { - public: - //! Destructor - virtual ~None() {} - - - virtual R invoke(<%=generator.list(i)%>) const override - { - return R(); - } - - virtual bool empty() const override - { - return true; - } - - virtual const void* object() const override - { - return NULL; - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return NULL; - } - - virtual bool isDescendantOf(const IEventObserverBase*) const override - { - return false; - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return false; - } - - virtual bool compareWithPointerToFunction(R (*pointer)(<%=generator.list(i)%>)) const override - { - return (nullptr == pointer); - } - - virtual bool compareWithPointerToObject(const void*) const override - { - return false; - } - - }; // class None)> -<% end %> - - - - // class BoundWithFunction - -<% (0..generator.argumentCount-1).each do |i| %> - template> - class BoundWithFunction)> final : - public IPointer)> - { - public: - //! Destructor - virtual ~BoundWithFunction() {} - - BoundWithFunction(R(*pointer)(<%=generator.list(i)%>)) : - pPointer(pointer) - { - assert(pointer != nullptr and "binded pointer-to-function can not be null"); - } - - virtual R invoke(<%=generator.variableList(i)%>) const override - { - return (*pPointer)(<%=generator.list(i, 'a')%>); - } - - virtual const void* object() const override - { - return NULL; - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return NULL; - } - - virtual bool isDescendantOf(const IEventObserverBase*) const override - { - return false; - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return false; - } - - virtual bool compareWithPointerToFunction(R (*pointer)(<%=generator.list(i)%>)) const override - { - return (reinterpret_cast(pPointer) == reinterpret_cast(pointer)); - } - - virtual bool compareWithPointerToObject(const void*) const override - { - return false; - } - - - private: - //! Pointer-to-function - R (*pPointer)(<%=generator.list(i)%>); - - }; // class BoundWithFunction)> -<% end %> - - - // class BoundWithFunctor - -# ifdef YUNI_HAS_CPP_BIND_LAMBDA -<% (0..generator.argumentCount-1).each do |i| %> - template> - class BoundWithFunctor)> final : - public IPointer)> - { - public: - //! Destructor - virtual ~BoundWithFunctor() {} - - BoundWithFunctor(C&& functor) : - pFunctor(std::forward(functor)) - {} - - virtual R invoke(<%=generator.variableList(i)%>) const override - { - return pFunctor(<%=generator.list(i, 'a')%>); - } - - virtual const void* object() const override - { - return nullptr; - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return nullptr; - } - - virtual bool isDescendantOf(const IEventObserverBase*) const override - { - return false; - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return false; - } - - virtual bool compareWithPointerToFunction(R (*pointer)(<%=generator.list(i)%>)) const override - { - return (reinterpret_cast(&pFunctor) == reinterpret_cast(pointer)); - } - - virtual bool compareWithPointerToObject(const void*) const override - { - return false; - } - - - private: - //! Pointer-to-function - C pFunctor; - - }; // class BoundWithFunctor)> - -<% end %> -# endif - - - - - - // class BoundWithFunctionAndUserData - -<% (1..generator.argumentCount).each do |i| %> - template> - class BoundWithFunctionAndUserData)> final : - public IPointer)> - { - public: - BoundWithFunctionAndUserData(R(*pointer)(<%=generator.list(i)%>), U userdata) - : pPointer(pointer), pUserdata(userdata) - { - assert(pointer != NULL and "binded pointer-to-function can not be null"); - } - - virtual R invoke(<%=generator.variableList(i-1)%>) const override - { - return (*pPointer)(<%=generator.list(i-1, 'a', "", ", ")%>*const_cast(&pUserdata)); - } - - virtual const void* object() const override - { - return NULL; - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return NULL; - } - - virtual bool isDescendantOf(const IEventObserverBase*) const override - { - return false; - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return false; - } - - virtual bool compareWithPointerToFunction(R (*pointer)(<%=generator.list(i-1)%>)) const override - { - return (reinterpret_cast(pPointer) == reinterpret_cast(pointer)); - } - - virtual bool compareWithPointerToObject(const void*) const override - { - return false; - } - - - private: - //! Pointer-to-function - R (*pPointer)(<%=generator.list(i)%>); - //! Storage type - typedef typename Static::Remove::RefOnly>::Type UserDataTypeByCopy; - //! The user data - UserDataTypeByCopy pUserdata; - - }; // class BoundWithFunctionAndUserData)> - - -<% end %> - - - - - - - - // class BoundWithMember - -<% (0..generator.argumentCount-1).each do |i| %> - template> - class BoundWithMember)> final : - public IPointer)> - { - public: - //! \name Constructor - //@{ - //! Constructor - BoundWithMember(C* c, R(C::*member)(<%=generator.list(i)%>)) : - pThis(c), - pMember(member) - { - assert(c != NULL and "binded object can not be null"); - } - //@} - - virtual R invoke(<%=generator.variableList(i)%>) const override - { - return (pThis->*pMember)(<%=generator.list(i, 'a')%>); - } - - virtual const void* object() const override - { - return reinterpret_cast(pThis); - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return Static::DynamicCastWhenInherits::PerformConst(pThis); - } - - virtual bool isDescendantOf(const IEventObserverBase* obj) const override - { - return Static::DynamicCastWhenInherits::Equals(obj, pThis); - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return Static::DynamicCastWhenInherits::Yes; - } - - virtual bool compareWithPointerToFunction(R (*)(<%=generator.list(i)%>)) const override - { - return false; - } - - virtual bool compareWithPointerToObject(const void* object) const override - { - return (reinterpret_cast(object) == pThis); - } - - - private: - //! Pointer to the object - mutable C* pThis; - //! Pointer-to-member - mutable R (C::*pMember)(<%=generator.list(i)%>); - - }; // class BoundWithMember)> - - -<% end %> - - - - - - - - // class BoundWithMemberAndUserData - -<% (1..generator.argumentCount).each do |i| %> - template> - class BoundWithMemberAndUserData)> final : - public IPointer)> - { - public: - typedef typename Static::Remove::RefOnly>::Type UserDataTypeByCopy; - - public: - BoundWithMemberAndUserData(C* c, R(C::*member)(<%=generator.list(i)%>), U userdata) : - pThis(c), - pMember(member), - pUserdata(userdata) - { - assert(c != NULL and "binded object can not be null"); - } - - virtual R invoke(<%=generator.variableList(i-1)%>) const override - { - return (pThis->*pMember)(<%=generator.list(i-1, 'a', "", ", ")%>const_cast(pUserdata)); - } - - virtual const void* object() const override - { - return reinterpret_cast(pThis); - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return Static::DynamicCastWhenInherits::PerformConst(pThis); - } - - virtual bool isDescendantOf(const IEventObserverBase* obj) const override - { - return Static::DynamicCastWhenInherits::Equals(obj, pThis); - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return Static::DynamicCastWhenInherits::Yes; - } - - - virtual bool compareWithPointerToFunction(R (*)(<%=generator.list(i-1)%>)) const override - { - return false; - } - - virtual bool compareWithPointerToObject(const void* object) const override - { - return (reinterpret_cast(object) == pThis); - } - - - private: - //! Pointer to the object - mutable C* pThis; - //! Pointer-to-member - mutable R (C::*pMember)(<%=generator.list(i)%>); - //! Userdata - UserDataTypeByCopy pUserdata; - - }; // class BoundWithMemberAndUserData)> - - -<% end %> - - -<% (0..generator.argumentCount-1).each do |i| %> - template> - class BoundWithSmartPtrMember)> final : - public IPointer)> - { - public: - typedef typename PtrT::Type C; - - public: - //! \name Constructor - //@{ - //! Constructor - BoundWithSmartPtrMember(const PtrT& c, R(C::*member)(<%=generator.list(i)%>)) : - pThis(c), - pMember(member) - {} - //@} - - virtual R invoke(<%=generator.variableList(i)%>) const override - { - return ((pThis.pointer())->*pMember)(<%=generator.list(i, 'a')%>); - } - - virtual const void* object() const override - { - return reinterpret_cast(pThis.pointer()); - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return Static::DynamicCastWhenInherits::PerformConst(pThis.pointer()); - } - - virtual bool isDescendantOf(const IEventObserverBase* obj) const override - { - return Static::DynamicCastWhenInherits::Equals(obj, pThis.pointer()); - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return Static::DynamicCastWhenInherits::Yes; - } - - virtual bool compareWithPointerToFunction(R (*)(<%=generator.list(i)%>)) const override - { - return false; - } - - virtual bool compareWithPointerToObject(const void* object) const override - { - return (reinterpret_cast(object) == pThis.pointer()); - } - - - private: - //! Pointer to the object - mutable PtrT pThis; - //! Pointer-to-member - mutable R (C::*pMember)(<%=generator.list(i)%>); - - }; // class BoundWithSmartPtrMember)> - - -<% end %> - - - - - - - - // class BoundWithMemberAndUserData - -<% (1..generator.argumentCount).each do |i| %> - template> - class BoundWithSmartPtrMemberAndUserData)> final - :public IPointer)> - { - public: - typedef typename PtrT::Type C; - typedef typename Static::Remove::RefOnly>::Type UserDataTypeByCopy; - - public: - BoundWithSmartPtrMemberAndUserData(const PtrT& c, R(C::*member)(<%=generator.list(i)%>), U userdata) : - pThis(c), - pMember(member), - pUserdata(userdata) - {} - - virtual R invoke(<%=generator.variableList(i-1)%>) const override - { - return ((pThis.pointer())->*pMember)(<%=generator.list(i-1, 'a', "", ", ")%>const_cast(pUserdata)); - } - - virtual const void* object() const override - { - return reinterpret_cast(pThis.pointer()); - } - - virtual const IEventObserverBase* observerBaseObject() const override - { - return Static::DynamicCastWhenInherits::PerformConst(pThis.pointer()); - } - - virtual bool isDescendantOf(const IEventObserverBase* obj) const override - { - return Static::DynamicCastWhenInherits::Equals(obj, pThis.pointer()); - } - - virtual bool isDescendantOfIEventObserverBase() const override - { - return Static::DynamicCastWhenInherits::Yes; - } - - - virtual bool compareWithPointerToFunction(R (*)(<%=generator.list(i-1)%>)) const override - { - return false; - } - - virtual bool compareWithPointerToObject(const void* object) const override - { - return (reinterpret_cast(object) == pThis.pointer()); - } - - - private: - //! Pointer to the object - mutable PtrT pThis; - //! Pointer-to-member - mutable R (C::*pMember)(<%=generator.list(i)%>); - //! Userdata - UserDataTypeByCopy pUserdata; - - }; // class BoundWithSmartPtrMemberAndUserData)> - - -<% end %> - - - - - - - -} // namespace BindImpl -} // namespace Private -} // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/charset/charset.cpp b/src/ext/yuni/src/yuni/core/charset/charset.cpp index 2323581439..30c63e0bd2 100644 --- a/src/ext/yuni/src/yuni/core/charset/charset.cpp +++ b/src/ext/yuni/src/yuni/core/charset/charset.cpp @@ -61,7 +61,7 @@ void Converter::reset() { if (!valid()) return; - iconv((iconv_t)pContext, NULL, NULL, NULL, NULL); + iconv((iconv_t)pContext, nullptr, nullptr, nullptr, nullptr); } const char* Converter::Name(Charset::Type type) diff --git a/src/ext/yuni/src/yuni/core/dynamiclibrary/file.cpp b/src/ext/yuni/src/yuni/core/dynamiclibrary/file.cpp index 54f35580a4..0f673490b3 100644 --- a/src/ext/yuni/src/yuni/core/dynamiclibrary/file.cpp +++ b/src/ext/yuni/src/yuni/core/dynamiclibrary/file.cpp @@ -215,7 +215,7 @@ bool File::loadFromRawFilename(const AnyString& filename, File::Relocation r, Fi bool File::hasSymbol(const AnyString& name) const { return NullHandle != pHandle - and NULL != reinterpret_cast(YUNI_DYNLIB_DLSYM(pHandle, name.c_str())); + && reinterpret_cast(YUNI_DYNLIB_DLSYM(pHandle, name.c_str())); } Symbol File::resolve(const AnyString& name) const diff --git a/src/ext/yuni/src/yuni/core/event/observer/item.h.generator.hpp b/src/ext/yuni/src/yuni/core/event/observer/item.h.generator.hpp deleted file mode 100644 index 64c2db0b93..0000000000 --- a/src/ext/yuni/src/yuni/core/event/observer/item.h.generator.hpp +++ /dev/null @@ -1,190 +0,0 @@ - -#pragma once - - - -namespace Yuni -{ -namespace Event -{ - - - - /*! - ** \brief Item for a list of observer(Interface) - ** - ** \tparam R The type of the returned value - - */ - template, class Dummy = void> - class IObserverItemA - { - public: - virtual ~IObserverItemA() {} - virtual IObserver* observer() const = 0; - virtual bool equalsTo(const IObserver* o) const = 0; - virtual R fireEvent() const = 0; - - }; // class IObserverItemA - - - - - - - - - - - - /*! - ** \tparam C The real type of the observer - ** \tparam Mode The mode when firing the event - ** \tparam R The type of the returned value - - */ - template, class Dummy = void> - class ObserverItemA final : public IObserverItemA, Dummy> - { - public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - ** - ** \param o Pointer to the object - ** \param method Pointer to member - */ - ObserverItemA(C* o, R (C::*method)()); - //! Destructor - virtual ~ObserverItemA() {} - //@} - - /*! - ** \brief Fire the event - */ - virtual R fireEvent() const; - - //! Get a pointer to the observer object - virtual IObserver* observer() const; - //! Test if the class contains a given observer - virtual bool equalsTo(const IObserver* o) const; - - private: - //! The real observer - C* pObserver; - //! Pointer to method - R (C::*pMethod)(); - - }; // class ObserverItem - - - - - - -} // namespace Event -} // namespace Yuni - -# include "item.hxx" - -#endif // __YUNI_CORE_EVENT_OBSERVER_ITEM_H__ - diff --git a/src/ext/yuni/src/yuni/core/event/observer/item.hxx.generator.hpp b/src/ext/yuni/src/yuni/core/event/observer/item.hxx.generator.hpp deleted file mode 100644 index 1678a2b4ba..0000000000 --- a/src/ext/yuni/src/yuni/core/event/observer/item.hxx.generator.hpp +++ /dev/null @@ -1,143 +0,0 @@ - -#pragma once -#include "item.h" - - - -namespace Yuni -{ -namespace Event -{ - - - template, class Dummy> - inline - ObserverItemA, Dummy>::ObserverItemA(C* o, R (C::*method)()) : - pObserver(o), - pMethod(method) - { - /* Asserts */ - assert(o != NULL and "The given object can not be NULL"); - } - - template, class Dummy> - inline IObserver* - ObserverItemA, Dummy>::observer() const - { - return pObserver; - } - - template, class Dummy> - inline bool - ObserverItemA, Dummy>::equalsTo(const IObserver* o) const - { - return (pObserver == o); - } - - template, class Dummy> - inline R - ObserverItemA, Dummy>::fireEvent() const - { - (pObserver->*pMethod)(); - } - - - - - -} // namespace Event -} // namespace Yuni - -#endif // __YUNI_CORE_EVENT_OBSERVER_ITEM_HXX__ - diff --git a/src/ext/yuni/src/yuni/core/event/traits.h.generator.hpp b/src/ext/yuni/src/yuni/core/event/traits.h.generator.hpp deleted file mode 100644 index b7a80300ad..0000000000 --- a/src/ext/yuni/src/yuni/core/event/traits.h.generator.hpp +++ /dev/null @@ -1,274 +0,0 @@ -/* -** YUNI's default license is the GNU Lesser Public License (LGPL), with some -** exclusions (see below). This basically means that you can get the full source -** code for nothing, so long as you adhere to a few rules. -** -** Under the LGPL you may use YUNI for any purpose you wish, and modify it if you -** require, as long as you: -** -** Pass on the (modified) YUNI source code with your software, with original -** copyrights intact : -** * If you distribute electronically, the source can be a separate download -** (either from your own site if you modified YUNI, or to the official YUNI -** website if you used an unmodified version) – just include a link in your -** documentation -** * If you distribute physical media, the YUNI source that you used to build -** your application should be included on that media -** Make it clear where you have customised it. -** -** In addition to the LGPL license text, the following exceptions / clarifications -** to the LGPL conditions apply to YUNI: -** -** * Making modifications to YUNI configuration files, build scripts and -** configuration headers such as yuni/platform.h in order to create a -** customised build setup of YUNI with the otherwise unmodified source code, -** does not constitute a derived work -** * Building against YUNI headers which have inlined code does not constitute a -** derived work -** * Code which subclasses YUNI classes outside of the YUNI libraries does not -** form a derived work -** * Statically linking the YUNI libraries into a user application does not make -** the user application a derived work. -** * Using source code obsfucation on the YUNI source code when distributing it -** is not permitted. -** As per the terms of the LGPL, a "derived work" is one for which you have to -** distribute source code for, so when the clauses above define something as not -** a derived work, it means you don't have to distribute source code for it. -** However, the original YUNI source code with all modifications must always be -** made available. -*/ -#pragma once -<% -require File.dirname(__FILE__) + '/../../../tools/generators/commons.rb' -generator = Generator.new() -%> -<%=generator.thisHeaderHasBeenGenerated("traits.h.generator.hpp")%> - -#include "../slist/slist.h" -#include "../atomic/bool.h" - - - -namespace Yuni -{ -namespace Private -{ -namespace EventImpl -{ - - template class WithNArguments; - - - template - class EmptyPredicate final - { - public: - typedef void ResultType; - public: - inline void operator () (T) {} - static void result() {} - }; - - - template - class PredicateRemoveObject final - { - public: - PredicateRemoveObject(const void* object) : - pObject(object) - {} - - bool operator == (const BindT& rhs) const - { - return (pObject == reinterpret_cast(rhs.object())); - } - private: - const void* pObject; - }; - - - template - class PredicateRemoveObserverBase final - { - public: - PredicateRemoveObserverBase(IEvent* event, const IEventObserverBase* object) : - pEvent(event), pObject(object) - {} - - bool operator == (const BindT& rhs) const - { - if (pObject == rhs.observerBaseObject()) - { - pObject->boundEventDecrementReference(pEvent); - return true; - } - return false; - } - private: - IEvent* pEvent; - const IEventObserverBase* pObject; - }; - - - template - class PredicateRemoveWithoutChecks final - { - public: - PredicateRemoveWithoutChecks(const IEventObserverBase* object) : - pObject(object) - {} - - inline bool operator == (const BindT& rhs) const - { - return (rhs.isDescendantOf(pObject)); - } - private: - const IEventObserverBase* pObject; - }; - - - - struct FoldTypeVoid {}; - template struct FoldType { typedef T value_type; }; - template<> struct FoldType { typedef FoldTypeVoid value_type; }; - - - - -<% (0..generator.argumentCount).each do |i| %> - template - class WithNArguments<<%=i%>, BindT> : public Policy::ObjectLevelLockable,BindT> > - { - public: - //! The Threading Policy - typedef Policy::ObjectLevelLockable,BindT> > ThreadingPolicy; - //! Bind - typedef BindT BindType; - //! The Return type - typedef typename BindType::ReturnType R;<% (0..i-1).each do |j| %> - //! Type of the argument <%=j%> - typedef typename BindType::template Argument<<%=j%>>::Type A<%=j%>;<% end %> - - - public: - //! \name Constructors - //@{ - //! Default constructor - WithNArguments() : - pEmpty(true) - {} - //! Copy constructor - WithNArguments(const WithNArguments& rhs) - { - typename ThreadingPolicy::MutexLocker locker(*this); - pEmpty = rhs.pEmpty; - pBindList = rhs.pBindList; - } - //@} - - //! \name Invoke - //@{ - /*! - ** \brief Invoke the delegate - */ - void invoke(<%=generator.variableList(i)%>) const - { - if (not pEmpty) - { - typename ThreadingPolicy::MutexLocker locker(*this); - const typename BindList::const_iterator end = pBindList.end(); - for (typename BindList::const_iterator i = pBindList.begin(); i != end; ++i) - (*i).invoke(<%=generator.list(i,'a')%>); - } - } - - template - R fold(typename FoldType::value_type initval, const CallbackT& accumulator<%=generator.variableList(i, "A", "a", ", ")%>) const - { - if (not pEmpty) - { - typename FoldType::value_type value = initval; - typename ThreadingPolicy::MutexLocker locker(*this); - const typename BindList::const_iterator end = pBindList.end(); - for (typename BindList::const_iterator i = pBindList.begin(); i != end; ++i) - accumulator(value, (*i).invoke(<%=generator.list(i,'a')%>)); - return value; - } - return initval; - } - - - template class PredicateT> - typename PredicateT::ResultType invoke(<%=generator.variableList(i)%>) const - { - PredicateT predicate; - if (not pEmpty) - { - typename ThreadingPolicy::MutexLocker locker(*this); - const typename BindList::const_iterator end = pBindList.end(); - for (typename BindList::const_iterator i = pBindList.begin(); i != end; ++i) - predicate((*i).invoke(<%=generator.list(i,'a')%>)); - } - return predicate.result(); - } - - - template class PredicateT> - typename PredicateT::ResultType invoke(PredicateT& predicate<%=generator.variableList(i, "A", "a", ", ")%>) const - { - if (not pEmpty) - { - typename ThreadingPolicy::MutexLocker locker(*this); - const typename BindList::const_iterator end = pBindList.end(); - for (typename BindList::const_iterator i = pBindList.begin(); i != end; ++i) - predicate((*i).invoke(<%=generator.list(i,'a')%>)); - } - return predicate.result(); - } - - template void assign(EventT& rhs) - { - typename ThreadingPolicy::MutexLocker locker(*this); - typename ThreadingPolicy::MutexLocker lockerRHS(rhs); - pBindList = rhs.pBindList; - pEmpty = pBindList.empty(); - } - - /*! - ** \brief Invoke the delegate - */ - void operator () (<%=generator.variableList(i)%>) const - { - if (not pEmpty) - { - typename ThreadingPolicy::MutexLocker locker(*this); - const typename BindList::const_iterator end = pBindList.end(); - for (typename BindList::const_iterator i = pBindList.begin(); i != end; ++i) - (*i).invoke(<%=generator.list(i,'a')%>); - } - } - //@} - - - protected: - //! Binding list (type) - typedef LinkedList BindList; - //! A flag to know if the event is empty or not - // This value must only set when the mutex is locked - volatile bool pEmpty; - //! Binding list - BindList pBindList; - // friend ! - template friend class Event; - - }; // class WithNArguments - - -<% end %> - - - - -} // namespace EventImpl -} // namespace Private -} // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/getopt/parser.cpp b/src/ext/yuni/src/yuni/core/getopt/parser.cpp index c34443c470..c3e31f7d72 100644 --- a/src/ext/yuni/src/yuni/core/getopt/parser.cpp +++ b/src/ext/yuni/src/yuni/core/getopt/parser.cpp @@ -118,7 +118,7 @@ inline Context::Context(Parser& parser) : pParser(parser), pTokenIndex(1), pPara bool Context::findNextParameter(IOption* option, int argc, char* argv[]) { - assert(option != NULL); + assert(option); if (not option->requireAdditionalParameter()) { @@ -343,7 +343,7 @@ GetOpt::ReturnCode Parser::operator()(int argc, char* argv[]) void Parser::helpUsage(const char* argv0) { - assert(argv0 != NULL); // just in case + assert(argv0); // just in case// OK std::cout.write("Usage: ", 7); std::cout << ExtractFilenameOnly(argv0); diff --git a/src/ext/yuni/src/yuni/core/logs/handler/callback.h b/src/ext/yuni/src/yuni/core/logs/handler/callback.h index 30ae6e6448..d794f61b2b 100644 --- a/src/ext/yuni/src/yuni/core/logs/handler/callback.h +++ b/src/ext/yuni/src/yuni/core/logs/handler/callback.h @@ -49,7 +49,7 @@ class YUNI_DECL Callback : public NextHandler } public: - mutable Yuni::Event callback; + mutable Yuni::Event callback; mutable String pDispatchedMessage; }; // class Callback diff --git a/src/ext/yuni/src/yuni/core/logs/handler/file.hxx b/src/ext/yuni/src/yuni/core/logs/handler/file.hxx index fd8618aefa..2fdd50032d 100644 --- a/src/ext/yuni/src/yuni/core/logs/handler/file.hxx +++ b/src/ext/yuni/src/yuni/core/logs/handler/file.hxx @@ -61,7 +61,7 @@ void File::internalDecoratorWriteWL(LoggerT& logger, const AnyStrin { if (pFile.opened()) { - typedef typename LoggerT::DecoratorsType DecoratorsType; + using DecoratorsType = typename LoggerT::DecoratorsType; // Append the message to the file logger.DecoratorsType::template internalDecoratorAddPrefix(pFile, s); diff --git a/src/ext/yuni/src/yuni/core/logs/handler/stdcout.h b/src/ext/yuni/src/yuni/core/logs/handler/stdcout.h index 19c27b05c7..1d3151564d 100644 --- a/src/ext/yuni/src/yuni/core/logs/handler/stdcout.h +++ b/src/ext/yuni/src/yuni/core/logs/handler/stdcout.h @@ -34,12 +34,10 @@ class YUNI_DECL StdCout : public NextHandler colorsAllowed = YUNI_LOGS_COLORS_ALLOWED, }; -public: template void internalDecoratorWriteWL(LoggerT& logger, const AnyString& s) const { - typedef typename LoggerT::DecoratorsType DecoratorsType; - + using DecoratorsType = typename LoggerT::DecoratorsType; // Write the message to the std::cout/cerr if (VerbosityType::shouldUsesStdCerr) { diff --git a/src/ext/yuni/src/yuni/core/math/random/distribution.h b/src/ext/yuni/src/yuni/core/math/random/distribution.h index 2fa126bd47..625cee347c 100644 --- a/src/ext/yuni/src/yuni/core/math/random/distribution.h +++ b/src/ext/yuni/src/yuni/core/math/random/distribution.h @@ -10,6 +10,8 @@ */ #pragma once +#include "yuni/core/preprocessor/capabilities.h" + namespace Yuni { namespace Math diff --git a/src/ext/yuni/src/yuni/core/noncopyable.h b/src/ext/yuni/src/yuni/core/noncopyable.h index b9a211ae2a..53a270d4cc 100644 --- a/src/ext/yuni/src/yuni/core/noncopyable.h +++ b/src/ext/yuni/src/yuni/core/noncopyable.h @@ -10,6 +10,8 @@ */ #pragma once +#include "yuni/core/preprocessor/capabilities.h" + namespace Yuni { /*! diff --git a/src/ext/yuni/src/yuni/core/nullable/extension.hxx b/src/ext/yuni/src/yuni/core/nullable/extension.hxx index 25c282a70c..3f17c4a231 100644 --- a/src/ext/yuni/src/yuni/core/nullable/extension.hxx +++ b/src/ext/yuni/src/yuni/core/nullable/extension.hxx @@ -17,7 +17,7 @@ namespace Extension namespace CString { template -struct Append> final +class Append> final { static void Perform(CStringT& s, const Yuni::Nullable& rhs) { diff --git a/src/ext/yuni/src/yuni/core/nullable/nullable.hxx b/src/ext/yuni/src/yuni/core/nullable/nullable.hxx index 9092035604..ba6c4b5c03 100644 --- a/src/ext/yuni/src/yuni/core/nullable/nullable.hxx +++ b/src/ext/yuni/src/yuni/core/nullable/nullable.hxx @@ -290,14 +290,14 @@ inline void Nullable::print(S& out, const U& nullValue) const } template -inline typename Nullable::reference Nullable::operator[](size_type n) +inline typename Nullable::reference Nullable::operator[](size_type) { return pHolder.reference(); } template inline typename Nullable::const_reference Nullable::operator[]( - size_type n) const + size_type) const { return pHolder.reference(); } @@ -327,7 +327,7 @@ inline typename Nullable::const_reference Nullable::back() c } template -inline bool Nullable::operator<(const Nullable& rhs) const +inline bool Nullable::operator<(const Nullable&) const { return false; } diff --git a/src/ext/yuni/src/yuni/core/preprocessor/capabilities.h b/src/ext/yuni/src/yuni/core/preprocessor/capabilities.h index a6c545923d..e3f53a1f5d 100644 --- a/src/ext/yuni/src/yuni/core/preprocessor/capabilities.h +++ b/src/ext/yuni/src/yuni/core/preprocessor/capabilities.h @@ -103,6 +103,8 @@ #include +#include "yuni/platform.h" + #define YUNI_OS_FLAG_WINDOWS 0 #define YUNI_OS_FLAG_UNIX 0 #define YUNI_OS_FLAG_LINUX 0 diff --git a/src/ext/yuni/src/yuni/core/preprocessor/vaargs.h.generator.hpp b/src/ext/yuni/src/yuni/core/preprocessor/vaargs.h.generator.hpp deleted file mode 100644 index 54ea5288e3..0000000000 --- a/src/ext/yuni/src/yuni/core/preprocessor/vaargs.h.generator.hpp +++ /dev/null @@ -1,208 +0,0 @@ -/* -** YUNI's default license is the GNU Lesser Public License (LGPL), with some -** exclusions (see below). This basically means that you can get the full source -** code for nothing, so long as you adhere to a few rules. -** -** Under the LGPL you may use YUNI for any purpose you wish, and modify it if you -** require, as long as you: -** -** Pass on the (modified) YUNI source code with your software, with original -** copyrights intact : -** * If you distribute electronically, the source can be a separate download -** (either from your own site if you modified YUNI, or to the official YUNI -** website if you used an unmodified version) – just include a link in your -** documentation -** * If you distribute physical media, the YUNI source that you used to build -** your application should be included on that media -** Make it clear where you have customised it. -** -** In addition to the LGPL license text, the following exceptions / clarifications -** to the LGPL conditions apply to YUNI: -** -** * Making modifications to YUNI configuration files, build scripts and -** configuration headers such as yuni/platform.h in order to create a -** customised build setup of YUNI with the otherwise unmodified source code, -** does not constitute a derived work -** * Building against YUNI headers which have inlined code does not constitute a -** derived work -** * Code which subclasses YUNI classes outside of the YUNI libraries does not -** form a derived work -** * Statically linking the YUNI libraries into a user application does not make -** the user application a derived work. -** * Using source code obsfucation on the YUNI source code when distributing it -** is not permitted. -** As per the terms of the LGPL, a "derived work" is one for which you have to -** distribute source code for, so when the clauses above define something as not -** a derived work, it means you don't have to distribute source code for it. -** However, the original YUNI source code with all modifications must always be -** made available. -*/ -#pragma once - - -<% -require File.dirname(__FILE__) + '/../../../tools/generators/commons.rb' -generator = Generator.new() - -maxArgs = 512 -%> -<%=generator.thisHeaderHasBeenGenerated("vaargs.h.generator.hpp")%> - -/*! -** \internal This header must remain compatible with C code. -*/ - - -/*! -** \brief Get the number of arguments -** -** \warning YUNI_VAARGS_COUNT() without arguments would violate 6.10.3p4 of ISO C99 -** \note This code was initially created by 'Laurent Deniau' -** \see http://groups.google.com/group/comp.std.c/browse_thread/thread/77ee8c8f92e4a3fb/346fc464319b1ee5 -*/ -#define YUNI_VAARGS_COUNT(...) \ - YUNI_PRIVATE_VAARGS_N_ARG_(__VA_ARGS__, YUNI_PRIVATE_VAARGS_RSEQ_N()) - - -/*! -** \brief Get the value of the Nth argument (zero-based) -** -** \param Index The index of the argument (zero-based) -*/ -#define YUNI_VAARGS_VALUE(Index, ...) \ - YUNI_PRIVATE_VAARGS_N_ARG_VALUE(Index, __VA_ARGS__, YUNI_PRIVATE_VAARGS_RSEQ_N()) - - -/*! -** \brief Call an arbitrary macro for each argument given in a varadiac parameter -** -** The macro must have the following signature : -** \code -** # define MY_MACRO(Index, Value) DoSomething... -** \endcode -** The index is zero-based. -** -** \param Macro The macro to call for each argument -*/ -#define YUNI_VAARGS_FOREACH(Macro, ...) \ - YUNI_PRIVATE_VAARGS_CALL_MACRO(Macro, YUNI_EMPTY, \ - YUNI_VAARGS_COUNT(__VA_ARGS__), __VA_ARGS__) - -/*! -** \brief Call an arbitrary macro for each argument given in a variadic parameter -** -** The macro must have the following signature : -** \code -** # define MY_MACRO(Index, Value) DoSomething... -** \endcode -** The index is zero-based. -** -** \param Macro The macro to call for each argument -** \param MacroSeparator The separator to add between each call to the previously given macro -*/ -#define YUNI_VAARGS_FOREACH_WITH_SEPARATOR(Macro, MacroSeparator, ...) \ - YUNI_PRIVATE_VAARGS_CALL_MACRO( \ - Macro, MacroSeparator, YUNI_VAARGS_COUNT(__VA_ARGS__), __VA_ARGS__) - - - - - - - - -/* Private macros, that _should not_ be used directly */ - -/*! -** \brief String concatenation -** -** This define is a replacement for YUNI_JOIN, in order to be able to use this -** header alone. -*/ -#define YUNI_PRIVATE_VAARGS_JOIN(X,Y) X ## Y - - -/*! -** \brief An empty value -*/ -#define YUNI_PRIVATE_VAARGS_EMPTY() - -/* Related to YUNI_VAARGS_COUNT */ - -#define YUNI_PRIVATE_VAARGS_N_ARG_(...) \ - YUNI_PRIVATE_VAARGS_ARG_N_INTERMEDIATE(__VA_ARGS__) - -#define YUNI_PRIVATE_VAARGS_ARG_N_INTERMEDIATE( \ - <% - (0..maxArgs).each do |i| - %>_<%=i%>,<% - end -%> \ - N,...) N - - -/* Related to both YUNI_VAARGS_VALUE and YUNI_VAARGS_COUNT */ - -#define YUNI_PRIVATE_VAARGS_RSEQ_N() \ - <% - (1..(maxArgs+1)).reverse_each do |i| - %><%=i%>,<% - end -%>0 - - - -/* Related to YUNI_VAARGS_VALUE */ - -#define YUNI_PRIVATE_VAARGS_N_ARG_VALUE(Index, ...) \ - YUNI_PRIVATE_VAARGS_ARG_N_INTERMEDIATE_VALUE(Index, __VA_ARGS__) - - -#define YUNI_PRIVATE_VAARGS_ARG_N_INTERMEDIATE_VALUE(I , \ - <% - (0..maxArgs).each do |i| %>_<%=i%>,<% end %> \ - N,...) \ - YUNI_PRIVATE_VAARGS_CALL_INDEX(YUNI_PRIVATE_VAARGS_JOIN(YUNI_PRIV_VAINX_ , I), \ - <% - (0..maxArgs-1).each do |i| %>_<%=i%>,<% end %>_<%=maxArgs%>) - - - -#define YUNI_PRIVATE_VAARGS_CALL_INDEX( C, \ - <% - (0..maxArgs-1).each do |i| %>_<%=i%>,<% end %>_<%=maxArgs%>) \ - C( \ - <% - (0..maxArgs-1).each do |i| %>_<%=i%>,<% end %>_<%=maxArgs%>) - - - -<% - (0..maxArgs - 1).each do |i| %># define YUNI_PRIV_VAINX_<%=i%>( \ - <% - (1..(i+1)).each do |j| %>_<%=j%>,<% end %>...) \ - _<%=(i+1)%> -<% end %> - - - -/* Related to YUNI_VAARGS_FOREACH */ - -#define YUNI_PRIVATE_VAARGS_CALL_MACRO(Macro, MacroSeparator, Total, ...) \ - YUNI_EMPTY, YUNI_PRIVATE_VAARGS_CALL_MC_INTERMEDIATE(Macro, MacroSeparator, \ - YUNI_PRIVATE_VAARGS_JOIN(YUNI_PRIVATE_VAARGS_CALL_MC_ , Total), __VA_ARGS__,piko ) - -#define YUNI_PRIVATE_VAARGS_CALL_MC_INTERMEDIATE(Macro, MacroSeparator, C, ...) \ - C(Macro, MacroSeparator, __VA_ARGS__) - - -#define YUNI_PRIVATE_VAARGS_CALL_MC_0(Macro, MacroSeparator, ...) - -<% - (1..maxArgs).each do |i| %># define YUNI_PRIVATE_VAARGS_CALL_MC_<%=i%>(Macro, MacroSeparator, \ - <% - (1..(i)).each do |j| %>_<%=j%>,<% end %>...) \ - YUNI_PRIVATE_VAARGS_CALL_MC_<%=(i-1)%>(Macro, MacroSeparator, <% (1..(i-1)).each do |k| %>_<%=k%>,<% end %> Dummy) \ - <% if i > 1 %> MacroSeparator <% end %> Macro(<%=(i-1)%>, _<%=(i)%>) -<% end %> - diff --git a/src/ext/yuni/src/yuni/core/process/rename.cpp b/src/ext/yuni/src/yuni/core/process/rename.cpp deleted file mode 100644 index 3568479182..0000000000 --- a/src/ext/yuni/src/yuni/core/process/rename.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* -** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org). -** -** This Source Code Form is subject to the terms of the Mozilla Public License -** v.2.0. If a copy of the MPL was not distributed with this file, You can -** obtain one at http://mozilla.org/MPL/2.0/. -** -** github: https://github.com/libyuni/libyuni/ -** gitlab: https://gitlab.com/libyuni/libyuni/ (mirror) -*/ -#include "rename.h" -#include "../../thread/mutex.h" - -#ifdef YUNI_OS_LINUX -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace Yuni -{ -namespace Process -{ -#ifdef YUNI_OS_LINUX - -namespace // anonymous -{ -static char** Argv = NULL; // pointer to argument vector -static char* LastArgv = NULL; // end of argv -// static char Argv0[128]; // program name - -static inline void LinuxInitializeRenameProcess(int argc, char** argv, char** envp) -{ - uint i = 0; - for (; envp[i] != NULL; ++i) - continue; - __environ = (char**)malloc(sizeof(char*) * (i + 1)); - - for (i = 0; envp[i] != NULL; ++i) - __environ[i] = strdup(envp[i]); - __environ[i] = nullptr; - - Argv = argv; - LastArgv - = (i > 0) ? envp[i - 1] + strlen(envp[i - 1]) : argv[argc - 1] + strlen(argv[argc - 1]); - - char* tmp = strrchr(argv[0], '/'); - if (!tmp) - tmp = argv[0]; - else - ++tmp; - - // strncpy(Argv0, tmp, sizeof(Argv0)); - // Argv0[sizeof(Argv0) - 1] = 0; -} - -static inline void LinuxRenameProcess(const char* text, uint size) -{ - // TODO Remove this static variable into a dynamicaly allocated one - enum - { - initialBufferSize = 2048, - }; - static char buffer[initialBufferSize]; - - memset(buffer, '\0', sizeof(buffer)); - char* p = buffer; - - uint buffersize = (uint)(sizeof(buffer) - (size_t)(p - buffer) - 1); - if (size > buffersize) - size = buffersize; - YUNI_MEMCPY(p, initialBufferSize, text, size); - p[size] = '\0'; - - for (uint i = 0; Argv[i]; ++i) - memset(Argv[i], '\0', strlen(Argv[i])); - - (void)strcpy(Argv[0], buffer); - Argv[1] = nullptr; -} - -} // anonymous namespace - -char** Rename(int argc, char** argv, const AnyString& newprocessname) -{ - // Global locking for multithreading - static Yuni::Mutex globalMutex; - Yuni::MutexLocker locker(globalMutex); - - static bool initialized = false; - if (not initialized) - { - LinuxInitializeRenameProcess(argc, argv, environ); - initialized = true; - } - LinuxRenameProcess(newprocessname.c_str(), newprocessname.size()); - return argv; -} - -#else - -char** Rename(int /*argc*/, char** argv, const AnyString& /*newprocessname*/) -{ - // does nothing - return argv; -} - -#endif - -} // namespace Process -} // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/process/rename.h b/src/ext/yuni/src/yuni/core/process/rename.h deleted file mode 100644 index fef2683cc9..0000000000 --- a/src/ext/yuni/src/yuni/core/process/rename.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org). -** -** This Source Code Form is subject to the terms of the Mozilla Public License -** v.2.0. If a copy of the MPL was not distributed with this file, You can -** obtain one at http://mozilla.org/MPL/2.0/. -** -** github: https://github.com/libyuni/libyuni/ -** gitlab: https://gitlab.com/libyuni/libyuni/ (mirror) -*/ -#pragma once -#include "../../yuni.h" -#include "../string.h" - -namespace Yuni -{ -namespace Process -{ -/*! -** \brief Try to rename the process name -** -** This routine does nothing on Windows -** This routine is an implementation of setproctitle -*/ -YUNI_DECL char** Rename(int argc, char** argv, const AnyString& newprocessname); - -} // namespace Process -} // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/string/operators.hxx b/src/ext/yuni/src/yuni/core/string/operators.hxx index e7e26e52da..2ef7c24fca 100644 --- a/src/ext/yuni/src/yuni/core/string/operators.hxx +++ b/src/ext/yuni/src/yuni/core/string/operators.hxx @@ -112,39 +112,39 @@ inline Yuni::CString operator+(const Yuni::CString& rh template inline bool operator==(const char* lhs, const Yuni::CString& rhs) { - return rhs == lhs; + return rhs.equals(lhs); } template inline bool operator!=(const char* lhs, const Yuni::CString& rhs) { - return rhs != lhs; + return !rhs.equals(lhs); } template inline bool operator==(const char lhs[N], const Yuni::CString& rhs) { - return rhs == lhs; + return rhs.equals(lhs); } template inline bool operator!=(const char lhs[N], const Yuni::CString& rhs) { - return rhs != lhs; + return !rhs.equals(lhs); } template inline bool operator==(const std::basic_string& lhs, const Yuni::CString& rhs) { - return rhs == lhs; + return rhs.equals(lhs); } template inline bool operator!=(const std::basic_string& lhs, const Yuni::CString& rhs) { - return rhs != lhs; + return !rhs.equals(lhs); } inline bool operator==(const AnyString& mbs, Yuni::UTF8::Char c) diff --git a/src/ext/yuni/src/yuni/core/string/traits/append.h b/src/ext/yuni/src/yuni/core/string/traits/append.h index 0a40e93d7a..75d022d283 100644 --- a/src/ext/yuni/src/yuni/core/string/traits/append.h +++ b/src/ext/yuni/src/yuni/core/string/traits/append.h @@ -13,6 +13,7 @@ #include "integer.h" #include #include +#include #ifdef YUNI_OS_MSVC #define YUNI_PRIVATE_MEMBUF_SPTRINF(BUFFER, SIZE, F, V) ::sprintf_s(BUFFER, SIZE, F, V) @@ -294,6 +295,16 @@ class Append> final } }; +// std::filesystem::path<> +template +class Append final +{ +public: + static void Perform(CStringT& s, const std::filesystem::path& rhs) + { + s << rhs.string(); + } +}; } // namespace CString } // namespace Extension } // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/system/environment.cpp b/src/ext/yuni/src/yuni/core/system/environment.cpp index 8f278e971e..cb5a5c9800 100644 --- a/src/ext/yuni/src/yuni/core/system/environment.cpp +++ b/src/ext/yuni/src/yuni/core/system/environment.cpp @@ -45,7 +45,7 @@ inline bool ReadImpl(const AnyString& name, StringT& out, bool emptyBefore) if (size != 0) { int sizeRequired - = WideCharToMultiByte(CP_UTF8, 0, buffer, (int)size - 1, NULL, 0, NULL, NULL); + = WideCharToMultiByte(CP_UTF8, 0, buffer, (int)size - 1, nullptr, 0, nullptr, nullptr); if (sizeRequired > 0) { out.reserve(out.size() + sizeRequired); @@ -55,8 +55,8 @@ inline bool ReadImpl(const AnyString& name, StringT& out, bool emptyBefore) (int)size - 1, out.data() + out.size(), size, - NULL, - NULL); + nullptr, + nullptr); ::free(buffer); out.resize(out.size() + (uint)sizeRequired); return true; diff --git a/src/ext/yuni/src/yuni/core/system/gettimeofday.cpp b/src/ext/yuni/src/yuni/core/system/gettimeofday.cpp index a8d3ec2aee..18ff782ed8 100644 --- a/src/ext/yuni/src/yuni/core/system/gettimeofday.cpp +++ b/src/ext/yuni/src/yuni/core/system/gettimeofday.cpp @@ -19,7 +19,7 @@ namespace Yuni { int gettimeofday(struct timeval* tv, struct timezone* tz) { - if (NULL != tv) + if (tv) { struct _timeb timebuffer; _ftime64_s(&timebuffer); @@ -27,7 +27,7 @@ int gettimeofday(struct timeval* tv, struct timezone* tz) tv->tv_usec = (int64_t)(timebuffer.millitm * 1000); } - if (NULL != tz) + if (tz) { static int tzflag = 0; if (!tzflag) diff --git a/src/ext/yuni/src/yuni/core/system/memory.cpp b/src/ext/yuni/src/yuni/core/system/memory.cpp index a872a46b02..4e1bfbce29 100644 --- a/src/ext/yuni/src/yuni/core/system/memory.cpp +++ b/src/ext/yuni/src/yuni/core/system/memory.cpp @@ -268,7 +268,7 @@ uint64_t Total() int mib[2] = {CTL_HW, HW_MEMSIZE}; uint64_t memory; size_t len = sizeof(uint64_t); - return (!sysctl(mib, 2, &memory, &len, NULL, 0)) ? memory : (uint64_t)defaultTotal; + return (!sysctl(mib, 2, &memory, &len, nullptr, 0)) ? memory : (uint64_t)defaultTotal; } uint64_t Available() @@ -298,7 +298,7 @@ bool Usage::update() int mib[2] = {CTL_HW, HW_MEMSIZE}; size_t len = sizeof(uint64_t); size_t sttotal; - if (sysctl(mib, 2, &sttotal, &len, NULL, 0)) + if (sysctl(mib, 2, &sttotal, &len, nullptr, 0)) { total = (uint64_t)defaultTotal; return false; diff --git a/src/ext/yuni/src/yuni/core/system/username.cpp b/src/ext/yuni/src/yuni/core/system/username.cpp index 9e5b57cf7c..1348b2e02c 100644 --- a/src/ext/yuni/src/yuni/core/system/username.cpp +++ b/src/ext/yuni/src/yuni/core/system/username.cpp @@ -37,12 +37,12 @@ uint WindowsUsername(char* cstring, uint size) // The variable `unwsize` contains the final zero --unwsize; // Getting the size of the buffer into UTF8 - int sizeRequired = WideCharToMultiByte(CP_UTF8, 0, unw, unwsize, NULL, 0, NULL, NULL); + int sizeRequired = WideCharToMultiByte(CP_UTF8, 0, unw, unwsize, nullptr, 0, nullptr, nullptr); if (sizeRequired > 0) { if (static_cast(sizeRequired) > size) sizeRequired = size; - WideCharToMultiByte(CP_UTF8, 0, unw, unwsize, cstring, sizeRequired, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, unw, unwsize, cstring, sizeRequired, nullptr, nullptr); return static_cast(sizeRequired); } } diff --git a/src/ext/yuni/src/yuni/core/tree/n/treeN.hxx b/src/ext/yuni/src/yuni/core/tree/n/treeN.hxx index a9475bf9e3..7b092bfe3a 100644 --- a/src/ext/yuni/src/yuni/core/tree/n/treeN.hxx +++ b/src/ext/yuni/src/yuni/core/tree/n/treeN.hxx @@ -456,7 +456,12 @@ template class TP, template class ChckP, class C inline void TreeN::addRef() const { typename ThreadingPolicy::MutexLocker locker(*this); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // g++-10 has no -Wvolatile, g++-13 does +#pragma GCC diagnostic ignored "-Wvolatile" ++pRefCount; +#pragma GCC diagnostic pop +#pragma GCC diagnostic pop } template class TP, template class ChckP, class ConvP> @@ -464,9 +469,13 @@ bool TreeN::release() const { typename ThreadingPolicy::MutexLocker locker(*this); assert(pRefCount > 0 and "TreeN: invalid reference count"); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // g++-10 has no -Wvolatile, g++-13 does +#pragma GCC diagnostic ignored "-Wvolatile" if (--pRefCount != 0) return false; - +#pragma GCC diagnostic pop +#pragma GCC diagnostic pop // Early clean-up // The method 'release' must be const for good code design. But // we have to be properly detached from the parent node. @@ -478,6 +487,7 @@ bool TreeN::release() const return true; } + template class TP, template class ChckP, class ConvP> inline bool TreeN::hasIntrusiveSmartPtr() const { diff --git a/src/ext/yuni/src/yuni/datetime/timestamp.cpp b/src/ext/yuni/src/yuni/datetime/timestamp.cpp index 90c1b26496..06c2fa68e9 100644 --- a/src/ext/yuni/src/yuni/datetime/timestamp.cpp +++ b/src/ext/yuni/src/yuni/datetime/timestamp.cpp @@ -97,9 +97,9 @@ char* FormatTimestampToString(const AnyString& format, int64_t timestamp) if (timestamp <= 0) { #ifdef YUNI_OS_MSVC - timestamp = (int64_t)::_time64(NULL); + timestamp = (int64_t)::_time64(nullptr); #else - timestamp = (int64_t)::time(NULL); + timestamp = (int64_t)::time(nullptr); #endif } diff --git a/src/ext/yuni/src/yuni/io/directory/info/platform.cpp b/src/ext/yuni/src/yuni/io/directory/info/platform.cpp index 7a330da911..516a344f41 100644 --- a/src/ext/yuni/src/yuni/io/directory/info/platform.cpp +++ b/src/ext/yuni/src/yuni/io/directory/info/platform.cpp @@ -189,12 +189,12 @@ class DirInfo final : private Yuni::NonCopyable } const int sizeRequired - = WideCharToMultiByte(CP_UTF8, 0, data.name, -1, NULL, 0, NULL, NULL); + = WideCharToMultiByte(CP_UTF8, 0, data.name, -1, nullptr, 0, nullptr, nullptr); if (sizeRequired <= 0) continue; name.reserve((uint)sizeRequired); WideCharToMultiByte( - CP_UTF8, 0, data.name, -1, (char*)name.data(), sizeRequired, NULL, NULL); + CP_UTF8, 0, data.name, -1, (char*)name.data(), sizeRequired, nullptr, nullptr); name.resize(((uint)sizeRequired) - 1); filename.clear(); @@ -341,12 +341,12 @@ IteratorData* IteratorDataCreate(const AnyString& folder, uint flags) data->push(folder); return data; } - return NULL; + return nullptr; } IteratorData* IteratorDataCopy(const IteratorData* data) { - return (data) ? (new IteratorData(*data)) : NULL; + return (data) ? (new IteratorData(*data)) : nullptr; } void IteratorDataFree(const IteratorData* data) @@ -356,52 +356,52 @@ void IteratorDataFree(const IteratorData* data) IteratorData* IteratorDataNext(IteratorData* data) { - assert(data != NULL); + assert(data); if (data->next()) return data; delete data; - return NULL; + return nullptr; } const String& IteratorDataFilename(const IteratorData* data) { - assert(data != NULL); + assert(data); return data->dirinfo.front().filename; } const String& IteratorDataParentName(const IteratorData* data) { - assert(data != NULL); + assert(data); return data->dirinfo.front().parent; } const String& IteratorDataName(const IteratorData* data) { - assert(data != NULL); + assert(data); return data->dirinfo.front().name; } uint64_t IteratorDataSize(const IteratorData* data) { - assert(data != NULL); + assert(data); return data->dirinfo.front().size; } int64_t IteratorDataModified(const IteratorData* data) { - assert(data != NULL); + assert(data); return data->dirinfo.front().modified; } bool IteratorDataIsFolder(const IteratorData* data) { - assert(data != NULL); + assert(data); return data->dirinfo.front().isFolder; } bool IteratorDataIsFile(const IteratorData* data) { - assert(data != NULL); + assert(data); return !data->dirinfo.front().isFolder; } diff --git a/src/ext/yuni/src/yuni/io/directory/iterator/iterator.cpp b/src/ext/yuni/src/yuni/io/directory/iterator/iterator.cpp index 2bcbd5743c..c4ddc8f573 100644 --- a/src/ext/yuni/src/yuni/io/directory/iterator/iterator.cpp +++ b/src/ext/yuni/src/yuni/io/directory/iterator/iterator.cpp @@ -148,7 +148,7 @@ Flow TraverseWindowsFolder(const String& filename, bool files) { // Convertir the filename - assert(opts.wbuffer != NULL); + assert(opts.wbuffer); opts.wbuffer[0] = L'\\'; opts.wbuffer[1] = L'\\'; opts.wbuffer[2] = L'?'; @@ -199,12 +199,12 @@ Flow TraverseWindowsFolder(const String& filename, } const int sizeRequired - = WideCharToMultiByte(CP_UTF8, 0, data.cFileName, -1, NULL, 0, NULL, NULL); + = WideCharToMultiByte(CP_UTF8, 0, data.cFileName, -1, nullptr, 0, nullptr, nullptr); if (sizeRequired <= 0) continue; newName.reserve((uint)sizeRequired); WideCharToMultiByte( - CP_UTF8, 0, data.cFileName, -1, (char*)newName.data(), sizeRequired, NULL, NULL); + CP_UTF8, 0, data.cFileName, -1, (char*)newName.data(), sizeRequired, nullptr, nullptr); newName.resize(((uint)sizeRequired) - 1); newFilename.clear(); diff --git a/src/ext/yuni/src/yuni/io/directory/remove.cpp b/src/ext/yuni/src/yuni/io/directory/remove.cpp index e35f9664f9..e5a936599a 100644 --- a/src/ext/yuni/src/yuni/io/directory/remove.cpp +++ b/src/ext/yuni/src/yuni/io/directory/remove.cpp @@ -73,7 +73,7 @@ static bool RmDirRecursiveInternal(const AnyString& path) buffer.clear() << path << SEP << (const char*)ep->d_name; ::unlink(buffer.c_str()); } - } while (NULL != (ep = ::readdir(dp))); + } while (nullptr != (ep = ::readdir(dp))); } (void)::closedir(dp); } diff --git a/src/ext/yuni/src/yuni/io/file/file.cpp b/src/ext/yuni/src/yuni/io/file/file.cpp index efe0dc80f8..9613b25b1d 100644 --- a/src/ext/yuni/src/yuni/io/file/file.cpp +++ b/src/ext/yuni/src/yuni/io/file/file.cpp @@ -71,7 +71,7 @@ bool Size(const AnyString& filename, uint64_t& value) } HANDLE hndl = CreateFileW( - wstr.c_str(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + wstr.c_str(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hndl == INVALID_HANDLE_VALUE) { value = 0u; @@ -158,7 +158,7 @@ bool GetLastWriteTime(HANDLE hFile) // Convert the last-write time to local time. if (!FileTimeToSystemTime(&ftWrite, &stUTC)) return false; - if (!SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal)) + if (!SystemTimeToTzSpecificLocalTime(nullptr, &stUTC, &stLocal)) return false; return true; diff --git a/src/ext/yuni/src/yuni/io/file/stream.cpp b/src/ext/yuni/src/yuni/io/file/stream.cpp index 8815990c22..6d5c2cf375 100644 --- a/src/ext/yuni/src/yuni/io/file/stream.cpp +++ b/src/ext/yuni/src/yuni/io/file/stream.cpp @@ -121,7 +121,7 @@ bool Stream::open(const AnyString& filename, int mode) pFd = ::fopen(filename.c_str(), OpenMode::ToCString(mode)); #endif - return (NULL != pFd); + return (pFd); } bool Stream::close() @@ -130,7 +130,7 @@ bool Stream::close() { if (0 == ::fclose(pFd)) { - pFd = NULL; + pFd = nullptr; return true; } return false; diff --git a/src/ext/yuni/src/yuni/io/filename-manipulation.cpp b/src/ext/yuni/src/yuni/io/filename-manipulation.cpp index 3a2fe9e8ee..01a99289a0 100644 --- a/src/ext/yuni/src/yuni/io/filename-manipulation.cpp +++ b/src/ext/yuni/src/yuni/io/filename-manipulation.cpp @@ -283,7 +283,7 @@ bool IsAbsolute(const AnyString& filename) } template -static inline void ExtractFilePathImpl(StringT& out, const AnyString& path, bool systemDependant) +static inline void parent_path_impl_static(StringT& out, const AnyString& path, bool systemDependant) { AnyString::size_type pos = (systemDependant) ? path.find_last_of(IO::Constant::Separator) @@ -294,14 +294,14 @@ static inline void ExtractFilePathImpl(StringT& out, const AnyString& path, bool out.assign(path, pos); } -void ExtractFilePath(String& out, const AnyString& path, bool systemDependant) +void parent_path(String& out, const AnyString& path, bool systemDependant) { - ExtractFilePathImpl(out, path, systemDependant); + parent_path_impl_static(out, path, systemDependant); } -void ExtractFilePath(Clob& out, const AnyString& path, bool systemDependant) +void parent_path_impl(Clob& out, const AnyString& path, bool systemDependant) { - ExtractFilePathImpl(out, path, systemDependant); + parent_path_impl_static(out, path, systemDependant); } template @@ -369,13 +369,13 @@ static inline void ExtractAbsoluteFilePathImpl(StringT& out, String tmp; if (IsAbsolute(path)) { - ExtractFilePath(tmp, path, systemDependant); + parent_path(tmp, path, systemDependant); } else { String absolute; MakeAbsolute(absolute, path); - ExtractFilePath(tmp, absolute, systemDependant); + parent_path(tmp, absolute, systemDependant); } Normalize(out, tmp); } diff --git a/src/ext/yuni/src/yuni/io/filename-manipulation.h b/src/ext/yuni/src/yuni/io/filename-manipulation.h index cb624f3338..9b5e9965fe 100644 --- a/src/ext/yuni/src/yuni/io/filename-manipulation.h +++ b/src/ext/yuni/src/yuni/io/filename-manipulation.h @@ -21,7 +21,7 @@ namespace IO ** The path part will be extracted according the system-(un)dependant path-separator ** \code ** String outputString; -** IO::ExtractFilePath(outputString, "/tmp/foo.txt"); +** IO::parent_path(outputString, "/tmp/foo.txt"); ** std::cout << outputString << std::endl; // writes `/tmp` ** \endcode ** @@ -29,7 +29,7 @@ namespace IO ** \param[in] path The filename ** \param[in] systemDependant Consider only the system-dependant path-separator */ -void ExtractFilePath(String& out, const AnyString& path, bool systemDependant = false); +void parent_path(String& out, const AnyString& path, bool systemDependant = false); /*! ** \brief Extract the path part of a filename @@ -37,7 +37,7 @@ void ExtractFilePath(String& out, const AnyString& path, bool systemDependant = ** The path part will be extracted according the system-(un)dependant path-separator ** \code ** String outputString; -** IO::ExtractFilePath(outputString, "/tmp/foo.txt"); +** IO::parent_path(outputString, "/tmp/foo.txt"); ** std::cout << outputString << std::endl; // writes `/tmp` ** \endcode ** @@ -45,7 +45,7 @@ void ExtractFilePath(String& out, const AnyString& path, bool systemDependant = ** \param[in] path The filename ** \param[in] systemDependant Consider only the system-dependant path-separator */ -void ExtractFilePath(Clob& out, const AnyString& path, bool systemDependant = false); +void parent_path_impl(Clob& out, const AnyString& path, bool systemDependant = false); /*! ** \brief Extract the path part of a filename and make it absolute diff --git a/src/ext/yuni/src/yuni/job/job.cpp b/src/ext/yuni/src/yuni/job/job.cpp index bef4051930..125bae6f51 100644 --- a/src/ext/yuni/src/yuni/job/job.cpp +++ b/src/ext/yuni/src/yuni/job/job.cpp @@ -21,14 +21,14 @@ IJob::IJob() : pThread(nullptr) IJob::~IJob() { - assert(this != NULL and "IJob: Destructor: Oo `this' is null !?"); - assert(pThread == NULL and "A job can not be attached to a thread when destroyed"); + assert(this && "IJob: Destructor: Oo `this' is null !?"); + assert(!pThread && "A job can not be attached to a thread when destroyed"); } bool IJob::suspend(uint delay) const { // This method must only be called from a thread - assert(pThread and "Job: The pointer to the attached thread must not be NULL"); + assert(pThread and "Job: The pointer to the attached thread must not be nullptr"); // We can suspend the job only if it is running if (pState == stateRunning) diff --git a/src/ext/yuni/src/yuni/job/queue/service.cpp b/src/ext/yuni/src/yuni/job/queue/service.cpp index 775f456cd3..18fe860903 100644 --- a/src/ext/yuni/src/yuni/job/queue/service.cpp +++ b/src/ext/yuni/src/yuni/job/queue/service.cpp @@ -37,14 +37,14 @@ static inline uint OptimalCPUCount() return count; } -QueueService::QueueService() : pStatus(sStopped), pThreads(NULL) +QueueService::QueueService() : pStatus(sStopped), pThreads(nullptr) { uint count = OptimalCPUCount(); pMinimumThreadCount = count; pMaximumThreadCount = count; } -QueueService::QueueService(bool autostart) : pStatus(sStopped), pThreads(NULL) +QueueService::QueueService(bool autostart) : pStatus(sStopped), pThreads(nullptr) { uint count = OptimalCPUCount(); pMinimumThreadCount = count; @@ -172,7 +172,7 @@ void QueueService::stop(uint timeout) return; threads = (ThreadArray*)pThreads; - pThreads = NULL; + pThreads = nullptr; pStatus = sStopping; } diff --git a/src/ext/yuni/src/yuni/thread/signal.cpp b/src/ext/yuni/src/yuni/thread/signal.cpp index 335d61fd20..9da95f2dde 100644 --- a/src/ext/yuni/src/yuni/thread/signal.cpp +++ b/src/ext/yuni/src/yuni/thread/signal.cpp @@ -33,10 +33,10 @@ Signal::Signal() // Making sure that our pseudo HANDLE type is valid assert(sizeof(HANDLE) >= sizeof(void*) and "Invalid type for Signal::pHandle"); - pHandle = (void*)CreateEvent(NULL, // default security attributes + pHandle = (void*)CreateEvent(nullptr, // default security attributes TRUE, // manual-reset event FALSE, // initial state is nonsignaled - NULL); // unamed + nullptr); // unamed #else pSignalled = false; @@ -53,10 +53,10 @@ Signal::Signal(const Signal&) // Making sure that our pseudo HANDLE type is valid assert(sizeof(HANDLE) >= sizeof(void*) and "Invalid type for Signal::pHandle"); - pHandle = (void*)CreateEvent(NULL, // default security attributes + pHandle = (void*)CreateEvent(nullptr, // default security attributes TRUE, // manual-reset event FALSE, // initial state is nonsignaled - NULL); // unamed + nullptr); // unamed #else pSignalled = false; @@ -194,7 +194,7 @@ bool Signal::wait(uint timeout) // Set the timespec t at [timeout] milliseconds in the future. assert(timeout < 2147483648u and "Invalid range for timeout (Signal::wait(timeout))"); - YUNI_SYSTEM_GETTIMEOFDAY(&now, NULL); + YUNI_SYSTEM_GETTIMEOFDAY(&now, nullptr); t.tv_nsec = (long)(now.tv_usec * 1000 + (((int)timeout % 1000) * 1000000)); t.tv_sec = (time_t)(now.tv_sec + timeout / 1000 + (t.tv_nsec / 1000000000L)); t.tv_nsec %= 1000000000L; diff --git a/src/ext/yuni/src/yuni/thread/thread.cpp b/src/ext/yuni/src/yuni/thread/thread.cpp index 7a84bc0bbd..c8eb06dd9f 100644 --- a/src/ext/yuni/src/yuni/thread/thread.cpp +++ b/src/ext/yuni/src/yuni/thread/thread.cpp @@ -89,8 +89,8 @@ extern "C" YUNI_THREAD_FNC_RETURN threadCallbackExecute(void* arg) #ifndef YUNI_OS_WINDOWS // pthread - Adjust cancellation behaviors - // ::pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); - ::pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); + // ::pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr); + ::pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, nullptr); #endif if (thread.onStarting()) @@ -196,7 +196,7 @@ IThread::IThread(uint stacksize) : , pShouldStop(true), #ifdef YUNI_HAS_PTHREAD_ATTR_SETSTACKSIZE - pStackSize((stacksize < PTHREAD_STACK_MIN ? PTHREAD_STACK_MIN : stacksize)) + pStackSize((stacksize < PTHREAD_STACK_MIN ? static_cast(PTHREAD_STACK_MIN) : stacksize)) #else pStackSize(stacksize) #endif diff --git a/src/ext/yuni/src/yuni/uuid/uuid.cpp b/src/ext/yuni/src/yuni/uuid/uuid.cpp index be2e1cc2db..d151ceca1b 100644 --- a/src/ext/yuni/src/yuni/uuid/uuid.cpp +++ b/src/ext/yuni/src/yuni/uuid/uuid.cpp @@ -69,7 +69,7 @@ void UUID::writeToCString(char cstring[42]) const bool UUID::initializeFromCString(const char* cstring) { - assert(cstring != NULL); + assert(cstring != nullptr); #ifndef YUNI_OS_WINDOWS // Why uuid_parse takes a char* and not a const char* ?? diff --git a/src/format-code.sh b/src/format-code.sh index bfb32bb0c8..abac85a423 100755 --- a/src/format-code.sh +++ b/src/format-code.sh @@ -3,8 +3,8 @@ if [ $# -eq 0 ] then # No arguments: format all - SOURCE_DIRS="analyzer/ ext/ libs/ solver/ tools/ ui/" - SOURCE_FILES=$(find $SOURCE_DIRS -type f \( -name "*.h" -or -name "*.cpp" -or -name "*.h" -or -name "*.hxx" -or -name "*.hpp" -or -name "*.cxx" -or -name "*.c" \) -and -not \( -iname "sqlite3.c" -or -name "*.h.generator.hpp" -or -name "*.hxx.generator.hpp" -or -name "*.generator.commonstypes.hpp" \)) + SOURCE_DIRS="analyzer/ libs/ solver/ tools/ config/ tests/ packaging/" + SOURCE_FILES=$(find $SOURCE_DIRS -regextype egrep -regex ".*/*\.(c|cxx|cpp|cc|h|hxx|hpp)$" ! -path '*/antlr-interface/*') else # Format files provided as arguments SOURCE_FILES="$@" @@ -17,8 +17,8 @@ else echo "$SOURCE_FILES" | xargs dos2unix fi -if ! [ -x "$(command -v clang-format-10)" ]; then - echo 'Warning: clang-format-10 is not installed. Skipping' >&2 +if ! [ -x "$(command -v clang-format)" ]; then + echo 'Warning: clang-format is not installed. Skipping' >&2 else - echo "$SOURCE_FILES" | xargs clang-format-10 -i --verbose + echo "$SOURCE_FILES" | xargs clang-format -i --verbose fi diff --git a/src/libs/antares/CMakeLists.txt b/src/libs/antares/CMakeLists.txt index 66cf4ec145..5b4f253052 100644 --- a/src/libs/antares/CMakeLists.txt +++ b/src/libs/antares/CMakeLists.txt @@ -1,82 +1,76 @@ OMESSAGE("Antares Core library") +add_subdirectory(InfoCollection) add_subdirectory(args) -add_subdirectory(writer) -add_subdirectory(memory) - -add_subdirectory(object) - add_subdirectory(array) -add_subdirectory(correlation) +add_subdirectory(benchmarking) +add_subdirectory(checks) add_subdirectory(concurrency) - -add_subdirectory(logs) -add_subdirectory(jit) +add_subdirectory(correlation) +add_subdirectory(date) +add_subdirectory(exception) +add_subdirectory(file-tree-study-loader) add_subdirectory(inifile) - -add_subdirectory(benchmarking) -add_subdirectory(InfoCollection) add_subdirectory(io) -add_subdirectory(exception) - +add_subdirectory(jit) +add_subdirectory(locale) +add_subdirectory(locator) +add_subdirectory(logs) +add_subdirectory(memory) +add_subdirectory(mersenne-twister) +add_subdirectory(paths) +add_subdirectory(resources) +add_subdirectory(series) +add_subdirectory(stdcxx) +add_subdirectory(study) +add_subdirectory(study-loader) add_subdirectory(sys) - +add_subdirectory(utils) +add_subdirectory(writer) +if(WITH_ANTLR4) + add_subdirectory(antlr-interface) +endif() + +add_subdirectory(optimization-options) + +set(HEADERS + include/antares/antares/antares.h + include/antares/antares/constants.h + include/antares/antares/fatal-error.h + include/antares/antares/version.h + include/antares/antares/Enum.hpp + include/antares/antares/Enum.hxx +) set(SRC - config.h - constants.h - constants.cpp - xpansion.h - # Misc - - locale.h - locale.cpp - - fatal-error.h - - # resource - resources/resources.h - resources/resources.cpp - - solver.h - solver.cpp - - # version - version.h - version.cpp - - # Enum - # TODO : should be in a target_include_directories : but need to remove all .h from all SRC - Enum.hpp - Enum.hxx + ${HEADERS} + constants.cpp + version.cpp ) -add_subdirectory(date) - -add_subdirectory(checks) -add_subdirectory(study) -add_subdirectory(stdcxx) -add_subdirectory(utils) -add_subdirectory(paths) -add_subdirectory(mersenne-twister) add_library(antares-core - antares.h - ${SRC} + ${SRC} ) -#TODO : needed for include yuni : why yuni must be include first ??? cheat : made it public so everybody will have this include (should be done in yuni) -#TODO : needed for include target_include_directories(antares-core - PRIVATE - ${CMAKE_SOURCE_DIR}/libs - ) + PUBLIC + $ + PRIVATE + $ +) target_link_libraries(antares-core - PUBLIC - yuni-static-core - Antares::logs - Antares::exception - ) + PUBLIC + yuni-static-core + Antares::logs + Antares::exception + Antares::study + Antares::config +) import_std_libs(antares-core) + +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/libs/antares/Enum.hxx b/src/libs/antares/Enum.hxx deleted file mode 100644 index af78bef493..0000000000 --- a/src/libs/antares/Enum.hxx +++ /dev/null @@ -1,86 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef ANTARES_DATA_ENUM_HXX -#define ANTARES_DATA_ENUM_HXX - -#include -#include - -#include -#include - -#include - -namespace Antares::Data::Enum -{ -template -E fromString(const std::string& name) -{ - const auto& names = getNames(); - const auto& it = std::find(names.begin(), names.end(), name); - if (it == names.end()) - { - throw AssertionError("Unexpected " + stdcxx::simpleClassName() + " name " + name); - } - - return static_cast(it - names.begin()); -} - -template -std::string toString(const E& value) -{ - auto index = static_cast(value); - const auto& names = getNames(); - if (index >= names.size()) - { - throw AssertionError("Unexpected " + stdcxx::simpleClassName() + " value " - + std::to_string(index)); - } - return *(names.begin() + index); -} - -template -std::list enumList() -{ - std::list result; - const auto& names = getNames(); - for (auto name : names) - { - result.push_back(fromString(name)); - } - - return result; -} - -} // namespace Antares::Data::Enum - - - - - -#endif // ANTARES_DATA_ENUM_HXX \ No newline at end of file diff --git a/src/libs/antares/InfoCollection/CMakeLists.txt b/src/libs/antares/InfoCollection/CMakeLists.txt index 08daf09625..40e4f92703 100644 --- a/src/libs/antares/InfoCollection/CMakeLists.txt +++ b/src/libs/antares/InfoCollection/CMakeLists.txt @@ -21,16 +21,9 @@ target_link_libraries(${PROJ} target_include_directories(${PROJ} PUBLIC - ${CMAKE_SOURCE_DIR}/libs #study - ${CMAKE_SOURCE_DIR}/libs/antares/date #parameters -> date - ${CMAKE_SOURCE_DIR}/libs/antares/array #links - ${CMAKE_SOURCE_DIR}/libs/antares/logs #study -> binding constraint -> matrix -> jit - ${CMAKE_SOURCE_DIR}/libs/antares/io #study -> binding constraint -> matrix - ${CMAKE_SOURCE_DIR}/libs/antares/writer #study - ${CMAKE_SOURCE_DIR}/libs/antares/exception #enum -> exception - ${CMAKE_SOURCE_DIR}/libs/antares/jit # something,something -> jit - ${CMAKE_SOURCE_DIR}/libs/antares/memory/include #study -> BC -> link -> memory - ${CMAKE_SOURCE_DIR}/libs/antares/inifile #study -> inifile - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/InfoCollection/StudyInfoCollector.cpp b/src/libs/antares/InfoCollection/StudyInfoCollector.cpp index 05f9894f12..fe72e57d10 100644 --- a/src/libs/antares/InfoCollection/StudyInfoCollector.cpp +++ b/src/libs/antares/InfoCollection/StudyInfoCollector.cpp @@ -1,14 +1,37 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 22/08/23. // #include "antares/infoCollection/StudyInfoCollector.h" + +#include #include "antares/benchmarking/DurationCollector.h" #include "antares/benchmarking/file_content.h" -#include "../../../config.h" using namespace Antares::Data; -namespace Benchmarking { + +namespace Benchmarking +{ // Collecting data study // --------------------------- @@ -43,7 +66,9 @@ void StudyInfoCollector::performedYearsCountToFileContent(FileContent& file_cont for (uint i = 0; i < study_.parameters.nbYears; i++) { if (study_.parameters.yearsFilter[i]) + { nbPerformedYears++; + } } // Adding an item related to number of performed years to the file content @@ -58,14 +83,8 @@ void StudyInfoCollector::enabledThermalClustersCountToFileContent(FileContent& f auto end = study_.areas.end(); for (auto i = study_.areas.begin(); i != end; ++i) { - Area& area = *(i->second); - auto end = area.thermal.list.end(); - for (auto i = area.thermal.list.begin(); i != end; ++i) - { - auto& cluster = i->second; - if (cluster->enabled) - nbEnabledThermalClusters++; - } + const Area& area = *(i->second); + nbEnabledThermalClusters += area.thermal.list.enabledAndNotMustRunCount(); } // Adding an item related to number of enabled thermal clusters to the file content @@ -74,27 +93,27 @@ void StudyInfoCollector::enabledThermalClustersCountToFileContent(FileContent& f void StudyInfoCollector::enabledBindingConstraintsCountToFileContent(FileContent& file_content) { - auto activeContraints = study_.bindingConstraints.activeContraints(); - auto nbEnabledBC = activeContraints.size(); + auto activeConstraints = study_.bindingConstraints.activeConstraints(); + auto nbEnabledBC = activeConstraints.size(); unsigned nbEnabledHourlyBC(0); unsigned nbEnabledDailyBC(0); unsigned nbEnabledWeeklyBC(0); - for (uint i = 0; i < nbEnabledBC; i++) + for (const auto& bc: activeConstraints) { - switch (activeContraints[i]->type()) + switch (bc->type()) { - case BindingConstraint::Type::typeHourly: - nbEnabledHourlyBC++; - break; - case BindingConstraint::Type::typeDaily: - nbEnabledDailyBC++; - break; - case BindingConstraint::Type::typeWeekly: - nbEnabledWeeklyBC++; - break; - default: - break; + case BindingConstraint::Type::typeHourly: + nbEnabledHourlyBC++; + break; + case BindingConstraint::Type::typeDaily: + nbEnabledDailyBC++; + break; + case BindingConstraint::Type::typeWeekly: + nbEnabledWeeklyBC++; + break; + default: + break; } } @@ -106,8 +125,8 @@ void StudyInfoCollector::enabledBindingConstraintsCountToFileContent(FileContent void StudyInfoCollector::unitCommitmentModeToFileContent(FileContent& file_content) { - const char* unitCommitment - = UnitCommitmentModeToCString(study_.parameters.unitCommitment.ucMode); + const char* unitCommitment = UnitCommitmentModeToCString( + study_.parameters.unitCommitment.ucMode); file_content.addItemToSection("study", "unit commitment", unitCommitment); } @@ -119,25 +138,25 @@ void StudyInfoCollector::maxNbYearsInParallelToFileContent(FileContent& file_con void StudyInfoCollector::solverVersionToFileContent(FileContent& file_content) { // Example : 8.3.0 -> 830 - const unsigned int version - = 100 * ANTARES_VERSION_HI + 10 * ANTARES_VERSION_LO + ANTARES_VERSION_BUILD; + const unsigned int version = 100 * ANTARES_VERSION_HI + 10 * ANTARES_VERSION_LO + + ANTARES_VERSION_BUILD; file_content.addItemToSection("study", "antares version", version); } void StudyInfoCollector::ORToolsUsed(FileContent& file_content) { - const bool& ortoolsUsed = study_.parameters.ortoolsUsed; + const bool& ortoolsUsed = study_.parameters.optOptions.ortoolsUsed; file_content.addItemToSection("study", "ortools used", ortoolsUsed ? "true" : "false"); } void StudyInfoCollector::ORToolsSolver(FileContent& file_content) { - const bool& ortoolsUsed = study_.parameters.ortoolsUsed; + const bool& ortoolsUsed = study_.parameters.optOptions.ortoolsUsed; std::string ortoolsSolver = "none"; if (ortoolsUsed) { - ortoolsSolver = study_.parameters.ortoolsSolver; + ortoolsSolver = study_.parameters.optOptions.ortoolsSolver; } file_content.addItemToSection("study", "ortools solver", ortoolsSolver); } @@ -148,8 +167,9 @@ void SimulationInfoCollector::toFileContent(FileContent& file_content) { file_content.addItemToSection("optimization problem", "variables", opt_info_.nbVariables); file_content.addItemToSection("optimization problem", "constraints", opt_info_.nbConstraints); - file_content.addItemToSection( - "optimization problem", "non-zero coefficients", opt_info_.nbNonZeroCoeffs); + file_content.addItemToSection("optimization problem", + "non-zero coefficients", + opt_info_.nbNonZeroCoeffs); } -} \ No newline at end of file +} // namespace Benchmarking diff --git a/src/libs/antares/InfoCollection/include/antares/infoCollection/StudyInfoCollector.h b/src/libs/antares/InfoCollection/include/antares/infoCollection/StudyInfoCollector.h index bb3b1f1df8..6aca93a605 100644 --- a/src/libs/antares/InfoCollection/include/antares/infoCollection/StudyInfoCollector.h +++ b/src/libs/antares/InfoCollection/include/antares/infoCollection/StudyInfoCollector.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 22/08/23. // @@ -6,15 +26,18 @@ #include "antares/study/study.h" -namespace Benchmarking { +namespace Benchmarking +{ class FileContent; class StudyInfoCollector { public: - StudyInfoCollector(const Antares::Data::Study& study) : study_(study) + StudyInfoCollector(const Antares::Data::Study& study): + study_(study) { } + void toFileContent(FileContent& file_content); private: @@ -35,7 +58,6 @@ class StudyInfoCollector const Antares::Data::Study& study_; }; - struct OptimizationInfo { unsigned int nbVariables = 0; @@ -46,11 +68,12 @@ struct OptimizationInfo class SimulationInfoCollector { public: - SimulationInfoCollector(const OptimizationInfo& optInfo) : opt_info_(optInfo){}; + SimulationInfoCollector(const OptimizationInfo& optInfo): + opt_info_(optInfo){}; void toFileContent(FileContent& file_content); private: const OptimizationInfo& opt_info_; }; -} \ No newline at end of file +} // namespace Benchmarking diff --git a/src/libs/antares/antares.h b/src/libs/antares/antares.h deleted file mode 100644 index 41fec76c09..0000000000 --- a/src/libs/antares/antares.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_H__ -#define __ANTARES_H__ - -#include -#include - -#define foreach YUNI_FOREACH - -#endif // __ANTARES_H__ diff --git a/src/libs/antares/antlr-interface/CMakeLists.txt b/src/libs/antares/antlr-interface/CMakeLists.txt new file mode 100644 index 0000000000..4cd06fef3b --- /dev/null +++ b/src/libs/antares/antlr-interface/CMakeLists.txt @@ -0,0 +1,34 @@ + +set(PROJ antlr-interface) +set(HEADERS + ExprBaseVisitor.h + ExprLexer.h + ExprParser.h + ExprVisitor.h +) + +Set(SRCS +ExprBaseVisitor.cpp +ExprLexer.cpp +ExprParser.cpp +ExprVisitor.cpp +) +find_package(antlr4-runtime CONFIG REQUIRED) + +add_library(${PROJ} ${SRCS}) +add_library(Antares::${PROJ} ALIAS ${PROJ}) + +if(MSVC) + target_link_libraries(${PROJ} PUBLIC antlr4_shared) # vcpkg triplet x64-windows provides shared lib +else() + target_link_libraries(${PROJ} PUBLIC antlr4_static) # vcpkg triplet x64-linux provides static lib +endif() + +target_include_directories(${PROJ} + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${ANTLR4_INCLUDE_DIR}) + +install(FILES ${HEADERS} + DESTINATION "include" +) diff --git a/src/libs/antares/antlr-interface/Expr.g4 b/src/libs/antares/antlr-interface/Expr.g4 new file mode 100644 index 0000000000..d0d1642497 --- /dev/null +++ b/src/libs/antares/antlr-interface/Expr.g4 @@ -0,0 +1,50 @@ +/* +Copyright (c) 2024, RTE (https://www.rte-france.com) + +See AUTHORS.txt + +This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at http://mozilla.org/MPL/2.0/. + +SPDX-License-Identifier: MPL-2.0 + +This file is part of the Antares project. +*/ + +grammar Expr; + +/* To match the whole input */ +fullexpr: expr EOF; + +shift: TIME (op=('+' | '-') expr)?; + +expr: '-' expr # negation + | expr op=('/' | '*') expr # muldiv + | expr op=('+' | '-') expr # addsub + | expr COMPARISON expr # comparison + | IDENTIFIER # identifier + | IDENTIFIER '.' IDENTIFIER # portField + | NUMBER # number + | '(' expr ')' # expression + | IDENTIFIER '(' expr ')' # function + | IDENTIFIER '[' shift (',' shift)* ']' # timeShift + | IDENTIFIER '[' expr (',' expr )* ']' # timeIndex + | IDENTIFIER '[' shift1=shift '..' shift2=shift ']' # timeShiftRange + | IDENTIFIER '[' expr '..' expr ']' # timeRange + ; + +fragment DIGIT : [0-9] ; +fragment CHAR : [a-zA-Z_]; +fragment CHAR_OR_DIGIT : (CHAR | DIGIT); + +NUMBER : DIGIT+ ('.' DIGIT+)?; +TIME : 't'; +IDENTIFIER : CHAR CHAR_OR_DIGIT*; +COMPARISON : ( '=' | '>=' | '<=' ); +ADDSUB : ( '+' | '-' ); +MULDIV : ( '*' | '/' ); +LBRACKET: '['; +RBRACKET: ']'; + +WS: (' ' | '\t' | '\r'| '\n') -> skip; diff --git a/src/libs/antares/antlr-interface/Expr.interp b/src/libs/antares/antlr-interface/Expr.interp new file mode 100644 index 0000000000..bed351938d --- /dev/null +++ b/src/libs/antares/antlr-interface/Expr.interp @@ -0,0 +1,50 @@ +token literal names: +null +'+' +'-' +'/' +'*' +'.' +'(' +')' +',' +'..' +null +'t' +null +null +null +null +'[' +']' +null + +token symbolic names: +null +null +null +null +null +null +null +null +null +null +NUMBER +TIME +IDENTIFIER +COMPARISON +ADDSUB +MULDIV +LBRACKET +RBRACKET +WS + +rule names: +fullexpr +shift +expr + + +atn: +[4, 1, 18, 86, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 3, 1, 13, 8, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 2, 37, 8, 2, 10, 2, 12, 2, 40, 9, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 2, 49, 8, 2, 10, 2, 12, 2, 52, 9, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3, 2, 70, 8, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 5, 2, 81, 8, 2, 10, 2, 12, 2, 84, 9, 2, 1, 2, 0, 1, 4, 3, 0, 2, 4, 0, 2, 1, 0, 1, 2, 1, 0, 3, 4, 97, 0, 6, 1, 0, 0, 0, 2, 9, 1, 0, 0, 0, 4, 69, 1, 0, 0, 0, 6, 7, 3, 4, 2, 0, 7, 8, 5, 0, 0, 1, 8, 1, 1, 0, 0, 0, 9, 12, 5, 11, 0, 0, 10, 11, 7, 0, 0, 0, 11, 13, 3, 4, 2, 0, 12, 10, 1, 0, 0, 0, 12, 13, 1, 0, 0, 0, 13, 3, 1, 0, 0, 0, 14, 15, 6, 2, -1, 0, 15, 16, 5, 2, 0, 0, 16, 70, 3, 4, 2, 13, 17, 70, 5, 12, 0, 0, 18, 19, 5, 12, 0, 0, 19, 20, 5, 5, 0, 0, 20, 70, 5, 12, 0, 0, 21, 70, 5, 10, 0, 0, 22, 23, 5, 6, 0, 0, 23, 24, 3, 4, 2, 0, 24, 25, 5, 7, 0, 0, 25, 70, 1, 0, 0, 0, 26, 27, 5, 12, 0, 0, 27, 28, 5, 6, 0, 0, 28, 29, 3, 4, 2, 0, 29, 30, 5, 7, 0, 0, 30, 70, 1, 0, 0, 0, 31, 32, 5, 12, 0, 0, 32, 33, 5, 16, 0, 0, 33, 38, 3, 2, 1, 0, 34, 35, 5, 8, 0, 0, 35, 37, 3, 2, 1, 0, 36, 34, 1, 0, 0, 0, 37, 40, 1, 0, 0, 0, 38, 36, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 41, 1, 0, 0, 0, 40, 38, 1, 0, 0, 0, 41, 42, 5, 17, 0, 0, 42, 70, 1, 0, 0, 0, 43, 44, 5, 12, 0, 0, 44, 45, 5, 16, 0, 0, 45, 50, 3, 4, 2, 0, 46, 47, 5, 8, 0, 0, 47, 49, 3, 4, 2, 0, 48, 46, 1, 0, 0, 0, 49, 52, 1, 0, 0, 0, 50, 48, 1, 0, 0, 0, 50, 51, 1, 0, 0, 0, 51, 53, 1, 0, 0, 0, 52, 50, 1, 0, 0, 0, 53, 54, 5, 17, 0, 0, 54, 70, 1, 0, 0, 0, 55, 56, 5, 12, 0, 0, 56, 57, 5, 16, 0, 0, 57, 58, 3, 2, 1, 0, 58, 59, 5, 9, 0, 0, 59, 60, 3, 2, 1, 0, 60, 61, 5, 17, 0, 0, 61, 70, 1, 0, 0, 0, 62, 63, 5, 12, 0, 0, 63, 64, 5, 16, 0, 0, 64, 65, 3, 4, 2, 0, 65, 66, 5, 9, 0, 0, 66, 67, 3, 4, 2, 0, 67, 68, 5, 17, 0, 0, 68, 70, 1, 0, 0, 0, 69, 14, 1, 0, 0, 0, 69, 17, 1, 0, 0, 0, 69, 18, 1, 0, 0, 0, 69, 21, 1, 0, 0, 0, 69, 22, 1, 0, 0, 0, 69, 26, 1, 0, 0, 0, 69, 31, 1, 0, 0, 0, 69, 43, 1, 0, 0, 0, 69, 55, 1, 0, 0, 0, 69, 62, 1, 0, 0, 0, 70, 82, 1, 0, 0, 0, 71, 72, 10, 12, 0, 0, 72, 73, 7, 1, 0, 0, 73, 81, 3, 4, 2, 13, 74, 75, 10, 11, 0, 0, 75, 76, 7, 0, 0, 0, 76, 81, 3, 4, 2, 12, 77, 78, 10, 10, 0, 0, 78, 79, 5, 13, 0, 0, 79, 81, 3, 4, 2, 11, 80, 71, 1, 0, 0, 0, 80, 74, 1, 0, 0, 0, 80, 77, 1, 0, 0, 0, 81, 84, 1, 0, 0, 0, 82, 80, 1, 0, 0, 0, 82, 83, 1, 0, 0, 0, 83, 5, 1, 0, 0, 0, 84, 82, 1, 0, 0, 0, 6, 12, 38, 50, 69, 80, 82] \ No newline at end of file diff --git a/src/libs/antares/antlr-interface/Expr.tokens b/src/libs/antares/antlr-interface/Expr.tokens new file mode 100644 index 0000000000..29d96df5f3 --- /dev/null +++ b/src/libs/antares/antlr-interface/Expr.tokens @@ -0,0 +1,30 @@ +T__0=1 +T__1=2 +T__2=3 +T__3=4 +T__4=5 +T__5=6 +T__6=7 +T__7=8 +T__8=9 +NUMBER=10 +TIME=11 +IDENTIFIER=12 +COMPARISON=13 +ADDSUB=14 +MULDIV=15 +LBRACKET=16 +RBRACKET=17 +WS=18 +'+'=1 +'-'=2 +'/'=3 +'*'=4 +'.'=5 +'('=6 +')'=7 +','=8 +'..'=9 +'t'=11 +'['=16 +']'=17 diff --git a/src/libs/antares/antlr-interface/ExprBaseVisitor.cpp b/src/libs/antares/antlr-interface/ExprBaseVisitor.cpp new file mode 100644 index 0000000000..42d6fef5d3 --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprBaseVisitor.cpp @@ -0,0 +1,7 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + + +#include "ExprBaseVisitor.h" + + diff --git a/src/libs/antares/antlr-interface/ExprBaseVisitor.h b/src/libs/antares/antlr-interface/ExprBaseVisitor.h new file mode 100644 index 0000000000..a8af3c573f --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprBaseVisitor.h @@ -0,0 +1,80 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + +#pragma once + + +#include "antlr4-runtime.h" +#include "ExprVisitor.h" + + +/** + * This class provides an empty implementation of ExprVisitor, which can be + * extended to create a visitor which only needs to handle a subset of the available methods. + */ +class ExprBaseVisitor : public ExprVisitor { +public: + + virtual std::any visitFullexpr(ExprParser::FullexprContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitShift(ExprParser::ShiftContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitIdentifier(ExprParser::IdentifierContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitNegation(ExprParser::NegationContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitExpression(ExprParser::ExpressionContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitComparison(ExprParser::ComparisonContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitAddsub(ExprParser::AddsubContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitPortField(ExprParser::PortFieldContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitMuldiv(ExprParser::MuldivContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitNumber(ExprParser::NumberContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitTimeIndex(ExprParser::TimeIndexContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitTimeShift(ExprParser::TimeShiftContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitFunction(ExprParser::FunctionContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitTimeShiftRange(ExprParser::TimeShiftRangeContext *ctx) override { + return visitChildren(ctx); + } + + virtual std::any visitTimeRange(ExprParser::TimeRangeContext *ctx) override { + return visitChildren(ctx); + } + + +}; + diff --git a/src/libs/antares/antlr-interface/ExprLexer.cpp b/src/libs/antares/antlr-interface/ExprLexer.cpp new file mode 100644 index 0000000000..a645fcddd0 --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprLexer.cpp @@ -0,0 +1,177 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + + +#include "ExprLexer.h" + + +using namespace antlr4; + + + +using namespace antlr4; + +namespace { + +struct ExprLexerStaticData final { + ExprLexerStaticData(std::vector ruleNames, + std::vector channelNames, + std::vector modeNames, + std::vector literalNames, + std::vector symbolicNames) + : ruleNames(std::move(ruleNames)), channelNames(std::move(channelNames)), + modeNames(std::move(modeNames)), literalNames(std::move(literalNames)), + symbolicNames(std::move(symbolicNames)), + vocabulary(this->literalNames, this->symbolicNames) {} + + ExprLexerStaticData(const ExprLexerStaticData&) = delete; + ExprLexerStaticData(ExprLexerStaticData&&) = delete; + ExprLexerStaticData& operator=(const ExprLexerStaticData&) = delete; + ExprLexerStaticData& operator=(ExprLexerStaticData&&) = delete; + + std::vector decisionToDFA; + antlr4::atn::PredictionContextCache sharedContextCache; + const std::vector ruleNames; + const std::vector channelNames; + const std::vector modeNames; + const std::vector literalNames; + const std::vector symbolicNames; + const antlr4::dfa::Vocabulary vocabulary; + antlr4::atn::SerializedATNView serializedATN; + std::unique_ptr atn; +}; + +::antlr4::internal::OnceFlag exprlexerLexerOnceFlag; +#if ANTLR4_USE_THREAD_LOCAL_CACHE +static thread_local +#endif +ExprLexerStaticData *exprlexerLexerStaticData = nullptr; + +void exprlexerLexerInitialize() { +#if ANTLR4_USE_THREAD_LOCAL_CACHE + if (exprlexerLexerStaticData != nullptr) { + return; + } +#else + assert(exprlexerLexerStaticData == nullptr); +#endif + auto staticData = std::make_unique( + std::vector{ + "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", + "DIGIT", "CHAR", "CHAR_OR_DIGIT", "NUMBER", "TIME", "IDENTIFIER", + "COMPARISON", "ADDSUB", "MULDIV", "LBRACKET", "RBRACKET", "WS" + }, + std::vector{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN" + }, + std::vector{ + "DEFAULT_MODE" + }, + std::vector{ + "", "'+'", "'-'", "'/'", "'*'", "'.'", "'('", "')'", "','", "'..'", + "", "'t'", "", "", "", "", "'['", "']'" + }, + std::vector{ + "", "", "", "", "", "", "", "", "", "", "NUMBER", "TIME", "IDENTIFIER", + "COMPARISON", "ADDSUB", "MULDIV", "LBRACKET", "RBRACKET", "WS" + } + ); + static const int32_t serializedATNSegment[] = { + 4,0,18,111,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, + 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13,2,14, + 7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20,7,20,1,0, + 1,0,1,1,1,1,1,2,1,2,1,3,1,3,1,4,1,4,1,5,1,5,1,6,1,6,1,7,1,7,1,8,1,8,1, + 8,1,9,1,9,1,10,1,10,1,11,1,11,3,11,69,8,11,1,12,4,12,72,8,12,11,12,12, + 12,73,1,12,1,12,4,12,78,8,12,11,12,12,12,79,3,12,82,8,12,1,13,1,13,1, + 14,1,14,5,14,88,8,14,10,14,12,14,91,9,14,1,15,1,15,1,15,1,15,1,15,3,15, + 98,8,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19,1,19,1,20,1,20,1,20,1,20,0, + 0,21,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,0,21,0,23,0,25,10,27, + 11,29,12,31,13,33,14,35,15,37,16,39,17,41,18,1,0,5,1,0,48,57,3,0,65,90, + 95,95,97,122,2,0,43,43,45,45,2,0,42,42,47,47,3,0,9,10,13,13,32,32,114, + 0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0, + 0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,25,1,0,0,0,0,27,1,0,0,0, + 0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,37,1,0,0,0,0,39, + 1,0,0,0,0,41,1,0,0,0,1,43,1,0,0,0,3,45,1,0,0,0,5,47,1,0,0,0,7,49,1,0, + 0,0,9,51,1,0,0,0,11,53,1,0,0,0,13,55,1,0,0,0,15,57,1,0,0,0,17,59,1,0, + 0,0,19,62,1,0,0,0,21,64,1,0,0,0,23,68,1,0,0,0,25,71,1,0,0,0,27,83,1,0, + 0,0,29,85,1,0,0,0,31,97,1,0,0,0,33,99,1,0,0,0,35,101,1,0,0,0,37,103,1, + 0,0,0,39,105,1,0,0,0,41,107,1,0,0,0,43,44,5,43,0,0,44,2,1,0,0,0,45,46, + 5,45,0,0,46,4,1,0,0,0,47,48,5,47,0,0,48,6,1,0,0,0,49,50,5,42,0,0,50,8, + 1,0,0,0,51,52,5,46,0,0,52,10,1,0,0,0,53,54,5,40,0,0,54,12,1,0,0,0,55, + 56,5,41,0,0,56,14,1,0,0,0,57,58,5,44,0,0,58,16,1,0,0,0,59,60,5,46,0,0, + 60,61,5,46,0,0,61,18,1,0,0,0,62,63,7,0,0,0,63,20,1,0,0,0,64,65,7,1,0, + 0,65,22,1,0,0,0,66,69,3,21,10,0,67,69,3,19,9,0,68,66,1,0,0,0,68,67,1, + 0,0,0,69,24,1,0,0,0,70,72,3,19,9,0,71,70,1,0,0,0,72,73,1,0,0,0,73,71, + 1,0,0,0,73,74,1,0,0,0,74,81,1,0,0,0,75,77,5,46,0,0,76,78,3,19,9,0,77, + 76,1,0,0,0,78,79,1,0,0,0,79,77,1,0,0,0,79,80,1,0,0,0,80,82,1,0,0,0,81, + 75,1,0,0,0,81,82,1,0,0,0,82,26,1,0,0,0,83,84,5,116,0,0,84,28,1,0,0,0, + 85,89,3,21,10,0,86,88,3,23,11,0,87,86,1,0,0,0,88,91,1,0,0,0,89,87,1,0, + 0,0,89,90,1,0,0,0,90,30,1,0,0,0,91,89,1,0,0,0,92,98,5,61,0,0,93,94,5, + 62,0,0,94,98,5,61,0,0,95,96,5,60,0,0,96,98,5,61,0,0,97,92,1,0,0,0,97, + 93,1,0,0,0,97,95,1,0,0,0,98,32,1,0,0,0,99,100,7,2,0,0,100,34,1,0,0,0, + 101,102,7,3,0,0,102,36,1,0,0,0,103,104,5,91,0,0,104,38,1,0,0,0,105,106, + 5,93,0,0,106,40,1,0,0,0,107,108,7,4,0,0,108,109,1,0,0,0,109,110,6,20, + 0,0,110,42,1,0,0,0,7,0,68,73,79,81,89,97,1,6,0,0 + }; + staticData->serializedATN = antlr4::atn::SerializedATNView(serializedATNSegment, sizeof(serializedATNSegment) / sizeof(serializedATNSegment[0])); + + antlr4::atn::ATNDeserializer deserializer; + staticData->atn = deserializer.deserialize(staticData->serializedATN); + + const size_t count = staticData->atn->getNumberOfDecisions(); + staticData->decisionToDFA.reserve(count); + for (size_t i = 0; i < count; i++) { + staticData->decisionToDFA.emplace_back(staticData->atn->getDecisionState(i), i); + } + exprlexerLexerStaticData = staticData.release(); +} + +} + +ExprLexer::ExprLexer(CharStream *input) : Lexer(input) { + ExprLexer::initialize(); + _interpreter = new atn::LexerATNSimulator(this, *exprlexerLexerStaticData->atn, exprlexerLexerStaticData->decisionToDFA, exprlexerLexerStaticData->sharedContextCache); +} + +ExprLexer::~ExprLexer() { + delete _interpreter; +} + +std::string ExprLexer::getGrammarFileName() const { + return "Expr.g4"; +} + +const std::vector& ExprLexer::getRuleNames() const { + return exprlexerLexerStaticData->ruleNames; +} + +const std::vector& ExprLexer::getChannelNames() const { + return exprlexerLexerStaticData->channelNames; +} + +const std::vector& ExprLexer::getModeNames() const { + return exprlexerLexerStaticData->modeNames; +} + +const dfa::Vocabulary& ExprLexer::getVocabulary() const { + return exprlexerLexerStaticData->vocabulary; +} + +antlr4::atn::SerializedATNView ExprLexer::getSerializedATN() const { + return exprlexerLexerStaticData->serializedATN; +} + +const atn::ATN& ExprLexer::getATN() const { + return *exprlexerLexerStaticData->atn; +} + + + + +void ExprLexer::initialize() { +#if ANTLR4_USE_THREAD_LOCAL_CACHE + exprlexerLexerInitialize(); +#else + ::antlr4::internal::call_once(exprlexerLexerOnceFlag, exprlexerLexerInitialize); +#endif +} diff --git a/src/libs/antares/antlr-interface/ExprLexer.h b/src/libs/antares/antlr-interface/ExprLexer.h new file mode 100644 index 0000000000..c7db2c5f77 --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprLexer.h @@ -0,0 +1,51 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + +#pragma once + + +#include "antlr4-runtime.h" + + + + +class ExprLexer : public antlr4::Lexer { +public: + enum { + T__0 = 1, T__1 = 2, T__2 = 3, T__3 = 4, T__4 = 5, T__5 = 6, T__6 = 7, + T__7 = 8, T__8 = 9, NUMBER = 10, TIME = 11, IDENTIFIER = 12, COMPARISON = 13, + ADDSUB = 14, MULDIV = 15, LBRACKET = 16, RBRACKET = 17, WS = 18 + }; + + explicit ExprLexer(antlr4::CharStream *input); + + ~ExprLexer() override; + + + std::string getGrammarFileName() const override; + + const std::vector& getRuleNames() const override; + + const std::vector& getChannelNames() const override; + + const std::vector& getModeNames() const override; + + const antlr4::dfa::Vocabulary& getVocabulary() const override; + + antlr4::atn::SerializedATNView getSerializedATN() const override; + + const antlr4::atn::ATN& getATN() const override; + + // By default the static state used to implement the lexer is lazily initialized during the first + // call to the constructor. You can call this function if you wish to initialize the static state + // ahead of time. + static void initialize(); + +private: + + // Individual action functions triggered by action() above. + + // Individual semantic predicate functions triggered by sempred() above. + +}; + diff --git a/src/libs/antares/antlr-interface/ExprLexer.interp b/src/libs/antares/antlr-interface/ExprLexer.interp new file mode 100644 index 0000000000..e98cab1e7c --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprLexer.interp @@ -0,0 +1,74 @@ +token literal names: +null +'+' +'-' +'/' +'*' +'.' +'(' +')' +',' +'..' +null +'t' +null +null +null +null +'[' +']' +null + +token symbolic names: +null +null +null +null +null +null +null +null +null +null +NUMBER +TIME +IDENTIFIER +COMPARISON +ADDSUB +MULDIV +LBRACKET +RBRACKET +WS + +rule names: +T__0 +T__1 +T__2 +T__3 +T__4 +T__5 +T__6 +T__7 +T__8 +DIGIT +CHAR +CHAR_OR_DIGIT +NUMBER +TIME +IDENTIFIER +COMPARISON +ADDSUB +MULDIV +LBRACKET +RBRACKET +WS + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 18, 111, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 1, 0, 1, 0, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 3, 11, 69, 8, 11, 1, 12, 4, 12, 72, 8, 12, 11, 12, 12, 12, 73, 1, 12, 1, 12, 4, 12, 78, 8, 12, 11, 12, 12, 12, 79, 3, 12, 82, 8, 12, 1, 13, 1, 13, 1, 14, 1, 14, 5, 14, 88, 8, 14, 10, 14, 12, 14, 91, 9, 14, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 3, 15, 98, 8, 15, 1, 16, 1, 16, 1, 17, 1, 17, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 1, 20, 1, 20, 1, 20, 0, 0, 21, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 0, 21, 0, 23, 0, 25, 10, 27, 11, 29, 12, 31, 13, 33, 14, 35, 15, 37, 16, 39, 17, 41, 18, 1, 0, 5, 1, 0, 48, 57, 3, 0, 65, 90, 95, 95, 97, 122, 2, 0, 43, 43, 45, 45, 2, 0, 42, 42, 47, 47, 3, 0, 9, 10, 13, 13, 32, 32, 114, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 25, 1, 0, 0, 0, 0, 27, 1, 0, 0, 0, 0, 29, 1, 0, 0, 0, 0, 31, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0, 0, 0, 37, 1, 0, 0, 0, 0, 39, 1, 0, 0, 0, 0, 41, 1, 0, 0, 0, 1, 43, 1, 0, 0, 0, 3, 45, 1, 0, 0, 0, 5, 47, 1, 0, 0, 0, 7, 49, 1, 0, 0, 0, 9, 51, 1, 0, 0, 0, 11, 53, 1, 0, 0, 0, 13, 55, 1, 0, 0, 0, 15, 57, 1, 0, 0, 0, 17, 59, 1, 0, 0, 0, 19, 62, 1, 0, 0, 0, 21, 64, 1, 0, 0, 0, 23, 68, 1, 0, 0, 0, 25, 71, 1, 0, 0, 0, 27, 83, 1, 0, 0, 0, 29, 85, 1, 0, 0, 0, 31, 97, 1, 0, 0, 0, 33, 99, 1, 0, 0, 0, 35, 101, 1, 0, 0, 0, 37, 103, 1, 0, 0, 0, 39, 105, 1, 0, 0, 0, 41, 107, 1, 0, 0, 0, 43, 44, 5, 43, 0, 0, 44, 2, 1, 0, 0, 0, 45, 46, 5, 45, 0, 0, 46, 4, 1, 0, 0, 0, 47, 48, 5, 47, 0, 0, 48, 6, 1, 0, 0, 0, 49, 50, 5, 42, 0, 0, 50, 8, 1, 0, 0, 0, 51, 52, 5, 46, 0, 0, 52, 10, 1, 0, 0, 0, 53, 54, 5, 40, 0, 0, 54, 12, 1, 0, 0, 0, 55, 56, 5, 41, 0, 0, 56, 14, 1, 0, 0, 0, 57, 58, 5, 44, 0, 0, 58, 16, 1, 0, 0, 0, 59, 60, 5, 46, 0, 0, 60, 61, 5, 46, 0, 0, 61, 18, 1, 0, 0, 0, 62, 63, 7, 0, 0, 0, 63, 20, 1, 0, 0, 0, 64, 65, 7, 1, 0, 0, 65, 22, 1, 0, 0, 0, 66, 69, 3, 21, 10, 0, 67, 69, 3, 19, 9, 0, 68, 66, 1, 0, 0, 0, 68, 67, 1, 0, 0, 0, 69, 24, 1, 0, 0, 0, 70, 72, 3, 19, 9, 0, 71, 70, 1, 0, 0, 0, 72, 73, 1, 0, 0, 0, 73, 71, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 81, 1, 0, 0, 0, 75, 77, 5, 46, 0, 0, 76, 78, 3, 19, 9, 0, 77, 76, 1, 0, 0, 0, 78, 79, 1, 0, 0, 0, 79, 77, 1, 0, 0, 0, 79, 80, 1, 0, 0, 0, 80, 82, 1, 0, 0, 0, 81, 75, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 26, 1, 0, 0, 0, 83, 84, 5, 116, 0, 0, 84, 28, 1, 0, 0, 0, 85, 89, 3, 21, 10, 0, 86, 88, 3, 23, 11, 0, 87, 86, 1, 0, 0, 0, 88, 91, 1, 0, 0, 0, 89, 87, 1, 0, 0, 0, 89, 90, 1, 0, 0, 0, 90, 30, 1, 0, 0, 0, 91, 89, 1, 0, 0, 0, 92, 98, 5, 61, 0, 0, 93, 94, 5, 62, 0, 0, 94, 98, 5, 61, 0, 0, 95, 96, 5, 60, 0, 0, 96, 98, 5, 61, 0, 0, 97, 92, 1, 0, 0, 0, 97, 93, 1, 0, 0, 0, 97, 95, 1, 0, 0, 0, 98, 32, 1, 0, 0, 0, 99, 100, 7, 2, 0, 0, 100, 34, 1, 0, 0, 0, 101, 102, 7, 3, 0, 0, 102, 36, 1, 0, 0, 0, 103, 104, 5, 91, 0, 0, 104, 38, 1, 0, 0, 0, 105, 106, 5, 93, 0, 0, 106, 40, 1, 0, 0, 0, 107, 108, 7, 4, 0, 0, 108, 109, 1, 0, 0, 0, 109, 110, 6, 20, 0, 0, 110, 42, 1, 0, 0, 0, 7, 0, 68, 73, 79, 81, 89, 97, 1, 6, 0, 0] \ No newline at end of file diff --git a/src/libs/antares/antlr-interface/ExprLexer.tokens b/src/libs/antares/antlr-interface/ExprLexer.tokens new file mode 100644 index 0000000000..29d96df5f3 --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprLexer.tokens @@ -0,0 +1,30 @@ +T__0=1 +T__1=2 +T__2=3 +T__3=4 +T__4=5 +T__5=6 +T__6=7 +T__7=8 +T__8=9 +NUMBER=10 +TIME=11 +IDENTIFIER=12 +COMPARISON=13 +ADDSUB=14 +MULDIV=15 +LBRACKET=16 +RBRACKET=17 +WS=18 +'+'=1 +'-'=2 +'/'=3 +'*'=4 +'.'=5 +'('=6 +')'=7 +','=8 +'..'=9 +'t'=11 +'['=16 +']'=17 diff --git a/src/libs/antares/antlr-interface/ExprParser.cpp b/src/libs/antares/antlr-interface/ExprParser.cpp new file mode 100644 index 0000000000..3c688d96d3 --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprParser.cpp @@ -0,0 +1,884 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + + +#include "ExprVisitor.h" + +#include "ExprParser.h" + + +using namespace antlrcpp; + +using namespace antlr4; + +namespace { + +struct ExprParserStaticData final { + ExprParserStaticData(std::vector ruleNames, + std::vector literalNames, + std::vector symbolicNames) + : ruleNames(std::move(ruleNames)), literalNames(std::move(literalNames)), + symbolicNames(std::move(symbolicNames)), + vocabulary(this->literalNames, this->symbolicNames) {} + + ExprParserStaticData(const ExprParserStaticData&) = delete; + ExprParserStaticData(ExprParserStaticData&&) = delete; + ExprParserStaticData& operator=(const ExprParserStaticData&) = delete; + ExprParserStaticData& operator=(ExprParserStaticData&&) = delete; + + std::vector decisionToDFA; + antlr4::atn::PredictionContextCache sharedContextCache; + const std::vector ruleNames; + const std::vector literalNames; + const std::vector symbolicNames; + const antlr4::dfa::Vocabulary vocabulary; + antlr4::atn::SerializedATNView serializedATN; + std::unique_ptr atn; +}; + +::antlr4::internal::OnceFlag exprParserOnceFlag; +#if ANTLR4_USE_THREAD_LOCAL_CACHE +static thread_local +#endif +ExprParserStaticData *exprParserStaticData = nullptr; + +void exprParserInitialize() { +#if ANTLR4_USE_THREAD_LOCAL_CACHE + if (exprParserStaticData != nullptr) { + return; + } +#else + assert(exprParserStaticData == nullptr); +#endif + auto staticData = std::make_unique( + std::vector{ + "fullexpr", "shift", "expr" + }, + std::vector{ + "", "'+'", "'-'", "'/'", "'*'", "'.'", "'('", "')'", "','", "'..'", + "", "'t'", "", "", "", "", "'['", "']'" + }, + std::vector{ + "", "", "", "", "", "", "", "", "", "", "NUMBER", "TIME", "IDENTIFIER", + "COMPARISON", "ADDSUB", "MULDIV", "LBRACKET", "RBRACKET", "WS" + } + ); + static const int32_t serializedATNSegment[] = { + 4,1,18,86,2,0,7,0,2,1,7,1,2,2,7,2,1,0,1,0,1,0,1,1,1,1,1,1,3,1,13,8,1, + 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1, + 2,1,2,1,2,1,2,1,2,5,2,37,8,2,10,2,12,2,40,9,2,1,2,1,2,1,2,1,2,1,2,1,2, + 1,2,5,2,49,8,2,10,2,12,2,52,9,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1, + 2,1,2,1,2,1,2,1,2,1,2,1,2,3,2,70,8,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2, + 1,2,5,2,81,8,2,10,2,12,2,84,9,2,1,2,0,1,4,3,0,2,4,0,2,1,0,1,2,1,0,3,4, + 97,0,6,1,0,0,0,2,9,1,0,0,0,4,69,1,0,0,0,6,7,3,4,2,0,7,8,5,0,0,1,8,1,1, + 0,0,0,9,12,5,11,0,0,10,11,7,0,0,0,11,13,3,4,2,0,12,10,1,0,0,0,12,13,1, + 0,0,0,13,3,1,0,0,0,14,15,6,2,-1,0,15,16,5,2,0,0,16,70,3,4,2,13,17,70, + 5,12,0,0,18,19,5,12,0,0,19,20,5,5,0,0,20,70,5,12,0,0,21,70,5,10,0,0,22, + 23,5,6,0,0,23,24,3,4,2,0,24,25,5,7,0,0,25,70,1,0,0,0,26,27,5,12,0,0,27, + 28,5,6,0,0,28,29,3,4,2,0,29,30,5,7,0,0,30,70,1,0,0,0,31,32,5,12,0,0,32, + 33,5,16,0,0,33,38,3,2,1,0,34,35,5,8,0,0,35,37,3,2,1,0,36,34,1,0,0,0,37, + 40,1,0,0,0,38,36,1,0,0,0,38,39,1,0,0,0,39,41,1,0,0,0,40,38,1,0,0,0,41, + 42,5,17,0,0,42,70,1,0,0,0,43,44,5,12,0,0,44,45,5,16,0,0,45,50,3,4,2,0, + 46,47,5,8,0,0,47,49,3,4,2,0,48,46,1,0,0,0,49,52,1,0,0,0,50,48,1,0,0,0, + 50,51,1,0,0,0,51,53,1,0,0,0,52,50,1,0,0,0,53,54,5,17,0,0,54,70,1,0,0, + 0,55,56,5,12,0,0,56,57,5,16,0,0,57,58,3,2,1,0,58,59,5,9,0,0,59,60,3,2, + 1,0,60,61,5,17,0,0,61,70,1,0,0,0,62,63,5,12,0,0,63,64,5,16,0,0,64,65, + 3,4,2,0,65,66,5,9,0,0,66,67,3,4,2,0,67,68,5,17,0,0,68,70,1,0,0,0,69,14, + 1,0,0,0,69,17,1,0,0,0,69,18,1,0,0,0,69,21,1,0,0,0,69,22,1,0,0,0,69,26, + 1,0,0,0,69,31,1,0,0,0,69,43,1,0,0,0,69,55,1,0,0,0,69,62,1,0,0,0,70,82, + 1,0,0,0,71,72,10,12,0,0,72,73,7,1,0,0,73,81,3,4,2,13,74,75,10,11,0,0, + 75,76,7,0,0,0,76,81,3,4,2,12,77,78,10,10,0,0,78,79,5,13,0,0,79,81,3,4, + 2,11,80,71,1,0,0,0,80,74,1,0,0,0,80,77,1,0,0,0,81,84,1,0,0,0,82,80,1, + 0,0,0,82,83,1,0,0,0,83,5,1,0,0,0,84,82,1,0,0,0,6,12,38,50,69,80,82 + }; + staticData->serializedATN = antlr4::atn::SerializedATNView(serializedATNSegment, sizeof(serializedATNSegment) / sizeof(serializedATNSegment[0])); + + antlr4::atn::ATNDeserializer deserializer; + staticData->atn = deserializer.deserialize(staticData->serializedATN); + + const size_t count = staticData->atn->getNumberOfDecisions(); + staticData->decisionToDFA.reserve(count); + for (size_t i = 0; i < count; i++) { + staticData->decisionToDFA.emplace_back(staticData->atn->getDecisionState(i), i); + } + exprParserStaticData = staticData.release(); +} + +} + +ExprParser::ExprParser(TokenStream *input) : ExprParser(input, antlr4::atn::ParserATNSimulatorOptions()) {} + +ExprParser::ExprParser(TokenStream *input, const antlr4::atn::ParserATNSimulatorOptions &options) : Parser(input) { + ExprParser::initialize(); + _interpreter = new atn::ParserATNSimulator(this, *exprParserStaticData->atn, exprParserStaticData->decisionToDFA, exprParserStaticData->sharedContextCache, options); +} + +ExprParser::~ExprParser() { + delete _interpreter; +} + +const atn::ATN& ExprParser::getATN() const { + return *exprParserStaticData->atn; +} + +std::string ExprParser::getGrammarFileName() const { + return "Expr.g4"; +} + +const std::vector& ExprParser::getRuleNames() const { + return exprParserStaticData->ruleNames; +} + +const dfa::Vocabulary& ExprParser::getVocabulary() const { + return exprParserStaticData->vocabulary; +} + +antlr4::atn::SerializedATNView ExprParser::getSerializedATN() const { + return exprParserStaticData->serializedATN; +} + + +//----------------- FullexprContext ------------------------------------------------------------------ + +ExprParser::FullexprContext::FullexprContext(ParserRuleContext *parent, size_t invokingState) + : ParserRuleContext(parent, invokingState) { +} + +ExprParser::ExprContext* ExprParser::FullexprContext::expr() { + return getRuleContext(0); +} + +tree::TerminalNode* ExprParser::FullexprContext::EOF() { + return getToken(ExprParser::EOF, 0); +} + + +size_t ExprParser::FullexprContext::getRuleIndex() const { + return ExprParser::RuleFullexpr; +} + + +std::any ExprParser::FullexprContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitFullexpr(this); + else + return visitor->visitChildren(this); +} + +ExprParser::FullexprContext* ExprParser::fullexpr() { + FullexprContext *_localctx = _tracker.createInstance(_ctx, getState()); + enterRule(_localctx, 0, ExprParser::RuleFullexpr); + +#if __cplusplus > 201703L + auto onExit = finally([=, this] { +#else + auto onExit = finally([=] { +#endif + exitRule(); + }); + try { + enterOuterAlt(_localctx, 1); + setState(6); + expr(0); + setState(7); + match(ExprParser::EOF); + + } + catch (RecognitionException &e) { + _errHandler->reportError(this, e); + _localctx->exception = std::current_exception(); + _errHandler->recover(this, _localctx->exception); + } + + return _localctx; +} + +//----------------- ShiftContext ------------------------------------------------------------------ + +ExprParser::ShiftContext::ShiftContext(ParserRuleContext *parent, size_t invokingState) + : ParserRuleContext(parent, invokingState) { +} + +tree::TerminalNode* ExprParser::ShiftContext::TIME() { + return getToken(ExprParser::TIME, 0); +} + +ExprParser::ExprContext* ExprParser::ShiftContext::expr() { + return getRuleContext(0); +} + + +size_t ExprParser::ShiftContext::getRuleIndex() const { + return ExprParser::RuleShift; +} + + +std::any ExprParser::ShiftContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitShift(this); + else + return visitor->visitChildren(this); +} + +ExprParser::ShiftContext* ExprParser::shift() { + ShiftContext *_localctx = _tracker.createInstance(_ctx, getState()); + enterRule(_localctx, 2, ExprParser::RuleShift); + size_t _la = 0; + +#if __cplusplus > 201703L + auto onExit = finally([=, this] { +#else + auto onExit = finally([=] { +#endif + exitRule(); + }); + try { + enterOuterAlt(_localctx, 1); + setState(9); + match(ExprParser::TIME); + setState(12); + _errHandler->sync(this); + + _la = _input->LA(1); + if (_la == ExprParser::T__0 + + || _la == ExprParser::T__1) { + setState(10); + antlrcpp::downCast(_localctx)->op = _input->LT(1); + _la = _input->LA(1); + if (!(_la == ExprParser::T__0 + + || _la == ExprParser::T__1)) { + antlrcpp::downCast(_localctx)->op = _errHandler->recoverInline(this); + } + else { + _errHandler->reportMatch(this); + consume(); + } + setState(11); + expr(0); + } + + } + catch (RecognitionException &e) { + _errHandler->reportError(this, e); + _localctx->exception = std::current_exception(); + _errHandler->recover(this, _localctx->exception); + } + + return _localctx; +} + +//----------------- ExprContext ------------------------------------------------------------------ + +ExprParser::ExprContext::ExprContext(ParserRuleContext *parent, size_t invokingState) + : ParserRuleContext(parent, invokingState) { +} + + +size_t ExprParser::ExprContext::getRuleIndex() const { + return ExprParser::RuleExpr; +} + +void ExprParser::ExprContext::copyFrom(ExprContext *ctx) { + ParserRuleContext::copyFrom(ctx); +} + +//----------------- IdentifierContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::IdentifierContext::IDENTIFIER() { + return getToken(ExprParser::IDENTIFIER, 0); +} + +ExprParser::IdentifierContext::IdentifierContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::IdentifierContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitIdentifier(this); + else + return visitor->visitChildren(this); +} +//----------------- NegationContext ------------------------------------------------------------------ + +ExprParser::ExprContext* ExprParser::NegationContext::expr() { + return getRuleContext(0); +} + +ExprParser::NegationContext::NegationContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::NegationContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitNegation(this); + else + return visitor->visitChildren(this); +} +//----------------- ExpressionContext ------------------------------------------------------------------ + +ExprParser::ExprContext* ExprParser::ExpressionContext::expr() { + return getRuleContext(0); +} + +ExprParser::ExpressionContext::ExpressionContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::ExpressionContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitExpression(this); + else + return visitor->visitChildren(this); +} +//----------------- ComparisonContext ------------------------------------------------------------------ + +std::vector ExprParser::ComparisonContext::expr() { + return getRuleContexts(); +} + +ExprParser::ExprContext* ExprParser::ComparisonContext::expr(size_t i) { + return getRuleContext(i); +} + +tree::TerminalNode* ExprParser::ComparisonContext::COMPARISON() { + return getToken(ExprParser::COMPARISON, 0); +} + +ExprParser::ComparisonContext::ComparisonContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::ComparisonContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitComparison(this); + else + return visitor->visitChildren(this); +} +//----------------- AddsubContext ------------------------------------------------------------------ + +std::vector ExprParser::AddsubContext::expr() { + return getRuleContexts(); +} + +ExprParser::ExprContext* ExprParser::AddsubContext::expr(size_t i) { + return getRuleContext(i); +} + +ExprParser::AddsubContext::AddsubContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::AddsubContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitAddsub(this); + else + return visitor->visitChildren(this); +} +//----------------- PortFieldContext ------------------------------------------------------------------ + +std::vector ExprParser::PortFieldContext::IDENTIFIER() { + return getTokens(ExprParser::IDENTIFIER); +} + +tree::TerminalNode* ExprParser::PortFieldContext::IDENTIFIER(size_t i) { + return getToken(ExprParser::IDENTIFIER, i); +} + +ExprParser::PortFieldContext::PortFieldContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::PortFieldContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitPortField(this); + else + return visitor->visitChildren(this); +} +//----------------- MuldivContext ------------------------------------------------------------------ + +std::vector ExprParser::MuldivContext::expr() { + return getRuleContexts(); +} + +ExprParser::ExprContext* ExprParser::MuldivContext::expr(size_t i) { + return getRuleContext(i); +} + +ExprParser::MuldivContext::MuldivContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::MuldivContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitMuldiv(this); + else + return visitor->visitChildren(this); +} +//----------------- NumberContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::NumberContext::NUMBER() { + return getToken(ExprParser::NUMBER, 0); +} + +ExprParser::NumberContext::NumberContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::NumberContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitNumber(this); + else + return visitor->visitChildren(this); +} +//----------------- TimeIndexContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::TimeIndexContext::IDENTIFIER() { + return getToken(ExprParser::IDENTIFIER, 0); +} + +tree::TerminalNode* ExprParser::TimeIndexContext::LBRACKET() { + return getToken(ExprParser::LBRACKET, 0); +} + +std::vector ExprParser::TimeIndexContext::expr() { + return getRuleContexts(); +} + +ExprParser::ExprContext* ExprParser::TimeIndexContext::expr(size_t i) { + return getRuleContext(i); +} + +tree::TerminalNode* ExprParser::TimeIndexContext::RBRACKET() { + return getToken(ExprParser::RBRACKET, 0); +} + +ExprParser::TimeIndexContext::TimeIndexContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::TimeIndexContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitTimeIndex(this); + else + return visitor->visitChildren(this); +} +//----------------- TimeShiftContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::TimeShiftContext::IDENTIFIER() { + return getToken(ExprParser::IDENTIFIER, 0); +} + +tree::TerminalNode* ExprParser::TimeShiftContext::LBRACKET() { + return getToken(ExprParser::LBRACKET, 0); +} + +std::vector ExprParser::TimeShiftContext::shift() { + return getRuleContexts(); +} + +ExprParser::ShiftContext* ExprParser::TimeShiftContext::shift(size_t i) { + return getRuleContext(i); +} + +tree::TerminalNode* ExprParser::TimeShiftContext::RBRACKET() { + return getToken(ExprParser::RBRACKET, 0); +} + +ExprParser::TimeShiftContext::TimeShiftContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::TimeShiftContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitTimeShift(this); + else + return visitor->visitChildren(this); +} +//----------------- FunctionContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::FunctionContext::IDENTIFIER() { + return getToken(ExprParser::IDENTIFIER, 0); +} + +ExprParser::ExprContext* ExprParser::FunctionContext::expr() { + return getRuleContext(0); +} + +ExprParser::FunctionContext::FunctionContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::FunctionContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitFunction(this); + else + return visitor->visitChildren(this); +} +//----------------- TimeShiftRangeContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::TimeShiftRangeContext::IDENTIFIER() { + return getToken(ExprParser::IDENTIFIER, 0); +} + +tree::TerminalNode* ExprParser::TimeShiftRangeContext::LBRACKET() { + return getToken(ExprParser::LBRACKET, 0); +} + +tree::TerminalNode* ExprParser::TimeShiftRangeContext::RBRACKET() { + return getToken(ExprParser::RBRACKET, 0); +} + +std::vector ExprParser::TimeShiftRangeContext::shift() { + return getRuleContexts(); +} + +ExprParser::ShiftContext* ExprParser::TimeShiftRangeContext::shift(size_t i) { + return getRuleContext(i); +} + +ExprParser::TimeShiftRangeContext::TimeShiftRangeContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::TimeShiftRangeContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitTimeShiftRange(this); + else + return visitor->visitChildren(this); +} +//----------------- TimeRangeContext ------------------------------------------------------------------ + +tree::TerminalNode* ExprParser::TimeRangeContext::IDENTIFIER() { + return getToken(ExprParser::IDENTIFIER, 0); +} + +tree::TerminalNode* ExprParser::TimeRangeContext::LBRACKET() { + return getToken(ExprParser::LBRACKET, 0); +} + +std::vector ExprParser::TimeRangeContext::expr() { + return getRuleContexts(); +} + +ExprParser::ExprContext* ExprParser::TimeRangeContext::expr(size_t i) { + return getRuleContext(i); +} + +tree::TerminalNode* ExprParser::TimeRangeContext::RBRACKET() { + return getToken(ExprParser::RBRACKET, 0); +} + +ExprParser::TimeRangeContext::TimeRangeContext(ExprContext *ctx) { copyFrom(ctx); } + + +std::any ExprParser::TimeRangeContext::accept(tree::ParseTreeVisitor *visitor) { + if (auto parserVisitor = dynamic_cast(visitor)) + return parserVisitor->visitTimeRange(this); + else + return visitor->visitChildren(this); +} + +ExprParser::ExprContext* ExprParser::expr() { + return expr(0); +} + +ExprParser::ExprContext* ExprParser::expr(int precedence) { + ParserRuleContext *parentContext = _ctx; + size_t parentState = getState(); + ExprParser::ExprContext *_localctx = _tracker.createInstance(_ctx, parentState); + ExprParser::ExprContext *previousContext = _localctx; + (void)previousContext; // Silence compiler, in case the context is not used by generated code. + size_t startState = 4; + enterRecursionRule(_localctx, 4, ExprParser::RuleExpr, precedence); + + size_t _la = 0; + +#if __cplusplus > 201703L + auto onExit = finally([=, this] { +#else + auto onExit = finally([=] { +#endif + unrollRecursionContexts(parentContext); + }); + try { + size_t alt; + enterOuterAlt(_localctx, 1); + setState(69); + _errHandler->sync(this); + switch (getInterpreter()->adaptivePredict(_input, 3, _ctx)) { + case 1: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + + setState(15); + match(ExprParser::T__1); + setState(16); + expr(13); + break; + } + + case 2: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(17); + match(ExprParser::IDENTIFIER); + break; + } + + case 3: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(18); + match(ExprParser::IDENTIFIER); + setState(19); + match(ExprParser::T__4); + setState(20); + match(ExprParser::IDENTIFIER); + break; + } + + case 4: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(21); + match(ExprParser::NUMBER); + break; + } + + case 5: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(22); + match(ExprParser::T__5); + setState(23); + expr(0); + setState(24); + match(ExprParser::T__6); + break; + } + + case 6: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(26); + match(ExprParser::IDENTIFIER); + setState(27); + match(ExprParser::T__5); + setState(28); + expr(0); + setState(29); + match(ExprParser::T__6); + break; + } + + case 7: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(31); + match(ExprParser::IDENTIFIER); + setState(32); + match(ExprParser::LBRACKET); + setState(33); + shift(); + setState(38); + _errHandler->sync(this); + _la = _input->LA(1); + while (_la == ExprParser::T__7) { + setState(34); + match(ExprParser::T__7); + setState(35); + shift(); + setState(40); + _errHandler->sync(this); + _la = _input->LA(1); + } + setState(41); + match(ExprParser::RBRACKET); + break; + } + + case 8: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(43); + match(ExprParser::IDENTIFIER); + setState(44); + match(ExprParser::LBRACKET); + setState(45); + expr(0); + setState(50); + _errHandler->sync(this); + _la = _input->LA(1); + while (_la == ExprParser::T__7) { + setState(46); + match(ExprParser::T__7); + setState(47); + expr(0); + setState(52); + _errHandler->sync(this); + _la = _input->LA(1); + } + setState(53); + match(ExprParser::RBRACKET); + break; + } + + case 9: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(55); + match(ExprParser::IDENTIFIER); + setState(56); + match(ExprParser::LBRACKET); + setState(57); + antlrcpp::downCast(_localctx)->shift1 = shift(); + setState(58); + match(ExprParser::T__8); + setState(59); + antlrcpp::downCast(_localctx)->shift2 = shift(); + setState(60); + match(ExprParser::RBRACKET); + break; + } + + case 10: { + _localctx = _tracker.createInstance(_localctx); + _ctx = _localctx; + previousContext = _localctx; + setState(62); + match(ExprParser::IDENTIFIER); + setState(63); + match(ExprParser::LBRACKET); + setState(64); + expr(0); + setState(65); + match(ExprParser::T__8); + setState(66); + expr(0); + setState(67); + match(ExprParser::RBRACKET); + break; + } + + default: + break; + } + _ctx->stop = _input->LT(-1); + setState(82); + _errHandler->sync(this); + alt = getInterpreter()->adaptivePredict(_input, 5, _ctx); + while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { + if (alt == 1) { + if (!_parseListeners.empty()) + triggerExitRuleEvent(); + previousContext = _localctx; + setState(80); + _errHandler->sync(this); + switch (getInterpreter()->adaptivePredict(_input, 4, _ctx)) { + case 1: { + auto newContext = _tracker.createInstance(_tracker.createInstance(parentContext, parentState)); + _localctx = newContext; + pushNewRecursionContext(newContext, startState, RuleExpr); + setState(71); + + if (!(precpred(_ctx, 12))) throw FailedPredicateException(this, "precpred(_ctx, 12)"); + setState(72); + antlrcpp::downCast(_localctx)->op = _input->LT(1); + _la = _input->LA(1); + if (!(_la == ExprParser::T__2 + + || _la == ExprParser::T__3)) { + antlrcpp::downCast(_localctx)->op = _errHandler->recoverInline(this); + } + else { + _errHandler->reportMatch(this); + consume(); + } + setState(73); + expr(13); + break; + } + + case 2: { + auto newContext = _tracker.createInstance(_tracker.createInstance(parentContext, parentState)); + _localctx = newContext; + pushNewRecursionContext(newContext, startState, RuleExpr); + setState(74); + + if (!(precpred(_ctx, 11))) throw FailedPredicateException(this, "precpred(_ctx, 11)"); + setState(75); + antlrcpp::downCast(_localctx)->op = _input->LT(1); + _la = _input->LA(1); + if (!(_la == ExprParser::T__0 + + || _la == ExprParser::T__1)) { + antlrcpp::downCast(_localctx)->op = _errHandler->recoverInline(this); + } + else { + _errHandler->reportMatch(this); + consume(); + } + setState(76); + expr(12); + break; + } + + case 3: { + auto newContext = _tracker.createInstance(_tracker.createInstance(parentContext, parentState)); + _localctx = newContext; + pushNewRecursionContext(newContext, startState, RuleExpr); + setState(77); + + if (!(precpred(_ctx, 10))) throw FailedPredicateException(this, "precpred(_ctx, 10)"); + setState(78); + match(ExprParser::COMPARISON); + setState(79); + expr(11); + break; + } + + default: + break; + } + } + setState(84); + _errHandler->sync(this); + alt = getInterpreter()->adaptivePredict(_input, 5, _ctx); + } + } + catch (RecognitionException &e) { + _errHandler->reportError(this, e); + _localctx->exception = std::current_exception(); + _errHandler->recover(this, _localctx->exception); + } + return _localctx; +} + +bool ExprParser::sempred(RuleContext *context, size_t ruleIndex, size_t predicateIndex) { + switch (ruleIndex) { + case 2: return exprSempred(antlrcpp::downCast(context), predicateIndex); + + default: + break; + } + return true; +} + +bool ExprParser::exprSempred(ExprContext *_localctx, size_t predicateIndex) { + switch (predicateIndex) { + case 0: return precpred(_ctx, 12); + case 1: return precpred(_ctx, 11); + case 2: return precpred(_ctx, 10); + + default: + break; + } + return true; +} + +void ExprParser::initialize() { +#if ANTLR4_USE_THREAD_LOCAL_CACHE + exprParserInitialize(); +#else + ::antlr4::internal::call_once(exprParserOnceFlag, exprParserInitialize); +#endif +} diff --git a/src/libs/antares/antlr-interface/ExprParser.h b/src/libs/antares/antlr-interface/ExprParser.h new file mode 100644 index 0000000000..aa1c8b6f09 --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprParser.h @@ -0,0 +1,244 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + +#pragma once + + +#include "antlr4-runtime.h" + + + + +class ExprParser : public antlr4::Parser { +public: + enum { + T__0 = 1, T__1 = 2, T__2 = 3, T__3 = 4, T__4 = 5, T__5 = 6, T__6 = 7, + T__7 = 8, T__8 = 9, NUMBER = 10, TIME = 11, IDENTIFIER = 12, COMPARISON = 13, + ADDSUB = 14, MULDIV = 15, LBRACKET = 16, RBRACKET = 17, WS = 18 + }; + + enum { + RuleFullexpr = 0, RuleShift = 1, RuleExpr = 2 + }; + + explicit ExprParser(antlr4::TokenStream *input); + + ExprParser(antlr4::TokenStream *input, const antlr4::atn::ParserATNSimulatorOptions &options); + + ~ExprParser() override; + + std::string getGrammarFileName() const override; + + const antlr4::atn::ATN& getATN() const override; + + const std::vector& getRuleNames() const override; + + const antlr4::dfa::Vocabulary& getVocabulary() const override; + + antlr4::atn::SerializedATNView getSerializedATN() const override; + + + class FullexprContext; + class ShiftContext; + class ExprContext; + + class FullexprContext : public antlr4::ParserRuleContext { + public: + FullexprContext(antlr4::ParserRuleContext *parent, size_t invokingState); + virtual size_t getRuleIndex() const override; + ExprContext *expr(); + antlr4::tree::TerminalNode *EOF(); + + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + + }; + + FullexprContext* fullexpr(); + + class ShiftContext : public antlr4::ParserRuleContext { + public: + antlr4::Token *op = nullptr; + ShiftContext(antlr4::ParserRuleContext *parent, size_t invokingState); + virtual size_t getRuleIndex() const override; + antlr4::tree::TerminalNode *TIME(); + ExprContext *expr(); + + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + + }; + + ShiftContext* shift(); + + class ExprContext : public antlr4::ParserRuleContext { + public: + ExprContext(antlr4::ParserRuleContext *parent, size_t invokingState); + + ExprContext() = default; + void copyFrom(ExprContext *context); + using antlr4::ParserRuleContext::copyFrom; + + virtual size_t getRuleIndex() const override; + + + }; + + class IdentifierContext : public ExprContext { + public: + IdentifierContext(ExprContext *ctx); + + antlr4::tree::TerminalNode *IDENTIFIER(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class NegationContext : public ExprContext { + public: + NegationContext(ExprContext *ctx); + + ExprContext *expr(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class ExpressionContext : public ExprContext { + public: + ExpressionContext(ExprContext *ctx); + + ExprContext *expr(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class ComparisonContext : public ExprContext { + public: + ComparisonContext(ExprContext *ctx); + + std::vector expr(); + ExprContext* expr(size_t i); + antlr4::tree::TerminalNode *COMPARISON(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class AddsubContext : public ExprContext { + public: + AddsubContext(ExprContext *ctx); + + antlr4::Token *op = nullptr; + std::vector expr(); + ExprContext* expr(size_t i); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class PortFieldContext : public ExprContext { + public: + PortFieldContext(ExprContext *ctx); + + std::vector IDENTIFIER(); + antlr4::tree::TerminalNode* IDENTIFIER(size_t i); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class MuldivContext : public ExprContext { + public: + MuldivContext(ExprContext *ctx); + + antlr4::Token *op = nullptr; + std::vector expr(); + ExprContext* expr(size_t i); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class NumberContext : public ExprContext { + public: + NumberContext(ExprContext *ctx); + + antlr4::tree::TerminalNode *NUMBER(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class TimeIndexContext : public ExprContext { + public: + TimeIndexContext(ExprContext *ctx); + + antlr4::tree::TerminalNode *IDENTIFIER(); + antlr4::tree::TerminalNode *LBRACKET(); + std::vector expr(); + ExprContext* expr(size_t i); + antlr4::tree::TerminalNode *RBRACKET(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class TimeShiftContext : public ExprContext { + public: + TimeShiftContext(ExprContext *ctx); + + antlr4::tree::TerminalNode *IDENTIFIER(); + antlr4::tree::TerminalNode *LBRACKET(); + std::vector shift(); + ShiftContext* shift(size_t i); + antlr4::tree::TerminalNode *RBRACKET(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class FunctionContext : public ExprContext { + public: + FunctionContext(ExprContext *ctx); + + antlr4::tree::TerminalNode *IDENTIFIER(); + ExprContext *expr(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class TimeShiftRangeContext : public ExprContext { + public: + TimeShiftRangeContext(ExprContext *ctx); + + ExprParser::ShiftContext *shift1 = nullptr; + ExprParser::ShiftContext *shift2 = nullptr; + antlr4::tree::TerminalNode *IDENTIFIER(); + antlr4::tree::TerminalNode *LBRACKET(); + antlr4::tree::TerminalNode *RBRACKET(); + std::vector shift(); + ShiftContext* shift(size_t i); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + class TimeRangeContext : public ExprContext { + public: + TimeRangeContext(ExprContext *ctx); + + antlr4::tree::TerminalNode *IDENTIFIER(); + antlr4::tree::TerminalNode *LBRACKET(); + std::vector expr(); + ExprContext* expr(size_t i); + antlr4::tree::TerminalNode *RBRACKET(); + + virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override; + }; + + ExprContext* expr(); + ExprContext* expr(int precedence); + + bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override; + + bool exprSempred(ExprContext *_localctx, size_t predicateIndex); + + // By default the static state used to implement the parser is lazily initialized during the first + // call to the constructor. You can call this function if you wish to initialize the static state + // ahead of time. + static void initialize(); + +private: +}; + diff --git a/src/libs/antares/antlr-interface/ExprVisitor.cpp b/src/libs/antares/antlr-interface/ExprVisitor.cpp new file mode 100644 index 0000000000..c214f0f76f --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprVisitor.cpp @@ -0,0 +1,7 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + + +#include "ExprVisitor.h" + + diff --git a/src/libs/antares/antlr-interface/ExprVisitor.h b/src/libs/antares/antlr-interface/ExprVisitor.h new file mode 100644 index 0000000000..c064d6d54a --- /dev/null +++ b/src/libs/antares/antlr-interface/ExprVisitor.h @@ -0,0 +1,54 @@ + +// Generated from Expr.g4 by ANTLR 4.13.1 + +#pragma once + + +#include "antlr4-runtime.h" +#include "ExprParser.h" + + + +/** + * This class defines an abstract visitor for a parse tree + * produced by ExprParser. + */ +class ExprVisitor : public antlr4::tree::AbstractParseTreeVisitor { +public: + + /** + * Visit parse trees produced by ExprParser. + */ + virtual std::any visitFullexpr(ExprParser::FullexprContext *context) = 0; + + virtual std::any visitShift(ExprParser::ShiftContext *context) = 0; + + virtual std::any visitIdentifier(ExprParser::IdentifierContext *context) = 0; + + virtual std::any visitNegation(ExprParser::NegationContext *context) = 0; + + virtual std::any visitExpression(ExprParser::ExpressionContext *context) = 0; + + virtual std::any visitComparison(ExprParser::ComparisonContext *context) = 0; + + virtual std::any visitAddsub(ExprParser::AddsubContext *context) = 0; + + virtual std::any visitPortField(ExprParser::PortFieldContext *context) = 0; + + virtual std::any visitMuldiv(ExprParser::MuldivContext *context) = 0; + + virtual std::any visitNumber(ExprParser::NumberContext *context) = 0; + + virtual std::any visitTimeIndex(ExprParser::TimeIndexContext *context) = 0; + + virtual std::any visitTimeShift(ExprParser::TimeShiftContext *context) = 0; + + virtual std::any visitFunction(ExprParser::FunctionContext *context) = 0; + + virtual std::any visitTimeShiftRange(ExprParser::TimeShiftRangeContext *context) = 0; + + virtual std::any visitTimeRange(ExprParser::TimeRangeContext *context) = 0; + + +}; + diff --git a/src/libs/antares/args/CMakeLists.txt b/src/libs/antares/args/CMakeLists.txt index eb9559c360..73b89f1137 100644 --- a/src/libs/antares/args/CMakeLists.txt +++ b/src/libs/antares/args/CMakeLists.txt @@ -13,10 +13,13 @@ add_library(Antares::args_helper ALIAS args_helper) target_link_libraries(args_helper PRIVATE - yuni-static-core - ) + yuni-static-core +) target_include_directories(args_helper PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + $ +) +install(DIRECTORY include/antares + DESTINATION "include" ) \ No newline at end of file diff --git a/src/libs/antares/args/args_to_utf8.cpp b/src/libs/antares/args/args_to_utf8.cpp index 7ac874e4d1..55a09f00ff 100644 --- a/src/libs/antares/args/args_to_utf8.cpp +++ b/src/libs/antares/args/args_to_utf8.cpp @@ -1,8 +1,33 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -#include #include "antares/args/args_to_utf8.h" +#include + #ifdef YUNI_OS_WINDOWS +// Turning off format because order of windows and shellapi matters, +// apparently +// clang-format off + #include #include #ifndef WIN32_LEAN_AND_MEAN @@ -10,9 +35,13 @@ #endif // WIN32_LEAN_AND_MEAN #include #include + +// clang-format on #endif // YUNI_OS_WINDOWS -IntoUTF8ArgsTranslator::IntoUTF8ArgsTranslator(int argc, char** argv) : argc_(argc), argv_(argv) +IntoUTF8ArgsTranslator::IntoUTF8ArgsTranslator(int argc, char** argv): + argc_(argc), + argv_(argv) { } @@ -24,10 +53,17 @@ std::pair IntoUTF8ArgsTranslator::convert() for (int i = 0; i != argc_; ++i) { const uint len = (uint)wcslen(wargv[i]); - const uint newLen = WideCharToMultiByte(CP_UTF8, 0, wargv[i], len, NULL, 0, NULL, NULL); + const uint newLen = WideCharToMultiByte(CP_UTF8, + 0, + wargv[i], + len, + nullptr, + 0, + nullptr, + nullptr); argv_[i] = (char*)malloc((newLen + 1) * sizeof(char)); memset(argv_[i], 0, (newLen + 1) * sizeof(char)); - WideCharToMultiByte(CP_UTF8, 0, wargv[i], len, argv_[i], newLen, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, wargv[i], len, argv_[i], newLen, nullptr, nullptr); argv_[i][newLen] = '\0'; } #endif @@ -38,7 +74,9 @@ IntoUTF8ArgsTranslator::~IntoUTF8ArgsTranslator() { #ifdef YUNI_OS_WINDOWS for (int i = 0; i != argc_; ++i) + { free(argv_[i]); + } free(argv_); #endif } diff --git a/src/libs/antares/args/include/antares/args/args_to_utf8.h b/src/libs/antares/args/include/antares/args/args_to_utf8.h index cb1c0085c6..8ca9a2e962 100644 --- a/src/libs/antares/args/include/antares/args/args_to_utf8.h +++ b/src/libs/antares/args/include/antares/args/args_to_utf8.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include diff --git a/src/libs/antares/array/CMakeLists.txt b/src/libs/antares/array/CMakeLists.txt index 5c212269d3..e2a7e48bf5 100644 --- a/src/libs/antares/array/CMakeLists.txt +++ b/src/libs/antares/array/CMakeLists.txt @@ -1,8 +1,8 @@ set(SRC_MATRIX - antares/array/matrix.h - antares/array/matrix.hxx + include/antares/array/matrix.h + include/antares/array/matrix.hxx matrix.cpp - ) +) source_group("array" FILES ${SRC_MATRIX}) add_library(array ${SRC_MATRIX}) @@ -15,9 +15,14 @@ target_link_libraries(array io #matrix.hxx jit #jit.hxx require logs Antares::memory - ) + Antares::study +) target_include_directories(array - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ) \ No newline at end of file + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/array/antares/array/matrix-to-buffer.h b/src/libs/antares/array/antares/array/matrix-to-buffer.h deleted file mode 100644 index acc6b4bf41..0000000000 --- a/src/libs/antares/array/antares/array/matrix-to-buffer.h +++ /dev/null @@ -1,120 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_H__ -#define __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_H__ - -#include - -namespace Antares -{ -template -class Matrix; -} - -namespace Antares -{ -// Forward declarations -const char* get_format(bool isDecimal, uint precision); -template -class I_mtx_to_buffer_dumper; - -class matrix_to_buffer_dumper_factory -{ -public: - matrix_to_buffer_dumper_factory(bool isDecimal, uint precision) : - any_decimal_(isDecimal and precision) - { - } - - ~matrix_to_buffer_dumper_factory() - { - } - - template - I_mtx_to_buffer_dumper* get_dumper(const Matrix* mtx, - std::string& data, - PredicateT& predicate); - -private: - bool any_decimal_; -}; - -template -class I_mtx_to_buffer_dumper -{ -public: - I_mtx_to_buffer_dumper(const Matrix* mtx, - std::string& data, - PredicateT& predicate) : - mtx_(mtx), buffer_(data), predicate_(predicate), format_(nullptr) - { - } - - void set_print_format(bool isDecimal, uint precision); - virtual void run() = 0; - ~I_mtx_to_buffer_dumper() - { - delete format_; - } - -protected: - const Matrix* mtx_; - std::string& buffer_; - PredicateT& predicate_; - const char* format_; -}; - -template -class one_column__dumper : public I_mtx_to_buffer_dumper -{ -public: - one_column__dumper(const Matrix* mtx, std::string& data, PredicateT& predicate) : - I_mtx_to_buffer_dumper(mtx, data, predicate) - { - } - void run() override; -}; - -template -class multiple_columns__dumper : public I_mtx_to_buffer_dumper -{ -public: - multiple_columns__dumper(const Matrix* mtx, - std::string& data, - PredicateT& predicate) : - I_mtx_to_buffer_dumper(mtx, data, predicate) - { - } - void run() override; -}; - -} // namespace Antares - -#include "matrix-to-buffer.hxx" - -#endif // __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_H__ \ No newline at end of file diff --git a/src/libs/antares/array/antares/array/matrix-to-buffer.hxx b/src/libs/antares/array/antares/array/matrix-to-buffer.hxx deleted file mode 100644 index bf434e9c2e..0000000000 --- a/src/libs/antares/array/antares/array/matrix-to-buffer.hxx +++ /dev/null @@ -1,186 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_HXX__ -#define __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_HXX__ - -#ifdef YUNI_OS_MSVC -#define ANTARES_MATRIX_SNPRINTF sprintf_s -#else -#define ANTARES_MATRIX_SNPRINTF snprintf -#endif - -namespace Antares -{ -namespace // anonymous -{ -template -struct MatrixScalar -{ - static inline void Append(std::string& file, T v, const char* const) - { - if (Yuni::Math::Zero(v)) - file.append(std::to_string(0)); - else - file.append(std::to_string(v)); - } -}; - -template<> -struct MatrixScalar -{ - static void Append(std::string& file, double v, const char* const format) - { - if (Yuni::Math::Zero(v)) - { - file += '0'; - } - else - { - char ConversionBuffer[128]; - const int sizePrintf - = (Yuni::Math::Zero(v - floor(v))) - ? ANTARES_MATRIX_SNPRINTF(ConversionBuffer, sizeof(ConversionBuffer), "%.0f", v) - : ANTARES_MATRIX_SNPRINTF(ConversionBuffer, sizeof(ConversionBuffer), format, v); - - if (sizePrintf >= 0 and sizePrintf < (int)(sizeof(ConversionBuffer))) - file += (const char*)ConversionBuffer; - else - file += "ERR"; - } - } -}; - -template<> -struct MatrixScalar -{ - static void Append(std::string& file, float v, const char* const format) - { - if (Yuni::Math::Zero(v)) - { - file += '0'; - } - else - { - char ConversionBuffer[128]; - const int sizePrintf - = (Yuni::Math::Zero(v - floor(v))) - ? ANTARES_MATRIX_SNPRINTF( - ConversionBuffer, sizeof(ConversionBuffer), "%.0f", (double)v) - : ANTARES_MATRIX_SNPRINTF( - ConversionBuffer, sizeof(ConversionBuffer), format, (double)v); - - if (sizePrintf >= 0 and sizePrintf < (int)(sizeof(ConversionBuffer))) - file += (const char*)ConversionBuffer; - else - file += "ERR"; - } - } -}; - -} // anonymous namespace - -template -I_mtx_to_buffer_dumper* matrix_to_buffer_dumper_factory::get_dumper( - const Matrix* mtx, - std::string& data, - PredicateT& predicate) -{ - if (mtx->width == 1) - return new one_column__dumper(mtx, data, predicate); - else - return new multiple_columns__dumper(mtx, data, predicate); -} - -template -void I_mtx_to_buffer_dumper::set_print_format(bool isDecimal, - uint precision) -{ - // Determining the string format to use according the given precision - format_ = "%.0f"; - - if (isDecimal and precision) - { - const char* const sfmt[] = { - "%.0f", - "%.1f", - "%.2f", - "%.3f", - "%.4f", - "%.5f", - "%.6f", - "%.7f", - "%.8f", - "%.9f", - "%.10f", - "%.11f", - "%.12f", - "%.13f", - "%.14f", - "%.15f", - "%.16f", - }; - assert(precision <= 16); - format_ = sfmt[precision]; - } -} - -template -void one_column__dumper::run() -{ - for (uint y = 0; y != (this->mtx_)->height; ++y) - { - MatrixScalar::Append( - this->buffer_, (ReadWriteT)this->predicate_((this->mtx_)->entry[0][y]), this->format_); - this->buffer_ += '\n'; - } -} - -template -void multiple_columns__dumper::run() -{ - for (uint y = 0; y < (this->mtx_)->height; ++y) - { - MatrixScalar::Append( - this->buffer_, (ReadWriteT)this->predicate_((this->mtx_)->entry[0][y]), this->format_); - for (uint x = 1; x < (this->mtx_)->width; ++x) - { - this->buffer_ += '\t'; - MatrixScalar::Append( - this->buffer_, - (ReadWriteT)this->predicate_((this->mtx_)->entry[x][y]), - this->format_); - } - this->buffer_ += '\n'; - } -} - -} // namespace Antares - -#undef ANTARES_MATRIX_SNPRINTF - -#endif // __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_HXX__ diff --git a/src/libs/antares/array/include/antares/array/matrix-to-buffer.h b/src/libs/antares/array/include/antares/array/matrix-to-buffer.h new file mode 100644 index 0000000000..54fd58812c --- /dev/null +++ b/src/libs/antares/array/include/antares/array/matrix-to-buffer.h @@ -0,0 +1,116 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_H__ +#define __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_H__ + +#include + +namespace Antares +{ +template +class Matrix; +} + +namespace Antares +{ +// Forward declarations +const char* get_format(bool isDecimal, uint precision); +template +class I_mtx_to_buffer_dumper; + +class matrix_to_buffer_dumper_factory +{ +public: + matrix_to_buffer_dumper_factory() + { + } + + ~matrix_to_buffer_dumper_factory() + { + } + + template + I_mtx_to_buffer_dumper* get_dumper(const Matrix* mtx, + std::string& data, + PredicateT& predicate); +}; + +template +class I_mtx_to_buffer_dumper +{ +public: + I_mtx_to_buffer_dumper(const Matrix* mtx, + std::string& data, + PredicateT& predicate): + mtx_(mtx), + buffer_(data), + predicate_(predicate), + format_(nullptr) + { + } + + void set_print_format(bool isDecimal, uint precision); + virtual void run() = 0; + + ~I_mtx_to_buffer_dumper() + { + delete format_; + } + +protected: + const Matrix* mtx_; + std::string& buffer_; + PredicateT& predicate_; + const char* format_; +}; + +template +class one_column__dumper: public I_mtx_to_buffer_dumper +{ +public: + one_column__dumper(const Matrix* mtx, std::string& data, PredicateT& predicate): + I_mtx_to_buffer_dumper(mtx, data, predicate) + { + } + + void run() override; +}; + +template +class multiple_columns__dumper: public I_mtx_to_buffer_dumper +{ +public: + multiple_columns__dumper(const Matrix* mtx, + std::string& data, + PredicateT& predicate): + I_mtx_to_buffer_dumper(mtx, data, predicate) + { + } + + void run() override; +}; + +} // namespace Antares + +#include "matrix-to-buffer.hxx" + +#endif // __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_H__ diff --git a/src/libs/antares/array/include/antares/array/matrix-to-buffer.hxx b/src/libs/antares/array/include/antares/array/matrix-to-buffer.hxx new file mode 100644 index 0000000000..085cfaa6bc --- /dev/null +++ b/src/libs/antares/array/include/antares/array/matrix-to-buffer.hxx @@ -0,0 +1,208 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_HXX__ +#define __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_HXX__ + +#ifdef YUNI_OS_MSVC +#define ANTARES_MATRIX_SNPRINTF sprintf_s +#else +#define ANTARES_MATRIX_SNPRINTF snprintf +#endif + +#include + +namespace Antares +{ +namespace // anonymous +{ +template +struct MatrixScalar +{ + static inline void Append(std::string& file, T v, const char* const) + { + if (Utils::isZero(v)) + { + file.append(std::to_string(0)); + } + else + { + file.append(std::to_string(v)); + } + } +}; + +template<> +struct MatrixScalar +{ + static void Append(std::string& file, double v, const char* const format) + { + if (Utils::isZero(v)) + { + file += '0'; + } + else + { + char ConversionBuffer[128]; + const int sizePrintf = Utils::isZero(v - floor(v)) + ? ANTARES_MATRIX_SNPRINTF(ConversionBuffer, + sizeof(ConversionBuffer), + "%.0f", + v) + : ANTARES_MATRIX_SNPRINTF(ConversionBuffer, + sizeof(ConversionBuffer), + format, + v); + + if (sizePrintf >= 0 and sizePrintf < (int)(sizeof(ConversionBuffer))) + { + file += (const char*)ConversionBuffer; + } + else + { + file += "ERR"; + } + } + } +}; + +template<> +struct MatrixScalar +{ + static void Append(std::string& file, float v, const char* const format) + { + if (Utils::isZero(v)) + { + file += '0'; + } + else + { + char ConversionBuffer[128]; + const int sizePrintf = Utils::isZero(v - floor(v)) + ? ANTARES_MATRIX_SNPRINTF(ConversionBuffer, + sizeof(ConversionBuffer), + "%.0f", + (double)v) + : ANTARES_MATRIX_SNPRINTF(ConversionBuffer, + sizeof(ConversionBuffer), + format, + (double)v); + + if (sizePrintf >= 0 and sizePrintf < (int)(sizeof(ConversionBuffer))) + { + file += (const char*)ConversionBuffer; + } + else + { + file += "ERR"; + } + } + } +}; + +} // anonymous namespace + +template +I_mtx_to_buffer_dumper* matrix_to_buffer_dumper_factory::get_dumper( + const Matrix* mtx, + std::string& data, + PredicateT& predicate) +{ + if (mtx->width == 1) + { + return new one_column__dumper(mtx, data, predicate); + } + else + { + return new multiple_columns__dumper(mtx, data, predicate); + } +} + +template +void I_mtx_to_buffer_dumper::set_print_format(bool isDecimal, + uint precision) +{ + // Determining the string format to use according the given precision + format_ = "%.0f"; + + if (isDecimal and precision) + { + const char* const sfmt[] = { + "%.0f", + "%.1f", + "%.2f", + "%.3f", + "%.4f", + "%.5f", + "%.6f", + "%.7f", + "%.8f", + "%.9f", + "%.10f", + "%.11f", + "%.12f", + "%.13f", + "%.14f", + "%.15f", + "%.16f", + }; + assert(precision <= 16); + format_ = sfmt[precision]; + } +} + +template +void one_column__dumper::run() +{ + for (uint y = 0; y != (this->mtx_)->height; ++y) + { + MatrixScalar::Append(this->buffer_, + (ReadWriteT)this->predicate_((this->mtx_)->entry[0][y]), + this->format_); + this->buffer_ += '\n'; + } +} + +template +void multiple_columns__dumper::run() +{ + for (uint y = 0; y < (this->mtx_)->height; ++y) + { + MatrixScalar::Append(this->buffer_, + (ReadWriteT)this->predicate_((this->mtx_)->entry[0][y]), + this->format_); + for (uint x = 1; x < (this->mtx_)->width; ++x) + { + this->buffer_ += '\t'; + MatrixScalar::Append(this->buffer_, + (ReadWriteT)this->predicate_( + (this->mtx_)->entry[x][y]), + this->format_); + } + this->buffer_ += '\n'; + } +} + +} // namespace Antares + +#undef ANTARES_MATRIX_SNPRINTF + +#endif // __ANTARES_LIBS_ARRAY_MATRIX_TO_BUFFER_SENDER_HXX__ diff --git a/src/libs/antares/array/antares/array/matrix.h b/src/libs/antares/array/include/antares/array/matrix.h similarity index 93% rename from src/libs/antares/array/antares/array/matrix.h rename to src/libs/antares/array/include/antares/array/matrix.h index 0ad94e9081..48eb27dd6f 100644 --- a/src/libs/antares/array/antares/array/matrix.h +++ b/src/libs/antares/array/include/antares/array/matrix.h @@ -1,40 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_ARRAY_MATRIX_H__ #define __ANTARES_LIBS_ARRAY_MATRIX_H__ -#include -#include #include -#include "../jit.h" -#include "../constants.h" #include + +#include +#include + #include -#include "../study/fwd.h" +#include "antares/antares/antares.h" +#include "antares/jit/jit.h" +#include "antares/study/fwd.h" namespace Antares { @@ -222,6 +218,7 @@ class Matrix bool print_dimensions, PredicateT& predicate, bool saveEvenIfAllZero = false) const; + //@} virtual Yuni::IO::Error loadFromFileToBuffer(BufferType& buffer, @@ -342,15 +339,6 @@ class Matrix template void pasteToColumn(uint x, const U* data); - /*! - ** \brief Copy values into a given column in the matrix - ** - ** \param x The column index (zero-based) - ** \param data The data to copy - */ - template - void pasteToColumn(uint x, const Antares::Memory::Array& data); - /*! ** \brief Set a entire column with a given value ** diff --git a/src/libs/antares/array/antares/array/matrix.hxx b/src/libs/antares/array/include/antares/array/matrix.hxx similarity index 91% rename from src/libs/antares/array/antares/array/matrix.hxx rename to src/libs/antares/array/include/antares/array/matrix.hxx index 9e2420624f..c95db1bd93 100644 --- a/src/libs/antares/array/antares/array/matrix.hxx +++ b/src/libs/antares/array/include/antares/array/matrix.hxx @@ -1,39 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_ARRAY_MATRIX_HXX__ #define __ANTARES_LIBS_ARRAY_MATRIX_HXX__ +#include +#include +#include + #include #include -#include -#include -#include -#include + #include +#include + #include "matrix-to-buffer.h" #define ANTARES_MATRIX_CSV_COMMA "\t;," @@ -51,6 +48,7 @@ public: { data = T(); } + template inline static void Copy(T& data, const U& value) { @@ -76,6 +74,7 @@ public: { data.clear(); } + template inline static void Copy(StringT& data, const U& value) { @@ -144,6 +143,7 @@ public: { direct = 1, }; + using StringT = Yuni::CString; public: @@ -154,13 +154,25 @@ public: } }; +template +Yuni::CString trunc(Yuni::CString& str) +{ + return str; +} + +template +static T trunc(T& in) +{ + return static_cast(std::trunc(in)); +} + template class MatrixRound final { public: static T Value(P value) { - return static_cast(Yuni::Math::Trunc(value)); + return static_cast(trunc(value)); } }; @@ -187,12 +199,19 @@ public: } // anonymous namespace template -inline Matrix::Matrix() : width(0), height(0), entry(nullptr), jit(nullptr) +inline Matrix::Matrix(): + width(0), + height(0), + entry(nullptr), + jit(nullptr) { } template -Matrix::Matrix(uint w, uint h) : width(w), height(h), jit(nullptr) +Matrix::Matrix(uint w, uint h): + width(w), + height(h), + jit(nullptr) { if (0 == width or 0 == height) { @@ -204,13 +223,17 @@ Matrix::Matrix(uint w, uint h) : width(w), height(h), jit(nullptr entry[w] = nullptr; for (uint i = 0; i != w; ++i) + { Antares::Memory::Allocate(entry[i], h); + } } } template -Matrix::Matrix(const Matrix& rhs) : - width(rhs.width), height(rhs.height), jit(nullptr) +Matrix::Matrix(const Matrix& rhs): + width(rhs.width), + height(rhs.height), + jit(nullptr) { if (0 == width or 0 == height) { @@ -240,8 +263,11 @@ Matrix::Matrix(Matrix&& rhs) noexcept template template -Matrix::Matrix(const Matrix& rhs) : - width(0), height(0), entry(nullptr), jit(nullptr) +Matrix::Matrix(const Matrix& rhs): + width(0), + height(0), + entry(nullptr), + jit(nullptr) { copyFrom(rhs); } @@ -256,7 +282,9 @@ Matrix::~Matrix() if (entry) { for (uint i = 0; i != width; ++i) + { Antares::Memory::Release(entry[i]); + } delete[] entry; } } @@ -283,7 +311,9 @@ void Matrix::averageTimeseries(bool roundValues) { ColumnType& column = entry[i]; for (uint j = 0; j != height; ++j) + { first[j] += column[j]; + } } // average @@ -293,18 +323,22 @@ void Matrix::averageTimeseries(bool roundValues) for (uint j = 0; j != height; ++j) { const double d = first[j] * coeff; - first[j] = Yuni::Math::Round(d); + first[j] = std::round(d); } } else { for (uint j = 0; j != height; ++j) + { first[j] *= coeff; + } } // Release all timeseries no longer needed for (uint i = 1; i != width; ++i) + { Antares::Memory::Release(entry[i]); + } // reset the width to 1 width = 1; } @@ -318,7 +352,9 @@ void Matrix::fill(const T& v) ColumnType& column = entry[i]; for (uint j = 0; j != height; ++j) + { column[j] = v; + } } } @@ -370,8 +406,10 @@ bool Matrix::internalLoadJITData(const AnyString& filename, template inline bool Matrix::loadFromCSVFile(const AnyString& filename) { - return loadFromCSVFile( - filename, 1, 0, optImmediate | optNoWarnIfEmpty | optNeverFails | optQuiet); + return loadFromCSVFile(filename, + 1, + 0, + optImmediate | optNoWarnIfEmpty | optNeverFails | optQuiet); } template @@ -442,30 +480,9 @@ void Matrix::pasteToColumn(uint x, const U* data) { // ...otherwise we have to copy each item by hand in any cases for (uint y = 0; y != height; ++y) + { column[y] = (T)data[y]; - } - - markAsModified(); -} - -template -template -void Matrix::pasteToColumn(uint x, const Antares::Memory::Array& data) -{ - assert(x < width and "Invalid column index (bigger than `this->width`)"); - ColumnType& column = entry[x]; - - // if the two types are strictly equal, we can perform some major - // optimisations - if (Yuni::Static::Type::StrictlyEqual::Yes) - { - (void)::memcpy(column, data, sizeof(T) * height); - } - else - { - // ...otherwise we have to copy each item by hand in any cases - for (uint y = 0; y != height; ++y) - column[y] = (T)data[y]; + } } markAsModified(); @@ -478,7 +495,9 @@ void Matrix::fillColumn(uint x, const T& value) ColumnType& column = entry[x]; for (uint y = 0; y != height; ++y) + { column[y] = value; + } markAsModified(); } @@ -498,7 +517,9 @@ template inline void Matrix::markAsModified() const { if (jit) + { jit->markAsModified(); + } } template @@ -526,7 +547,9 @@ void Matrix::clear() if (entry) { for (uint i = 0; i != width; ++i) + { Antares::Memory::Release(entry[i]); + } delete[] entry; entry = nullptr; } @@ -562,7 +585,9 @@ void Matrix::resize(uint w, uint h, bool fixedSize) if (entry) { for (uint i = 0; i != width; ++i) + { Antares::Memory::Release(entry[i]); + } delete[] entry; } if (!w and !h) @@ -591,14 +616,18 @@ void Matrix::resize(uint w, uint h, bool fixedSize) // JIT Update if (JIT::enabled and not jit and fixedSize) + { jit = JIT::Reset(jit); + } if (jit and w != 0 and h != 0) { jit->minWidth = w; jit->maxHeight = h; if (fixedSize) + { jit->options = jit->options | optFixedSize; + } } markAsModified(); } @@ -613,11 +642,15 @@ static inline bool DetectEncoding(const AnyString& filename, const AnyString& da if ((unsigned char)data[0] == 0xFE and ((unsigned char)data[1]) == 0xFF) { if (data.size() > 3 and !data[2] and !data[3]) + { logs.error() << '`' << filename << "`: UTF-32 Little Endian encoding detected. ASCII/UTF-8 required."; + } else + { logs.error() << '`' << filename << "`: UTF-16 Big Endian encoding detected. ASCII/UTF-8 required."; + } return false; } // UTF-16 Little endian @@ -691,9 +724,13 @@ bool Matrix::loadFromBuffer(const AnyString& filename, assert(not data.empty()); maxHeight = data.countChar('\n'); if (data.last() == '\n') + { --maxHeight; + } else + { ++maxHeight; + } } // gp : dead code - can never be reached // The first occurence of the carriage return @@ -714,10 +751,14 @@ bool Matrix::loadFromBuffer(const AnyString& filename, if (c == '\r' or c == '\t' or c == ' ') { if (!(--max)) + { break; + } } else + { break; + } } while (true); } @@ -734,13 +775,17 @@ bool Matrix::loadFromBuffer(const AnyString& filename, if (x < 1) { if (!(options & optQuiet)) + { logs.warning() << '`' << filename << "`: Invalid header"; + } x = 1; } if (y < 1) { if (!(options & optQuiet)) + { logs.warning() << '`' << filename << "`: Invalid header"; + } y = maxHeight; } maxHeight = y; @@ -766,7 +811,9 @@ bool Matrix::loadFromBuffer(const AnyString& filename, if (!x) { if (not(options & optQuiet) and not(options & optNoWarnIfEmpty)) + { logs.warning() << "`" << filename << "`: Invalid format: The file seems empty"; + } zero(); return false; } @@ -829,7 +876,9 @@ bool Matrix::loadFromBuffer(const AnyString& filename, break; } if (data[newOffset] != '\r') + { ++newWidth; + } ++newOffset; } resizeWithoutDataLost(newWidth, height); @@ -845,7 +894,9 @@ bool Matrix::loadFromBuffer(const AnyString& filename, << '`' << filename << "`: Invalid format: Too many entry for the row " << y << " (offset: " << (uint)pos << "byte)"; if (!(--errorCount)) + { logs.warning() << " ... (skipped)"; + } } break; } @@ -877,13 +928,17 @@ bool Matrix::loadFromBuffer(const AnyString& filename, << ",y:" << y << ", offset: " << (uint)pos << "byte), text: `" << converter << " read:" << entry[x][y] << '`'; if (not(--errorCount)) + { logs.warning() << " ... (skipped)"; + } } MatrixData::Init(entry[x][y]); } else + { entry[x][y] = MatrixRound::Value( static_cast(fallback)); + } } else { @@ -924,7 +979,9 @@ bool Matrix::loadFromBuffer(const AnyString& filename, else { if (separator == '\n') + { break; + } } } @@ -940,7 +997,9 @@ bool Matrix::loadFromBuffer(const AnyString& filename, << filename << ": at line " << (y + 1) << ", not enough columns (expected " << width << ", got " << x << ')'; if (not(--errorCount)) + { logs.warning() << " ... (skipped)"; + } } } while (x < width) // Init for missing entry @@ -968,7 +1027,9 @@ bool Matrix::loadFromBuffer(const AnyString& filename, while (y < height) { for (x = 0; x < width; ++x) + { MatrixData::Init(entry[x][y]); + } ++y; } } @@ -983,27 +1044,31 @@ bool Matrix::internalLoadCSVFile(const AnyString& filename, uint options, BufferType* buffer) { - using namespace Yuni; - // Status bool result = false; const bool hasOwnership = (NULL == buffer); if (not buffer) + { buffer = new BufferType(); + } switch (loadFromFileToBuffer(*buffer, filename)) { - case IO::errNone: + case Yuni::IO::errNone: { // Empty files if (buffer->empty()) { if (maxHeight and minWidth) + { reset((minWidth != 0 ? minWidth : 1), maxHeight); // gp : minWidth always != 0 here ==> Refactoring + } else + { clear(); + } result = true; break; } @@ -1014,24 +1079,32 @@ bool Matrix::internalLoadCSVFile(const AnyString& filename, // Adding a final \n to make sure we have a line return at the end of the file *buffer += '\n'; // Load the data - result = loadFromBuffer( - filename, *buffer, minWidth, maxHeight, (options & optFixedSize), options); + result = loadFromBuffer(filename, + *buffer, + minWidth, + maxHeight, + (options & optFixedSize), + options); // Mark as modified if (0 != (options & optMarkAsModified)) { if (jit) + { jit->markAsModified(); + } } break; } - case IO::errNotFound: + case Yuni::IO::errNotFound: { if (not(options & optQuiet)) + { logs.error() << "I/O Error: not found: '" << filename << "'"; + } break; } - case IO::errMemoryLimit: + case Yuni::IO::errMemoryLimit: { if (not(options & optQuiet)) { @@ -1043,17 +1116,23 @@ bool Matrix::internalLoadCSVFile(const AnyString& filename, default: { if (not(options & optQuiet)) + { logs.error() << "I/O Error: failed to load '" << filename << "'"; + } } } if (hasOwnership) + { delete buffer; + } // The matrix may not be loaded but we have to initialize it to avoid // further SegV if the application decides to continue anyway. if (not result) + { reset(minWidth, maxHeight); + } // Post-processing when the Load-on-Demand is enabled if (JIT::enabled and not jit and (0 != (options & optFixedSize))) @@ -1090,8 +1169,10 @@ bool Matrix::containsOnlyZero() const auto& column = entry[x]; for (uint y = 0; y != height; ++y) { - if (not Yuni::Math::Zero((T)column[y])) + if (!Utils::isZero((T)column[y])) + { return false; + } } } } @@ -1109,8 +1190,10 @@ bool Matrix::containsOnlyZero(PredicateT& predicate) const auto& column = entry[x]; for (uint y = 0; y != height; ++y) { - if (not Yuni::Math::Zero((T)predicate(column[y]))) + if (!Utils::isZero((T)predicate(column[y]))) + { return false; + } } } } @@ -1126,6 +1209,7 @@ void Matrix::saveToBuffer(std::string& data, bool saveEvenIfAllZero) const { using namespace Yuni; + enum { // Get if the read/write type is a decimal type (e.g. double/float/long double) @@ -1133,10 +1217,12 @@ void Matrix::saveToBuffer(std::string& data, }; if (not print_dimensions and (containsOnlyZero(predicate) and not saveEvenIfAllZero)) + { // Does nothing if the matrix only contains zero return; + } - matrix_to_buffer_dumper_factory mtx_to_buffer_dumper_factory(isDecimal, precision); + matrix_to_buffer_dumper_factory mtx_to_buffer_dumper_factory; I_mtx_to_buffer_dumper* mtx_to_buffer_dpr = mtx_to_buffer_dumper_factory.get_dumper(this, data, predicate); @@ -1148,7 +1234,9 @@ void Matrix::saveToBuffer(std::string& data, data.reserve(width * height * 6); if (print_dimensions) + { data += "size:" + std::to_string(width) + 'x' + std::to_string(height) + '\n'; + } mtx_to_buffer_dpr->run(); } @@ -1200,7 +1288,9 @@ bool Matrix::internalSaveCSVFile(const AnyString& filename, } if (jit_mgr.jit_activated() && jit_mgr.do_we_force_matrix_load_from_disk()) + { jit_mgr.load_matrix(this); + } #ifndef NDEBUG // Attempt to open the file, and to write data @@ -1210,7 +1300,9 @@ bool Matrix::internalSaveCSVFile(const AnyString& filename, Yuni::IO::File::Stream file; if (not openFile(file, filename)) + { return false; + } if (height and width) { @@ -1245,7 +1337,9 @@ void Matrix::resizeWithoutDataLost(uint x, uint y, const T& defVa if (x <= width and y <= height) // shrinking { for (uint i = x; i < width; ++i) + { Antares::Memory::Release(entry[i]); + } // Update the matrix size width = x; @@ -1266,7 +1360,9 @@ void Matrix::resizeWithoutDataLost(uint x, uint y, const T& defVa (void)::memcpy(column, copy.entry[i], sizeof(T) * minH); for (uint j = minH; j < y; ++j) + { column[j] = defVal; + } } if (defVal == T()) @@ -1295,8 +1391,10 @@ bool Matrix::loadAllJITData() const if (jit and not JIT::IsReady(jit)) { return (const_cast*>(this)) - ->loadFromCSVFile( - jit->sourceFilename, jit->minWidth, jit->maxHeight, jit->options | optImmediate); + ->loadFromCSVFile(jit->sourceFilename, + jit->minWidth, + jit->maxHeight, + jit->options | optImmediate); } return true; } @@ -1305,20 +1403,26 @@ template template void Matrix::multiplyAllEntriesBy(const U& c) { - if (entry) + if (!entry) { - if (!Yuni::Math::Zero(c)) + return; + } + + if (!Utils::isZero(c)) + { + for (uint x = 0; x != width; ++x) { - for (uint x = 0; x != width; ++x) - { - ColumnType& column = entry[x]; + ColumnType& column = entry[x]; - for (uint y = 0; y != height; ++y) - column[y] *= (T)c; + for (uint y = 0; y != height; ++y) + { + column[y] *= (T)c; } } - else - zero(); + } + else + { + zero(); } } @@ -1329,7 +1433,9 @@ void Matrix::multiplyColumnBy(uint x, const U& c) assert(x < width and "Invalid column index (bigger than `this->width`)"); ColumnType& column = entry[x]; for (uint y = 0; y != height; ++y) + { column[y] *= (T)c; + } } template @@ -1340,7 +1446,9 @@ void Matrix::divideColumnBy(uint x, const U& c) assert(c != (T)0 && "Dividing by zero"); ColumnType& column = entry[x]; for (uint y = 0; y != height; ++y) + { column[y] /= (T)c; + } } template @@ -1350,7 +1458,9 @@ void Matrix::roundAllEntries() { ColumnType& col = entry[x]; for (uint y = 0; y != height; ++y) - col[y] = (T)Yuni::Math::Round(col[y]); + { + col[y] = (T)std::round(col[y]); + } } } @@ -1361,7 +1471,9 @@ void Matrix::makeAllEntriesAbsolute() { ColumnType& col = entry[x]; for (uint y = 0; y != height; ++y) - col[y] = Yuni::Math::Abs(col[y]); + { + col[y] = std::abs(col[y]); + } } } @@ -1375,7 +1487,9 @@ T Matrix::findLowerBound() const for (uint y = 0; y != height; ++y) { if (col[y] < r) + { r = col[y]; + } } } return (T)r; @@ -1391,7 +1505,9 @@ T Matrix::findUpperBound() const for (uint y = 0; y != height; ++y) { if (col[y] > r) + { r = col[y]; + } } } return (T)r; @@ -1428,7 +1544,9 @@ void Matrix::copyFrom(const Matrix& rhs) { // ...otherwise we have to copy each item by hand in any cases for (uint y = 0; y != height; ++y) + { column[y] = (T)src[y]; + } } } } @@ -1455,7 +1573,9 @@ template inline void Matrix::copyFrom(const Matrix* rhs) { if (rhs) + { copyFrom(*rhs); + } } template @@ -1520,9 +1640,13 @@ void Matrix::print() const for (uint x = 0; x != width; ++x) { if (x) + { std::cout << ",\t"; + } else + { std::cout << '\t'; + } std::cout << entry[x][y]; } std::cout << "]\n"; @@ -1557,7 +1681,9 @@ bool MatrixTestForAtLeastOnePositiveValue(const Matrix& m) for (y = 0; y < m.height; ++y) { if (col[y] > T1(0)) + { return true; + } } } } @@ -1581,7 +1707,9 @@ template void Matrix::reverseRows(uint column, uint start, uint end) { if (height <= 1 or !(column < width) or !(start < end)) + { return; + } // The values of the selected column auto& values = entry[column]; @@ -1600,12 +1728,16 @@ void Matrix::circularShiftRows(uint column, uint count) { assert(column < width and "Column out of bounds"); if (height <= 1 or !(column < width) or !count) + { return; + } // fits \p count into [0..height[ count = (count % height + height) % height; if (count == 0 or (uint) count == height) + { return; + } // Algorithm in O(N) reverseRows(column, 0, count); diff --git a/src/libs/antares/array/matrix.cpp b/src/libs/antares/array/matrix.cpp index b253446912..75cd0b9111 100644 --- a/src/libs/antares/array/matrix.cpp +++ b/src/libs/antares/array/matrix.cpp @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include #include "antares/array/matrix.h" +#include + using namespace Yuni; namespace Antares diff --git a/src/libs/antares/benchmarking/CMakeLists.txt b/src/libs/antares/benchmarking/CMakeLists.txt index 965272f9c5..09cf5dfd85 100644 --- a/src/libs/antares/benchmarking/CMakeLists.txt +++ b/src/libs/antares/benchmarking/CMakeLists.txt @@ -10,16 +10,20 @@ source_group("misc\\benchmarking" FILES ${SRC_BENCHMARKING}) add_library(benchmarking ${SRC_BENCHMARKING} - ) +) add_library(Antares::benchmarking ALIAS benchmarking) target_include_directories(benchmarking PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include - ) + $ +) target_link_libraries(benchmarking PRIVATE yuni-static-core inifile - ) +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/benchmarking/DurationCollector.cpp b/src/libs/antares/benchmarking/DurationCollector.cpp index b3a4f488a9..9d66166bca 100644 --- a/src/libs/antares/benchmarking/DurationCollector.cpp +++ b/src/libs/antares/benchmarking/DurationCollector.cpp @@ -1,22 +1,73 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/benchmarking/DurationCollector.h" + #include #include -#include "antares/benchmarking/DurationCollector.h" -namespace Benchmarking { +namespace Benchmarking +{ void DurationCollector::addDuration(const std::string& name, int64_t duration) { - const std::lock_guard lock(mutex_); + const std::lock_guard lock(mutex_); duration_items_[name].push_back(duration); } void DurationCollector::toFileContent(FileContent& file_content) { - for (const auto& [name, durations] : duration_items_) + for (const auto& [name, durations]: duration_items_) { - const int64_t duration_sum = accumulate(durations.begin(), durations.end(), (int64_t)0); + const int64_t duration_sum = accumulate(durations.begin(), durations.end(), 0); file_content.addDurationItem(name, (unsigned int)duration_sum, (int)durations.size()); } } + +DurationCollector::OperationTimer DurationCollector::operator()(const std::string& key) +{ + return OperationTimer(*this, key); +} + +void DurationCollector::OperationTimer::addDuration(int64_t duration_ms) const +{ + const std::scoped_lock lock(collector.mutex_); + collector.duration_items_[key].push_back(duration_ms); +} + +void operator<<(const DurationCollector::OperationTimer& op, const std::function& f) +{ + using clock = std::chrono::steady_clock; + auto start_ = clock::now(); + f(); + auto end_ = clock::now(); + auto duration_ms = std::chrono::duration_cast(end_ - start_).count(); + op.addDuration(duration_ms); +} + +int64_t DurationCollector::getTime(const std::string& name) const +{ + const auto& v = duration_items_.at(name); + + return accumulate(v.begin(), v.end(), 0); +} + } // namespace Benchmarking diff --git a/src/libs/antares/benchmarking/file_content.cpp b/src/libs/antares/benchmarking/file_content.cpp index 3272d4611f..07d362a4f3 100644 --- a/src/libs/antares/benchmarking/file_content.cpp +++ b/src/libs/antares/benchmarking/file_content.cpp @@ -1,6 +1,25 @@ -#include - +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include +#include using namespace std; @@ -18,13 +37,13 @@ FileContent::iterator FileContent::end() void FileContent::addItemToSection(const string& section, const string& key, int value) { - std::lock_guard guard(pSectionsMutex); + std::lock_guard guard(pSectionsMutex); sections_[section][key] = to_string(value); } void FileContent::addItemToSection(const string& section, const string& key, const string& value) { - std::lock_guard guard(pSectionsMutex); + std::lock_guard guard(pSectionsMutex); sections_[section][key] = value; } @@ -38,15 +57,15 @@ void FileContent::addDurationItem(const string& name, unsigned int duration, int std::string FileContent::saveToBufferAsIni() { Antares::IniFile ini; - for (const auto& [sectionName, content] : *this) + for (const auto& [sectionName, content]: *this) { // Loop on properties auto* section = ini.addSection(sectionName); - for (const auto& [key, value] : content) + for (const auto& [key, value]: content) + { section->add(key, value); + } } - std::string buffer; - ini.saveToString(buffer); - return buffer; + return ini.toString(); } } // namespace Benchmarking diff --git a/src/libs/antares/benchmarking/include/antares/benchmarking/DurationCollector.h b/src/libs/antares/benchmarking/include/antares/benchmarking/DurationCollector.h index 511cfb554e..30912e83d0 100644 --- a/src/libs/antares/benchmarking/include/antares/benchmarking/DurationCollector.h +++ b/src/libs/antares/benchmarking/include/antares/benchmarking/DurationCollector.h @@ -1,37 +1,62 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once -#include +#include +#include #include -#include #include +#include +#include #include "file_content.h" namespace Benchmarking { -class IDurationCollector +class DurationCollector { public: - virtual void addDuration(const std::string& name, int64_t duration) = 0; -}; + void toFileContent(FileContent& file_content); + void addDuration(const std::string& name, int64_t duration); -class NullDurationCollector : public IDurationCollector -{ -public: - NullDurationCollector() = default; - void addDuration(const std::string& /* name */, int64_t /* duration */) override - { /* Do nothing */ - } -}; + struct OperationTimer + { + OperationTimer(DurationCollector& collector, const std::string& key): + collector(collector), + key(key) + { + } -class DurationCollector : public IDurationCollector -{ -public: - DurationCollector() = default; + void addDuration(int64_t duration_ms) const; - void toFileContent(FileContent& file_content); - void addDuration(const std::string& name, int64_t duration) override; + DurationCollector& collector; + const std::string key; + }; + + OperationTimer operator()(const std::string& key); + + friend void operator<<(const OperationTimer& op, const std::function& f); + + int64_t getTime(const std::string& name) const; private: std::map> duration_items_; diff --git a/src/libs/antares/benchmarking/include/antares/benchmarking/file_content.h b/src/libs/antares/benchmarking/include/antares/benchmarking/file_content.h index 7f18df9aa3..15cd23c7a8 100644 --- a/src/libs/antares/benchmarking/include/antares/benchmarking/file_content.h +++ b/src/libs/antares/benchmarking/include/antares/benchmarking/file_content.h @@ -1,8 +1,28 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once -#include -#include #include +#include +#include namespace Benchmarking { diff --git a/src/libs/antares/benchmarking/include/antares/benchmarking/timer.h b/src/libs/antares/benchmarking/include/antares/benchmarking/timer.h index b13cc98378..42c6ad4679 100644 --- a/src/libs/antares/benchmarking/include/antares/benchmarking/timer.h +++ b/src/libs/antares/benchmarking/include/antares/benchmarking/timer.h @@ -1,33 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_TIME_ELAPSED__TIME_ELAPSED_H__ #define __ANTARES_LIBS_TIME_ELAPSED__TIME_ELAPSED_H__ -#include +#include namespace Benchmarking { diff --git a/src/libs/antares/benchmarking/timer.cpp b/src/libs/antares/benchmarking/timer.cpp index a76c2fdd91..a7a1d25d50 100644 --- a/src/libs/antares/benchmarking/timer.cpp +++ b/src/libs/antares/benchmarking/timer.cpp @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include #include +#include + using namespace Yuni; static inline int64_t MilliSecTimer() diff --git a/src/libs/antares/checks/CMakeLists.txt b/src/libs/antares/checks/CMakeLists.txt index 68e3447c9c..e301b8b548 100644 --- a/src/libs/antares/checks/CMakeLists.txt +++ b/src/libs/antares/checks/CMakeLists.txt @@ -1,6 +1,6 @@ set(SRC_CHECKS checkLoadedInputData.cpp - antares/checks/checkLoadedInputData.h + include/antares/checks/checkLoadedInputData.h ) source_group("checks" FILES ${SRC_CHECKS}) @@ -11,7 +11,7 @@ add_library(Antares::checks ALIAS checks) target_include_directories(checks PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} + $ ) target_link_libraries(checks @@ -22,3 +22,7 @@ target_link_libraries(checks Antares::study # cpp -> area antares-core ) + +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/libs/antares/checks/antares/checks/checkLoadedInputData.h b/src/libs/antares/checks/antares/checks/checkLoadedInputData.h deleted file mode 100644 index 8900cbfd62..0000000000 --- a/src/libs/antares/checks/antares/checks/checkLoadedInputData.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -namespace Antares::Check -{ -void checkStudyVersion(const AnyString& optStudyFolder); - -void checkSimplexRangeHydroPricing(Antares::Data::SimplexOptimization optRange, - Antares::Data::HydroPricingMode hpMode); - -void checkSimplexRangeUnitCommitmentMode(Antares::Data::SimplexOptimization optRange, - Antares::Data::UnitCommitmentMode ucMode); - -void checkSimplexRangeHydroHeuristic(Antares::Data::SimplexOptimization optRange, - const Antares::Data::AreaList& areas); - -void checkMinStablePower(bool tsGenThermal, const Antares::Data::AreaList& areas); - -void checkFuelCostColumnNumber(const Antares::Data::AreaList& areas); -void checkCO2CostColumnNumber(const Antares::Data::AreaList& areas); - -} // namespace Antares::Check diff --git a/src/libs/antares/checks/checkLoadedInputData.cpp b/src/libs/antares/checks/checkLoadedInputData.cpp index 3fcad20e02..b62408b050 100644 --- a/src/libs/antares/checks/checkLoadedInputData.cpp +++ b/src/libs/antares/checks/checkLoadedInputData.cpp @@ -1,56 +1,69 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include #include #include -#include - -#include +#include #include +#include +#include namespace Antares::Check { +void checkOrtoolsUsage(Antares::Data::UnitCommitmentMode ucMode, + bool ortoolsUsed, + const std::string& solverName) +{ + using namespace Antares::Data; + if (ucMode == UnitCommitmentMode::ucMILP) + { + if (!ortoolsUsed) + { + throw Error::IncompatibleMILPWithoutOrtools(); + } + + if (solverName == "sirius") + { + throw Error::IncompatibleMILPOrtoolsSolver(); + } + } +} + void checkStudyVersion(const AnyString& optStudyFolder) { using namespace Antares::Data; - auto version = StudyTryToFindTheVersion(optStudyFolder); - if (version == versionUnknown) + auto version = StudyHeader::tryToFindTheVersion(optStudyFolder); + + if (version == StudyVersion::unknown()) { throw Error::InvalidStudy(optStudyFolder); } - else + + if (version > StudyVersion::latest()) { - if ((uint)version > (uint)versionLatest) - { - throw Error::InvalidVersion(VersionToCStr(version), - VersionToCStr(versionLatest)); - } + throw Error::InvalidVersion(version.toString(), StudyVersion::latest().toString()); } } + // CHECK incompatible de choix simultané des options « simplex range= daily » et « hydro-pricing // = MILP ». void checkSimplexRangeHydroPricing(Antares::Data::SimplexOptimization optRange, @@ -134,50 +147,56 @@ void checkMinStablePower(bool tsGenThermal, const Antares::Data::AreaList& areas } else { - areas.each([](Antares::Data::Area& area) { area.thermal.checkAndCorrectAvailability(); }); + areas.each([](const auto& area) { area.thermal.checkAndCorrectAvailability(); }); } } // Number of columns for Fuel & CO2 cost in thermal clusters must be one, or same as the number of // TS template -static void checkThermalColumnNumber(const Antares::Data::AreaList& areas, - Matrix Antares::Data::EconomicInputData::*matrix) +static void checkThermalColumnNumber( + const Antares::Data::AreaList& areas, + Antares::Data::TimeSeries::TS Antares::Data::EconomicInputData::*matrix) { ExceptionT exception; bool error = false; for (uint areaIndex = 0; areaIndex < areas.size(); ++areaIndex) { const auto& area = *(areas.byIndex[areaIndex]); - for (uint clusterIndex = 0; clusterIndex != area.thermal.clusterCount(); ++clusterIndex) + for (auto& cluster: area.thermal.list.each_enabled()) { - const auto& cluster = *(area.thermal.clusters[clusterIndex]); - if (cluster.costgeneration == Antares::Data::setManually) + if (cluster->costgeneration == Antares::Data::setManually) + { continue; - const uint otherMatrixWidth = (cluster.ecoInput.*matrix).width; - uint tsWidth = cluster.series->timeSeries.width; + } + const uint otherMatrixWidth = (cluster->ecoInput.*matrix).width; + uint tsWidth = cluster->series.timeSeries.width; if (otherMatrixWidth != 1 && otherMatrixWidth != tsWidth) { - logs.warning() << "Area: " << area.name << ". Cluster name: " << cluster.name() + logs.warning() << "Area: " << area.name << ". Cluster name: " << cluster->name() << ". " << exception.what(); error = true; } } } if (error) + { throw exception; + } } void checkFuelCostColumnNumber(const Antares::Data::AreaList& areas) { - checkThermalColumnNumber(areas, - &Antares::Data::EconomicInputData::fuelcost); + checkThermalColumnNumber( + areas, + &Antares::Data::EconomicInputData::fuelcost); } void checkCO2CostColumnNumber(const Antares::Data::AreaList& areas) { - checkThermalColumnNumber(areas, - &Antares::Data::EconomicInputData::co2cost); + checkThermalColumnNumber( + areas, + &Antares::Data::EconomicInputData::co2cost); } } // namespace Antares::Check diff --git a/src/libs/antares/checks/include/antares/checks/checkLoadedInputData.h b/src/libs/antares/checks/include/antares/checks/checkLoadedInputData.h new file mode 100644 index 0000000000..62352390bc --- /dev/null +++ b/src/libs/antares/checks/include/antares/checks/checkLoadedInputData.h @@ -0,0 +1,47 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/optimization-options/options.h" +#include "antares/study/fwd.h" + +namespace Antares::Check +{ + +void checkOrtoolsUsage(Antares::Data::UnitCommitmentMode ucMode, + bool ortoolsUsed, + const std::string& solverName); + +void checkStudyVersion(const AnyString& optStudyFolder); + +void checkSimplexRangeHydroPricing(Antares::Data::SimplexOptimization optRange, + Antares::Data::HydroPricingMode hpMode); + +void checkSimplexRangeUnitCommitmentMode(Antares::Data::SimplexOptimization optRange, + Antares::Data::UnitCommitmentMode ucMode); + +void checkSimplexRangeHydroHeuristic(Antares::Data::SimplexOptimization optRange, + const Antares::Data::AreaList& areas); + +void checkMinStablePower(bool tsGenThermal, const Antares::Data::AreaList& areas); + +void checkFuelCostColumnNumber(const Antares::Data::AreaList& areas); +void checkCO2CostColumnNumber(const Antares::Data::AreaList& areas); + +} // namespace Antares::Check diff --git a/src/libs/antares/concurrency/CMakeLists.txt b/src/libs/antares/concurrency/CMakeLists.txt index ca8eb73c0e..29ab30a24b 100644 --- a/src/libs/antares/concurrency/CMakeLists.txt +++ b/src/libs/antares/concurrency/CMakeLists.txt @@ -4,6 +4,12 @@ add_library(concurrency) add_library(Antares::concurrency ALIAS concurrency) target_sources(concurrency PRIVATE concurrency.cpp) -target_include_directories(concurrency PUBLIC include) +target_include_directories(concurrency PUBLIC + $ +) -target_link_libraries(concurrency yuni-static-core) \ No newline at end of file +target_link_libraries(concurrency yuni-static-core) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/concurrency/concurrency.cpp b/src/libs/antares/concurrency/concurrency.cpp index 51f683372a..a7f118438c 100644 --- a/src/libs/antares/concurrency/concurrency.cpp +++ b/src/libs/antares/concurrency/concurrency.cpp @@ -1,51 +1,54 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/concurrency/concurrency.h" + #include + #include "yuni/job/job.h" -#include "antares/concurrency/concurrency.h" namespace Antares::Concurrency { -namespace { +namespace +{ /*! -* Just wraps an arbitrary task as a yuni job, and allows to retrieve the corresponding future. -*/ -class PackagedJob : public Yuni::Job::IJob { + * Just wraps an arbitrary task as a yuni job, and allows to retrieve the corresponding future. + */ +class PackagedJob: public Yuni::Job::IJob +{ public: - PackagedJob(const Task& task) : task_(task) {} + PackagedJob(const Task& task): + task_(task) + { + } - TaskFuture getFuture() { + TaskFuture getFuture() + { return task_.get_future(); } protected: - void onExecute() override { + void onExecute() override + { task_(); } @@ -53,31 +56,35 @@ class PackagedJob : public Yuni::Job::IJob { std::packaged_task task_; }; -} +} // namespace std::future AddTask(Yuni::Job::QueueService& threadPool, const Task& task, - Yuni::Job::Priority priority) { + Yuni::Job::Priority priority) +{ auto job = std::make_unique(task); auto future = job->getFuture(); threadPool.add(job.release(), priority); return future; } -void FutureSet::add(TaskFuture&& f) { +void FutureSet::add(TaskFuture&& f) +{ std::lock_guard lock(mutex_); futures_.push_back(std::move(f)); } -void FutureSet::join() { +void FutureSet::join() +{ std::vector toBeJoined; { std::lock_guard lock(mutex_); std::swap(futures_, toBeJoined); } - for (auto& f: toBeJoined) { + for (auto& f: toBeJoined) + { f.get(); } } -} +} // namespace Antares::Concurrency diff --git a/src/libs/antares/concurrency/include/antares/concurrency/concurrency.h b/src/libs/antares/concurrency/include/antares/concurrency/concurrency.h index 8813f3eeb1..2269fa33d4 100644 --- a/src/libs/antares/concurrency/include/antares/concurrency/concurrency.h +++ b/src/libs/antares/concurrency/include/antares/concurrency/concurrency.h @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef ANTARES_CONCURRENCY_H #define ANTARES_CONCURRENCY_H #include + #include "yuni/job/queue/service.h" namespace Antares::Concurrency @@ -43,8 +38,21 @@ using TaskFuture = std::future; * as opposite to Yuni::Job::QueueService::add which swallows them. */ [[nodiscard]] TaskFuture AddTask(Yuni::Job::QueueService& threadPool, - const Task& task, - Yuni::Job::Priority priority = Yuni::Job::priorityDefault); + const Task& task, + Yuni::Job::Priority priority = Yuni::Job::priorityDefault); + +/*! + * \brief Queues the provided function objects and returns the corresponding std::future. + * + * T must define operator (). + * + * This allows to handle exceptions occuring in the underlying task, + * as opposite to Yuni::Job::QueueService::add which swallows them. + */ +template +[[nodiscard]] TaskFuture AddTask(Yuni::Job::QueueService& threadPool, + const std::shared_ptr& task, + Yuni::Job::Priority priority = Yuni::Job::priorityDefault); /*! * \brief Utility class to gather futures to wait for. @@ -82,7 +90,44 @@ class FutureSet std::vector futures_; }; +namespace Detail +{ // implementation details + +/*! + * Utility class to wrap a callable object pointer + * into a copyable callable object. + * + * @tparam T the underlying callable type + */ +template +class CopyableCallable +{ +public: + explicit CopyableCallable(const std::shared_ptr& functionObject): + functionObject_(functionObject) + { + } + + void operator()() + { + (*functionObject_)(); + } + +private: + std::shared_ptr functionObject_; +}; + +} // namespace Detail + +template +TaskFuture AddTask(Yuni::Job::QueueService& threadPool, + const std::shared_ptr& task, + Yuni::Job::Priority priority) +{ + Task wrappedTask = Detail::CopyableCallable(task); + return AddTask(threadPool, wrappedTask, priority); } +} // namespace Antares::Concurrency -#endif //ANTARES_CONCURRENCY_H +#endif // ANTARES_CONCURRENCY_H diff --git a/src/libs/antares/config.h b/src/libs/antares/config.h deleted file mode 100644 index b421c6c91f..0000000000 --- a/src/libs/antares/config.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_CONFIG_H__ -#define __ANTARES_LIBS_CONFIG_H__ - -#include - -// Informations provided by CMake -#include "../../config.h" - -#endif /* __ANTARES_LIBS_CONFIG_H__ */ diff --git a/src/libs/antares/constants.cpp b/src/libs/antares/constants.cpp index 050e1a1ffb..fa780a8af3 100644 --- a/src/libs/antares/constants.cpp +++ b/src/libs/antares/constants.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "constants.h" +#include "antares/antares/constants.h" namespace Antares::Constants { diff --git a/src/libs/antares/constants.h b/src/libs/antares/constants.h deleted file mode 100644 index f82f0372de..0000000000 --- a/src/libs/antares/constants.h +++ /dev/null @@ -1,61 +0,0 @@ - -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_CONSTANTS_H__ -#define __ANTARES_LIBS_CONSTANTS_H__ - -#include "xpansion.h" -#include - -/*! Name of the app to use into logs */ -#define LOG_APPLICATION_NAME "antares" -/*! Vendor */ -#define LOG_APPLICATION_VENDOR "RTE" - -/*! Days per year */ -#define DAYS_PER_YEAR 365 - -/*! Hours per year */ -#define HOURS_PER_YEAR 8760 - -namespace Antares::Constants -{ -extern const std::array daysPerMonth; -extern const unsigned int nbHoursInAWeek; -} // namespace Antares::Constants - -/*! Max number of MC years */ -constexpr unsigned int MAX_NB_MC_YEARS = 50000; - -enum AntaresConstants -{ - ant_k_area_name_max_length = 128, - ant_k_cluster_name_max_length = 128, - ant_k_constraint_name_max_length = 128, -}; - -#endif /* __ANTARES_LIBS_CONSTANTS_H__ */ diff --git a/src/libs/antares/correlation/CMakeLists.txt b/src/libs/antares/correlation/CMakeLists.txt index c06f2b7a74..35036d78d7 100644 --- a/src/libs/antares/correlation/CMakeLists.txt +++ b/src/libs/antares/correlation/CMakeLists.txt @@ -1,8 +1,8 @@ set(SRC_CORRELATION correlation.cpp - antares/correlation/correlation.h - antares/correlation/correlation.hxx - ) + include/antares/correlation/correlation.h + include/antares/correlation/correlation.hxx +) source_group("correlation" FILES ${SRC_CORRELATION}) add_library(correlation @@ -16,13 +16,14 @@ target_link_libraries(correlation Antares::inifile Antares::array Antares::study #correlation.h -> area.h - ) + Antares::locator +) target_include_directories(correlation - PRIVATE - ${CMAKE_SOURCE_DIR}/libs/ #area -> antares/study/parameters/adq-patch-params.h - ${CMAKE_SOURCE_DIR}/libs/antares/date #area -> antares/study/parameters/adq-patch-params.h -> date - ${CMAKE_SOURCE_DIR}/libs/antares/writer #area -> antares/parts/thermal/cluster -> writer PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ) \ No newline at end of file + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/correlation/antares/correlation/correlation.hxx b/src/libs/antares/correlation/antares/correlation/correlation.hxx deleted file mode 100644 index 01d825fbdc..0000000000 --- a/src/libs/antares/correlation/antares/correlation/correlation.hxx +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_ARRAY_CORRELATION_HXX__ -#define __ANTARES_LIBS_ARRAY_CORRELATION_HXX__ -#include "antares/study/area/area.h" - -namespace Antares -{ -namespace Data -{ -inline void InterAreaCorrelationResetMatrix(Matrix<>* m, AreaList* l) -{ - assert(NULL != m); - assert(NULL != l); - m->resize(l->size(), l->size()); - m->fillUnit(); -} - -inline void Correlation::mode(Correlation::Mode mode) -{ - pMode = mode; -} - -inline Correlation::Mode Correlation::mode() const -{ - return pMode; -} - -template -inline void Correlation::set(Matrix<>& m, const Area& from, const Area& to, const StringT& value) -{ - double d; - if (!value.template to(d)) - { - Antares::logs.error() << correlationName << ": Invalid decimal value for '" << from.name - << "' / '" << to.name << "' (got '" << value << "')"; - return; - } - - set(m, from, to, d); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_ARRAY_CORRELATION_HXX__ diff --git a/src/libs/antares/correlation/correlation.cpp b/src/libs/antares/correlation/correlation.cpp index b6673f238b..50b4084bf1 100644 --- a/src/libs/antares/correlation/correlation.cpp +++ b/src/libs/antares/correlation/correlation.cpp @@ -1,34 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/correlation/correlation.h" -#include "antares/study/study.h" -#include "antares/study/area/area.h" + #include +#include +#include "antares/study/area/area.h" +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; @@ -86,21 +82,27 @@ static inline bool ReadCorrelationModeFromINI(const IniFile& ini, if (!section) { if (warnings) + { logs.error() << ini.filename() << ": the section 'general' is missing"; + } return false; } const IniFile::Property* p = section->find("mode"); if (!p) { if (warnings) + { logs.error() << ini.filename() << ": the property 'mode' is missing"; + } return false; } mode = Correlation::CStringToMode(p->value.c_str()); if (mode == Correlation::modeNone) { if (warnings) + { logs.error() << ini.filename() << ": invalid correlation mode"; + } return false; } return true; @@ -120,7 +122,9 @@ static inline void ReadCorrelationCoefficients(Correlation& correlation, for (auto* p = section.firstProperty; p; p = p->next) { if (p->key.empty()) + { continue; + } const AreaName::Size offset = p->key.find('%'); if (offset == AreaName::npos or !offset or offset == p->key.size() - 1) @@ -137,15 +141,19 @@ static inline void ReadCorrelationCoefficients(Correlation& correlation, if (!from) { if (warnings) + { logs.error() << ini.filename() << ": '" << nameFrom << "': impossible to find the area"; + } continue; } if (!to) { if (warnings) + { logs.error() << ini.filename() << ": '" << nameTo << "': impossible to find the area"; + } continue; } @@ -171,7 +179,9 @@ static inline void ExportCorrelationCoefficients(Study& study, const std::string& name) { if (m.empty() or m.width != m.height) + { return; + } file << '[' << name << "]\n"; @@ -183,7 +193,7 @@ static inline void ExportCorrelationCoefficients(Study& study, auto& col = m.entry[x]; for (uint y = 0; y < x; ++y) { - if (!Math::Zero(col[y])) + if (!Utils::isZero(col[y])) { file << from << '%' << study.areas.byIndex[y]->id << " = " << col[y] << '\n'; } @@ -202,13 +212,13 @@ int InterAreaCorrelationLoadFromIniFile(Matrix<>* m, AreaList* l, IniFile* ini, if (ini) { IniFile::Section* s; - for (s = ini->firstSection; s != NULL; s = s->next) /* Each section */ + for (s = ini->firstSection; s; s = s->next) /* Each section */ { Area* from = AreaListLFind(l, s->name.c_str()); if (from) { IniFile::Property* p; - for (p = s->firstProperty; p != NULL; p = p->next) /* Each property*/ + for (p = s->firstProperty; p; p = p->next) /* Each property*/ { Area* to = AreaListLFind(l, p->key.c_str()); if (to and to != from) @@ -219,15 +229,19 @@ int InterAreaCorrelationLoadFromIniFile(Matrix<>* m, AreaList* l, IniFile* ini, else /* nullptr != to */ { if (warnings) + { logs.warning() << "Correlation: " << s->name << ": " << p->key << ": Area not found"; + } } } } else /* nullptr != from */ { if (warnings) + { logs.warning() << "Correlation: " << s->name << ": Area not found"; + } } } return 1; @@ -235,12 +249,12 @@ int InterAreaCorrelationLoadFromIniFile(Matrix<>* m, AreaList* l, IniFile* ini, return 0; } -int InterAreaCorrelationLoadFromFile(Matrix<>* m, AreaList* l, const char filename[]) +int InterAreaCorrelationLoadFromFile(Matrix<>* m, AreaList* l, const std::string& filename) { /* Asserts */ assert(m); assert(l); - assert(filename); + assert(!filename.empty()); InterAreaCorrelationResetMatrix(m, l); IniFile ini; @@ -278,7 +292,9 @@ IniFile* InterAreaCorrelationSaveToIniFile(const Matrix<>* m, const AreaList* l) for (y = 0; y < x; ++y) { if (fabs(col[y]) > 0.00000001) + { s->add(l->byIndex[y]->id, col[y]); + } } } } @@ -292,7 +308,9 @@ int InterAreaCorrelationSaveToFile(const Matrix<>* m, const AreaList* l, const c assert(l); if (!filename or '\0' == *filename) + { return 0; + } if (m->width != l->size() or m->height != l->size()) { logs.error() << filename << ": The matrix does not have the good sie (" << l->size() << 'x' @@ -308,7 +326,10 @@ int InterAreaCorrelationSaveToFile(const Matrix<>* m, const AreaList* l, const c return 0; } -Correlation::Correlation() : annual(nullptr), monthly(nullptr), pMode(modeNone) +Correlation::Correlation(): + annual(nullptr), + monthly(nullptr), + pMode(modeNone) { } @@ -359,9 +380,13 @@ Correlation::Mode Correlation::CStringToMode(const AnyString& str) s.trim(" \t\r\n"); s.toLower(); if (s == "annual") + { return modeAnnual; + } if (s == "monthly") + { return modeMonthly; + } return modeNone; } @@ -377,7 +402,9 @@ void Correlation::internalSaveToINI(Study& study, IO::File::Stream& file) const ExportCorrelationCoefficients(study, *annual, file, "annual"); } else + { logs.error() << correlationName << ": the annual correlation coefficients are missing"; + } if (monthly) { @@ -387,13 +414,17 @@ void Correlation::internalSaveToINI(Study& study, IO::File::Stream& file) const } } else + { logs.error() << correlationName << ": the montlhy correlation coefficients are missing"; + } } bool Correlation::internalLoadFromINITry(Study& study, const IniFile& ini, bool warnings) { if (!ReadCorrelationModeFromINI(ini, pMode, warnings)) + { return false; + } if (JIT::usedFromGUI or pMode == modeAnnual) { @@ -403,7 +434,9 @@ bool Correlation::internalLoadFromINITry(Study& study, const IniFile& ini, bool auto* section = ini.find("annual"); if (section) // the section might be missing + { ReadCorrelationCoefficients(*this, study, *annual, ini, *section, warnings); + } } if (JIT::usedFromGUI or pMode == modeMonthly) @@ -422,11 +455,17 @@ bool Correlation::internalLoadFromINITry(Study& study, const IniFile& ini, bool { if (index >= 0 and index < 12) { - ReadCorrelationCoefficients( - *this, study, monthly[index], ini, *section, warnings); + ReadCorrelationCoefficients(*this, + study, + monthly[index], + ini, + *section, + warnings); } else + { logs.error() << "Invalid month index: " << index; + } } } } @@ -546,9 +585,13 @@ void Correlation::set(Matrix<>& m, const Area& from, const Area& to, double v) { double copy = v; if (v < -1.) + { v = -1.; + } if (v > +1.) + { v = +1.; + } logs.warning() << correlationName << ": `" << from.name << "` / `" << to.name << "`: Expected a value in [-1..+1], got " << copy << ", rounded to " << v; } @@ -564,19 +607,25 @@ void Correlation::retrieveMontlyMatrixArray(const Matrix<>* array[12]) const case modeAnnual: { for (uint i = 0; i != 12; ++i) + { array[i] = annual; + } break; } case modeMonthly: { for (uint i = 0; i != 12; ++i) + { array[i] = &(monthly[i]); + } break; } default: { for (uint i = 0; i != 12; ++i) + { array[i] = nullptr; + } return; } } @@ -586,11 +635,15 @@ uint64_t Correlation::memoryUsage() const { uint64_t r = sizeof(Correlation); if (annual) + { r += annual->memoryUsage(); + } if (monthly) { for (uint i = 0; i != 12; ++i) + { r += monthly[i].memoryUsage(); + } } return r; } @@ -599,9 +652,13 @@ bool Correlation::forceReload(bool reload) const { bool ret = true; if (annual) + { ret = annual->forceReload(reload) and ret; + } for (uint i = 0; i != 12; ++i) + { ret = monthly[i].forceReload(reload) and ret; + } return ret; } @@ -609,9 +666,13 @@ bool Correlation::forceReload(bool reload) const void Correlation::markAsModified() const { if (annual) + { annual->markAsModified(); + } for (uint i = 0; i != 12; ++i) + { monthly[i].markAsModified(); + } } static inline uint FindMappedAreaName(const AreaName& name, @@ -645,7 +706,9 @@ static void CopyFromSingleMatrix(const Matrix<>& mxsrc, { auto* a = studySource.areas.find(*i); if (!a) + { continue; + } x = a->index; } @@ -672,6 +735,7 @@ void Correlation::copyFrom(const Correlation& source, // No correlation return; } + enum { invalid = (uint)-1, @@ -698,8 +762,13 @@ void Correlation::copyFrom(const Correlation& source, // copying the annual correlation matrix std::cout << "ANNUAL\n"; - CopyFromSingleMatrix( - *source.annual, *annual, studySource, areaSourceIndex, areaTargetIndex, mapping, study); + CopyFromSingleMatrix(*source.annual, + *annual, + studySource, + areaSourceIndex, + areaTargetIndex, + mapping, + study); std::cout << "MONTHLY\n"; // copying monthly correlation matrix @@ -716,4 +785,3 @@ void Correlation::copyFrom(const Correlation& source, } } // namespace Antares::Data - diff --git a/src/libs/antares/correlation/antares/correlation/correlation.h b/src/libs/antares/correlation/include/antares/correlation/correlation.h similarity index 85% rename from src/libs/antares/correlation/antares/correlation/correlation.h rename to src/libs/antares/correlation/include/antares/correlation/correlation.h index 0db3c21e7b..9dc48c5a76 100644 --- a/src/libs/antares/correlation/antares/correlation/correlation.h +++ b/src/libs/antares/correlation/include/antares/correlation/correlation.h @@ -1,41 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_ARRAY_CORRELATION_H__ #define __ANTARES_LIBS_ARRAY_CORRELATION_H__ #include + #include #include -#include "../study/fwd.h" -#include "../study/version.h" +#include "antares/study/fwd.h" +#include "antares/study/version.h" -namespace Antares -{ -namespace Data +namespace Antares::Data { class Correlation final @@ -102,9 +95,7 @@ class Correlation final ** \param version Format version expected. Use studyVersionUnknown to use the format version ** of the given study */ - bool loadFromFile(Study& study, - const AnyString& filename, - bool warnings = true); + bool loadFromFile(Study& study, const AnyString& filename, bool warnings = true); /*! ** \brief Save the correlation matrices into an INI file @@ -195,7 +186,7 @@ void InterAreaCorrelationResetMatrix(Matrix<>* m, AreaList* l); ** \param filename The filename to use to load values ** \return A non-zero value if the matrix has been loaded, 0 otherwise */ -int InterAreaCorrelationLoadFromFile(Matrix<>* m, AreaList* l, const char filename[]); +int InterAreaCorrelationLoadFromFile(Matrix<>* m, AreaList* l, const std::string& filename); /*! ** \brief Save an inter-area correlation matrix to a file @@ -240,10 +231,10 @@ int InterAreaCorrelationLoadFromIniFile(Matrix<>* m, AreaList* l, IniFile* ini, */ IniFile* InterAreaCorrelationSaveToIniFile(const Matrix<>* m, const AreaList* l); -} // namespace Data -} // namespace Antares +} // namespace Antares::Data #include + #include "correlation.hxx" #endif /* __ANTARES_LIBS_ARRAY_CORRELATION_H__ */ diff --git a/src/libs/antares/correlation/include/antares/correlation/correlation.hxx b/src/libs/antares/correlation/include/antares/correlation/correlation.hxx new file mode 100644 index 0000000000..788992bb71 --- /dev/null +++ b/src/libs/antares/correlation/include/antares/correlation/correlation.hxx @@ -0,0 +1,64 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_ARRAY_CORRELATION_HXX__ +#define __ANTARES_LIBS_ARRAY_CORRELATION_HXX__ +#include "antares/study/area/area.h" + +namespace Antares +{ +namespace Data +{ +inline void InterAreaCorrelationResetMatrix(Matrix<>* m, AreaList* l) +{ + assert(NULL != m); + assert(NULL != l); + m->resize(l->size(), l->size()); + m->fillUnit(); +} + +inline void Correlation::mode(Correlation::Mode mode) +{ + pMode = mode; +} + +inline Correlation::Mode Correlation::mode() const +{ + return pMode; +} + +template +inline void Correlation::set(Matrix<>& m, const Area& from, const Area& to, const StringT& value) +{ + double d; + if (!value.template to(d)) + { + Antares::logs.error() << correlationName << ": Invalid decimal value for '" << from.name + << "' / '" << to.name << "' (got '" << value << "')"; + return; + } + + set(m, from, to, d); +} + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_ARRAY_CORRELATION_HXX__ diff --git a/src/libs/antares/date/CMakeLists.txt b/src/libs/antares/date/CMakeLists.txt index 3f56483ef1..8fb4115240 100644 --- a/src/libs/antares/date/CMakeLists.txt +++ b/src/libs/antares/date/CMakeLists.txt @@ -1,6 +1,6 @@ set(PROJ date) set(HEADERS - antares/${PROJ}/date.h + include/antares/${PROJ}/date.h ) set(SRC_DATE ${HEADERS} @@ -12,6 +12,8 @@ add_library(${PROJ} ${SRC_DATE}) add_library(Antares::${PROJ} ALIAS ${PROJ}) target_link_libraries(${PROJ} + PUBLIC + study PRIVATE yuni-static-core logs @@ -19,5 +21,9 @@ target_link_libraries(${PROJ} target_include_directories(${PROJ} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/date/date.cpp b/src/libs/antares/date/date.cpp index 1572c27cd3..acec182242 100644 --- a/src/libs/antares/date/date.cpp +++ b/src/libs/antares/date/date.cpp @@ -1,43 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include + +#include + #include #include -#include -#include #include + +#include #include using namespace Yuni; - namespace Antares::Date { -static const uint StandardDaysPerMonths[12] = { +static const uint StandardDaysPerMonths[MONTHS_PER_YEAR] = { 31, // january 28, // february 31, // march @@ -78,14 +75,44 @@ static const char* const monthNamesLower[] = {"january", "november", "december"}; -static const char* const monthShortNames[] - = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - -static const char* const monthShortLowerNames[] - = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; - -static const char* const monthShortUpperNames[] - = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; +static const char* const monthShortNames[] = {"Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec"}; + +static const char* const monthShortLowerNames[] = {"jan", + "feb", + "mar", + "apr", + "may", + "jun", + "jul", + "aug", + "sep", + "oct", + "nov", + "dec"}; + +static const char* const monthShortUpperNames[] = {"JAN", + "FEB", + "MAR", + "APR", + "MAY", + "JUN", + "JUL", + "AUG", + "SEP", + "OCT", + "NOV", + "DEC"}; uint DayInterval::numberOfWeeks() const { @@ -94,8 +121,13 @@ uint DayInterval::numberOfWeeks() const const char* DayOfTheWeekToString(DayOfTheWeek d) { - static const char* const days[] - = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; + static const char* const days[] = {"Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday"}; return days[(uint)d % 7]; } @@ -103,14 +135,17 @@ const char* DayOfTheWeekToString(DayOfTheWeek d) bool StringToMonth(MonthName& out, AnyString text) { if (text.empty()) + { return false; + } text.trim(); - CString<12, false> t = text; - t.toLower(); + std::string t = text; + boost::algorithm::to_lower(t); + /* t.toLower(); */ if (t.size() == 3) { - for (uint m = 0; m != 12; ++m) + for (uint m = 0; m != MONTHS_PER_YEAR; ++m) { if (monthShortLowerNames[m] == t) { @@ -121,7 +156,7 @@ bool StringToMonth(MonthName& out, AnyString text) } else { - for (uint m = 0; m != 12; ++m) + for (uint m = 0; m != MONTHS_PER_YEAR; ++m) { if (monthNamesLower[m] == t) { @@ -136,28 +171,33 @@ bool StringToMonth(MonthName& out, AnyString text) const char* MonthToString(int m, int offset) { - return monthNames[(m - offset) % 12]; + return monthNames[(m - offset) % MONTHS_PER_YEAR]; } const char* MonthToLowerString(int m, int offset) { - return monthNamesLower[(m - offset) % 12]; + return monthNamesLower[(m - offset) % MONTHS_PER_YEAR]; } const char* MonthToShortString(int m, int offset) { - return monthShortNames[(m - offset) % 12]; + return monthShortNames[(m - offset) % MONTHS_PER_YEAR]; } const char* MonthToUpperShortString(int m, int offset) { - return monthShortUpperNames[(m - offset) % 12]; + return monthShortUpperNames[(m - offset) % MONTHS_PER_YEAR]; } const char* WeekdayToString(int m) { - static const char* const wdays[] - = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; + static const char* const wdays[] = {"Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday"}; return wdays[m % 7]; } @@ -227,23 +267,33 @@ bool StringToDayOfTheWeek(DayOfTheWeek& v, const AnyString& text) return true; } if (str == "mardi") + { return 0 != (v = tuesday); + } if (str == "mercredi") + { return 0 != (v = wednesday); + } break; } case 't': { if (str == "tuesday") + { return 0 != (v = tuesday); + } if (str == "thursday") + { return 0 != (v = thursday); + } break; } case 'f': { if (str == "friday") + { return 0 != (v = friday); + } break; } @@ -259,35 +309,49 @@ bool StringToDayOfTheWeek(DayOfTheWeek& v, const AnyString& text) case 's': { if (str == "saturday") + { return 0 != (v = saturday); + } if (str == "sunday") + { return 0 != (v = sunday); + } if (str == "samedi") + { return 0 != (v = saturday); + } break; } case 'w': { if (str == "wednesday") + { return 0 != (v = wednesday); + } break; } case 'j': { if (str == "jeudi") + { return 0 != (v = thursday); + } break; } case 'v': { if (str == "vendredi") + { return 0 != (v = friday); + } break; } case 'd': { if (str == "dimanche") + { return 0 != (v = sunday); + } break; } } @@ -363,7 +427,7 @@ bool Calendar::saveToCSVFile(const AnyString& filename) const line.clear() << "hour begin\thour end\tdays\tday uear begin\tday year end\tfirst weekday"; report.months.push_back(line); - for (uint m = 0; m != 12; ++m) + for (uint m = 0; m != MONTHS_PER_YEAR; ++m) { auto& month = months[m]; line.clear(); @@ -381,11 +445,17 @@ bool Calendar::saveToCSVFile(const AnyString& filename) const { file << report.hours[i] << '\t'; if (i < report.days.size()) + { file << report.days[i] << '\t'; + } if (i < report.weeks.size()) + { file << report.weeks[i] << '\t'; + } if (i < report.months.size()) + { file << report.months[i] << '\t'; + } file << '\n'; } return true; @@ -416,8 +486,7 @@ static inline DayOfTheWeek NextDayOfTheWeek(DayOfTheWeek weekday) void Calendar::reset() { #ifndef NDEBUG - logs.debug() << " reset calendar" - << ", month : " << MonthToString(settings_.firstMonth) + logs.debug() << " reset calendar" << ", month : " << MonthToString(settings_.firstMonth) << ", january 1rst : " << DayOfTheWeekToString(settings_.weekday1rstJanuary) << ", first weekday : " << DayOfTheWeekToString(settings_.weekFirstDay); #endif @@ -428,11 +497,13 @@ void Calendar::reset() (void)::memset(months, '\0', sizeof(months)); // Reset months relationship - for (uint m = 0; m != 12 + 1; ++m) + for (uint m = 0; m != MONTHS_PER_YEAR + 1; ++m) { - uint realmonth = (m + (uint)settings_.firstMonth) % 12; - if (m < 12) + uint realmonth = (m + (uint)settings_.firstMonth) % MONTHS_PER_YEAR; + if (m < MONTHS_PER_YEAR) + { mapping.months[realmonth] = m; + } months[m].days = StandardDaysPerMonths[realmonth]; months[m].realmonth = (MonthName)realmonth; @@ -444,7 +515,9 @@ void Calendar::reset() // leap year if (settings_.leapYear) + { months[mapping.months[february]].days += 1; + } // looking for the weekday of the first month auto weekday = settings_.weekday1rstJanuary; @@ -455,7 +528,9 @@ void Calendar::reset() { uint nbdays = (int)months[mapping.months[m]].days; for (uint d = 0; d != nbdays; ++d) + { weekday = (weekday == monday) ? sunday : ((DayOfTheWeek)((uint)weekday - 1)); + } } } @@ -568,13 +643,17 @@ void Calendar::reset() // next weeks... uint userweek = (startuserweek == 53 ? 1 : 2); for (int w = weekindex + 1; w < maxWeeksInYear; ++w, ++userweek) + { weeks[w].userweek = userweek; + } // previous weeks... // userweek = (startuserweek == 1 ? 53 : 52); userweek = 52; // always 52 from now on for (int w = weekindex - 1; w >= 0; --w, --userweek) + { weeks[w].userweek = userweek; + } } // Caution : @@ -591,21 +670,33 @@ void Calendar::reset() // Hour in the year - 1..8760 uint hour = hourYear + 1; if (hour >= 1000) + { hourtext << hour; + } else if (hour < 10) + { hourtext << "000" << hour; + } else if (hour < 100) + { hourtext << "00" << hour; + } else if (hour < 1000) + { hourtext << '0' << hour; + } // week hourtext << " ("; uint week = weeks[hourinfo.week].userweek; if (week >= 10) + { hourtext << week; + } else + { hourtext << '0' << week; + } hourtext << ')'; hourtext << " - "; @@ -615,16 +706,24 @@ void Calendar::reset() hourtext << text.months[hourinfo.month].shortUpperName; hourtext << ' '; if (hourinfo.dayMonth + 1 < 10) + { hourtext << '0' << (hourinfo.dayMonth + 1); + } else + { hourtext << (hourinfo.dayMonth + 1); + } hourtext << ' '; if (hourinfo.dayHour >= 10) + { hourtext << hourinfo.dayHour; + } else + { hourtext << '0' << hourinfo.dayHour; + } hourtext << ":00"; } @@ -636,19 +735,29 @@ void Calendar::reset() auto& dayinfo = days[d]; uint day = d + 1; if (day < 10) + { str << "00" << day; + } else if (day < 100) + { str << '0' << day; + } else + { str << day; + } // week str << " ("; uint week = weeks[dayinfo.week].userweek; if (week >= 10) + { str << week; + } else + { str << '0' << week; + } str << ") - "; str << WeekdayToShortUpperString((uint)dayinfo.weekday); @@ -656,12 +765,15 @@ void Calendar::reset() str << text.months[dayinfo.month].shortUpperName; str << ' '; if (dayinfo.dayMonth + 1 < 10) + { str << '0' << (dayinfo.dayMonth + 1); + } else + { str << (dayinfo.dayMonth + 1); + } } } } } // namespace Antares::Date - diff --git a/src/libs/antares/date/antares/date/date.h b/src/libs/antares/date/include/antares/date/date.h similarity index 90% rename from src/libs/antares/date/antares/date/date.h rename to src/libs/antares/date/include/antares/date/date.h index 08bc29330e..1e4db54f61 100644 --- a/src/libs/antares/date/antares/date/date.h +++ b/src/libs/antares/date/include/antares/date/date.h @@ -1,37 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_DATE_DATE_H__ #define __ANTARES_LIBS_DATE_DATE_H__ +#include + #include #include -#include -#include "../../../constants.h" -#include "../../../study/fwd.h" + +#include "antares/study/fwd.h" namespace Antares { @@ -66,9 +61,7 @@ enum MonthName } // namespace Antares -namespace Antares -{ -namespace Date +namespace Antares::Date { /*! ** \brief Convert a month from its index to its string representation (January..December) @@ -192,6 +185,7 @@ class Calendar using ShortString12 = Yuni::CString<11, false>; //! Short string representation with maximum 8 characters using ShortString8 = Yuni::CString<7, false>; + enum { //! The maximum number of hours in a year @@ -338,10 +332,12 @@ class Calendar ** \brief Default constructor */ Calendar(); + //! Destructor ~Calendar() { } + //@} /*! @@ -368,7 +364,6 @@ class Calendar Settings settings_; }; // class Calendar -} // namespace Date -} // namespace Antares +} // namespace Antares::Date #endif // __ANTARES_TOOLBOX_DATE_H__ diff --git a/src/libs/antares/exception/AssertionError.cpp b/src/libs/antares/exception/AssertionError.cpp index 9391bc75d1..3f41b205e4 100644 --- a/src/libs/antares/exception/AssertionError.cpp +++ b/src/libs/antares/exception/AssertionError.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -30,10 +24,11 @@ namespace Antares { namespace Data { -AssertionError::AssertionError(const std::string& message) : std::runtime_error(message) +AssertionError::AssertionError(const std::string& message): + std::runtime_error(message) { } } // namespace Data -} // namespace Antares \ No newline at end of file +} // namespace Antares diff --git a/src/libs/antares/exception/CMakeLists.txt b/src/libs/antares/exception/CMakeLists.txt index 823b4acca6..691967b267 100644 --- a/src/libs/antares/exception/CMakeLists.txt +++ b/src/libs/antares/exception/CMakeLists.txt @@ -4,9 +4,10 @@ set(SRC_PROJ LoadingError.cpp UnfeasibleProblemError.cpp - antares/exception/AssertionError.hpp - antares/exception/UnfeasibleProblemError.hpp - antares/exception/LoadingError.hpp + include/antares/exception/AssertionError.hpp + include/antares/exception/InitializationError.hpp + include/antares/exception/LoadingError.hpp + include/antares/exception/UnfeasibleProblemError.hpp ) source_group("exception" FILES ${SRC_PROJ}) @@ -14,12 +15,17 @@ add_library(${PROJ} ${SRC_PROJ}) add_library(Antares::${PROJ} ALIAS ${PROJ}) target_link_libraries(${PROJ} + PUBLIC + Antares::study PRIVATE yuni-static-core ) target_include_directories(${PROJ} - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/libs #fwd + PUBLIC + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/exception/LoadingError.cpp b/src/libs/antares/exception/LoadingError.cpp index 5334b0912d..499f0ed3f6 100644 --- a/src/libs/antares/exception/LoadingError.cpp +++ b/src/libs/antares/exception/LoadingError.cpp @@ -1,96 +1,149 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "antares/exception/LoadingError.hpp" +#include + namespace Antares { namespace Error { -StudyFolderDoesNotExist::StudyFolderDoesNotExist(const Yuni::String& folder) : - LoadingError(std::string("Study folder") + folder.c_str() + " does not exist.") +StudyFolderDoesNotExist::StudyFolderDoesNotExist(const Yuni::String& folder): + LoadingError(std::string("Study folder") + folder.c_str() + " does not exist.") { } -ReadingStudy::ReadingStudy() : LoadingError("Got a fatal error reading the study.") +ReadingStudy::ReadingStudy(): + LoadingError("Got a fatal error reading the study.") { } -NoAreas::NoAreas() : LoadingError("No area found. A valid study contains contains at least one.") +NoAreas::NoAreas(): + LoadingError("No area found. A valid study contains contains at least one.") { } -InvalidFileName::InvalidFileName() : LoadingError("Invalid file names detected.") +InvalidFileName::InvalidFileName(): + LoadingError("Invalid file names detected.") { } -RuntimeInfoInitialization::RuntimeInfoInitialization() : - LoadingError("Error initializing runtime infos.") +RuntimeInfoInitialization::RuntimeInfoInitialization(): + LoadingError("Error initializing runtime infos.") { } -WritingPID::WritingPID(const Yuni::String& file) : - LoadingError(std::string("Impossible to write pid file ") + file.c_str()) +WritingPID::WritingPID(const Yuni::String& file): + LoadingError(std::string("Impossible to write pid file ") + file.c_str()) { } -InvalidOptimizationRange::InvalidOptimizationRange() : - LoadingError("Invalid command line value for --optimization-range ('day' or 'week' expected)") +InvalidOptimizationRange::InvalidOptimizationRange(): + LoadingError("Invalid command line value for --optimization-range ('day' or 'week' expected)") { } -InvalidSimulationMode::InvalidSimulationMode() : - LoadingError("Only one simulation mode is allowed: --expansion, --economy, --adequacy") +InvalidSimulationMode::InvalidSimulationMode(): + LoadingError("Only one simulation mode is allowed: --expansion, --economy, --adequacy") { } -InvalidSolver::InvalidSolver(const std::string& solver) : - LoadingError("Can't use solver '" + solver + "' : it does not match any available OR-Tools solver") +static std::string InvalidSolverHelper(const std::string& solver, + const std::string& availableSolvers) { + std::ostringstream message; + message << "Can't use solver '" << solver + << "' : it does not match any available OR-Tools solver. Possible choices are " + << availableSolvers; + return message.str(); } -InvalidStudy::InvalidStudy(const Yuni::String& study) : - LoadingError(std::string("The folder `") + study.c_str() + "` does not seem to be a valid study") +InvalidSolver::InvalidSolver(const std::string& solver, const std::string& availableSolvers): + LoadingError(InvalidSolverHelper(solver, availableSolvers)) { } -InvalidVersion::InvalidVersion(const char* version, const char* latest) : - LoadingError(std::string("Invalid version for the study : found `") + version + "`, expected <=`" - + latest + '`') +static std::string InvalidSolverSpecificParametersHelper(const std::string& solver, + const std::string& specificParameters) { + std::ostringstream message; + message << "Specific parameters '" << specificParameters + << "' are not valid or not supported for solver " << solver; + return message.str(); } -NoStudyProvided::NoStudyProvided() : - LoadingError("A study folder is required. Use '--help' for more information") +InvalidSolverSpecificParameters::InvalidSolverSpecificParameters( + const std::string& solver, + const std::string& specificParameters): + LoadingError(InvalidSolverSpecificParametersHelper(solver, specificParameters)) { } -InvalidNumberOfMCYears::InvalidNumberOfMCYears(uint nbYears) : - LoadingError("Invalid number of MC years, got " + std::to_string(nbYears) + ", expected <= 50000") +InvalidStudy::InvalidStudy(const Yuni::String& study): + LoadingError(std::string("The folder `") + study.c_str() + + "` does not seem to be a valid study") { } -IncompatibleParallelOptions::IncompatibleParallelOptions() : - LoadingError("Options --parallel and --force-parallel are incompatible") +InvalidVersion::InvalidVersion(const std::string& version, const std::string& latest): + LoadingError(std::string("Invalid version for the study : found `") + version + + "`, expected <=`" + latest + '`') { } -IncompatibleOptRangeHydroPricing::IncompatibleOptRangeHydroPricing() : - LoadingError("Simplex optimization range and hydro pricing mode : values are not compatible ") +NoStudyProvided::NoStudyProvided(): + LoadingError("A study folder is required. Use '--help' for more information") { } -IncompatibleOptRangeUCMode::IncompatibleOptRangeUCMode() : - LoadingError("Simplexe optimization range and unit commitment mode : values are not compatible") +IncompatibleParallelOptions::IncompatibleParallelOptions(): + LoadingError("Options --parallel and --force-parallel are incompatible") { } -IncompatibleDailyOptHeuristicForArea::IncompatibleDailyOptHeuristicForArea( - const Antares::Data::AreaName& name) : - LoadingError(std::string("Area ") + name.c_str() - + " : simplex daily optimization and use heuristic target == no are not compatible") +IncompatibleMILPWithoutOrtools::IncompatibleMILPWithoutOrtools(): + LoadingError("Unit Commitment mode 'milp' must be used with an OR-Tools solver ") +{ +} + +IncompatibleMILPOrtoolsSolver::IncompatibleMILPOrtoolsSolver(): + LoadingError("'milp' mode does not work with OR-Tools using Sirius solver") +{ +} + +IncompatibleOptRangeHydroPricing::IncompatibleOptRangeHydroPricing(): + LoadingError("Simplex optimization range and hydro pricing mode : values are not compatible ") { } -WritingProgressFile::WritingProgressFile(const Yuni::String& file) : - LoadingError(std::string("I/O error: impossible to write ") + file.c_str()) +IncompatibleOptRangeUCMode::IncompatibleOptRangeUCMode(): + LoadingError("Simplexe optimization range and unit commitment mode : values are not compatible") +{ +} + +IncompatibleDailyOptHeuristicForArea::IncompatibleDailyOptHeuristicForArea( + const Antares::Data::AreaName& name): + LoadingError( + std::string("Area ") + name.c_str() + + " : simplex daily optimization and use heuristic target == no are not compatible") { } @@ -100,59 +153,64 @@ std::string InvalidParametersForThermalClusters::buildMessage( const std::string startMessage("Conflict between Min Stable Power, Pnom, spinning and capacity " "modulation for the following clusters : "); std::string clusters; - for (const auto& it : clusterNames) + for (const auto& it: clusterNames) { clusters += it.second.c_str(); clusters += ";"; } if (!clusters.empty()) + { clusters.pop_back(); // Remove final semicolon + } return startMessage + clusters; } InvalidParametersForThermalClusters::InvalidParametersForThermalClusters( - const std::map& clusterNames) : - LoadingError(buildMessage(clusterNames)) + const std::map& clusterNames): + LoadingError(buildMessage(clusterNames)) { } -CommandLineArguments::CommandLineArguments(uint errors) : - LoadingError("Invalid command-line arguments provided : " + std::to_string(errors) - + " error(s) found") +CommandLineArguments::CommandLineArguments(uint errors): + LoadingError("Invalid command-line arguments provided : " + std::to_string(errors) + + " error(s) found") { } -IncompatibleStudyModeForAdqPatch::IncompatibleStudyModeForAdqPatch() : - LoadingError("Adequacy Patch can only be used with Economy Simulation Mode") +IncompatibleSimulationModeForAdqPatch::IncompatibleSimulationModeForAdqPatch(): + LoadingError("Adequacy Patch can only be used with Economy Simulation Mode") { } -NoAreaInsideAdqPatchMode::NoAreaInsideAdqPatchMode() : - LoadingError("Minimum one area must be inside adequacy patch mode when using adequacy patch") +NoAreaInsideAdqPatchMode::NoAreaInsideAdqPatchMode(): + LoadingError("Minimum one area must be inside adequacy patch mode when using adequacy patch") { } -IncompatibleHurdleCostCSR::IncompatibleHurdleCostCSR() : - LoadingError("Incompatible options include.hurdleCost and curtailmentSharing.includeHurdleCost") +IncompatibleHurdleCostCSR::IncompatibleHurdleCostCSR(): + LoadingError("Incompatible options include.hurdleCost and curtailmentSharing.includeHurdleCost") { } -AdqPatchDisabledLMR::AdqPatchDisabledLMR() : - LoadingError("Incompatible options LMR disabled and priceTakingOrder equal Dens") +AdqPatchDisabledLMR::AdqPatchDisabledLMR(): + LoadingError("Incompatible options LMR disabled and priceTakingOrder equal Dens") { } -IncompatibleOutputOptions::IncompatibleOutputOptions(const std::string& text) : LoadingError(text) +IncompatibleOutputOptions::IncompatibleOutputOptions(const std::string& text): + LoadingError(text) { } -IncompatibleCO2CostColumns::IncompatibleCO2CostColumns() : - LoadingError("Number of columns for CO2 Cost can be one or same as number of TS in Availability") +IncompatibleCO2CostColumns::IncompatibleCO2CostColumns(): + LoadingError( + "Number of columns for CO2 Cost can be one or same as number of TS in Availability") { } -IncompatibleFuelCostColumns::IncompatibleFuelCostColumns() : - LoadingError("Number of columns for Fuel Cost can be one or same as number of TS in Availability") +IncompatibleFuelCostColumns::IncompatibleFuelCostColumns(): + LoadingError( + "Number of columns for Fuel Cost can be one or same as number of TS in Availability") { } diff --git a/src/libs/antares/exception/UnfeasibleProblemError.cpp b/src/libs/antares/exception/UnfeasibleProblemError.cpp index 433b039b48..c67b30eeb7 100644 --- a/src/libs/antares/exception/UnfeasibleProblemError.cpp +++ b/src/libs/antares/exception/UnfeasibleProblemError.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -30,11 +24,11 @@ namespace Antares { namespace Data { -UnfeasibleProblemError::UnfeasibleProblemError(const std::string& message) : - std::runtime_error(message) +UnfeasibleProblemError::UnfeasibleProblemError(const std::string& message): + std::runtime_error(message) { } } // namespace Data -} // namespace Antares \ No newline at end of file +} // namespace Antares diff --git a/src/libs/antares/exception/antares/exception/AssertionError.hpp b/src/libs/antares/exception/antares/exception/AssertionError.hpp deleted file mode 100644 index 32e53e8a7f..0000000000 --- a/src/libs/antares/exception/antares/exception/AssertionError.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef ANTARES_DATA_ASSERTIONERROR_HPP -#define ANTARES_DATA_ASSERTIONERROR_HPP - -#include - -namespace Antares -{ -namespace Data -{ -class AssertionError : public std::runtime_error -{ -public: - explicit AssertionError(const std::string& message); - - ~AssertionError() noexcept override = default; -}; - -} // namespace Data - -} // namespace Antares - -#endif // ANTARES_DATA_ASSERTIONERROR_HPP \ No newline at end of file diff --git a/src/libs/antares/exception/antares/exception/InitializationError.hpp b/src/libs/antares/exception/antares/exception/InitializationError.hpp deleted file mode 100644 index 0109875fb8..0000000000 --- a/src/libs/antares/exception/antares/exception/InitializationError.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -namespace Antares::Solver::Initialization::Error -{ -class NoResultWriter : public std::runtime_error -{ -public: - NoResultWriter(): std::runtime_error("No result writer") {} -}; -class NoQueueService : public std::runtime_error -{ -public: - NoQueueService(): std::runtime_error("No queue service") {} -}; -} // namespace Antares::Solver::Initialization::Error diff --git a/src/libs/antares/exception/antares/exception/LoadingError.hpp b/src/libs/antares/exception/antares/exception/LoadingError.hpp deleted file mode 100644 index a9b7b0fa30..0000000000 --- a/src/libs/antares/exception/antares/exception/LoadingError.hpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include -#include - -#include -#include -#include "antares/study/fwd.h" - -namespace Antares -{ -namespace Error -{ -class LoadingError : public std::runtime_error -{ -public: - using std::runtime_error::runtime_error; -}; - -class StudyFolderDoesNotExist : public LoadingError -{ -public: - explicit StudyFolderDoesNotExist(const Yuni::String& folder); -}; - -class ReadingStudy : public LoadingError -{ -public: - ReadingStudy(); -}; - -class NoAreas : public LoadingError -{ -public: - NoAreas(); -}; - -class InvalidFileName : public LoadingError -{ -public: - InvalidFileName(); -}; - -class RuntimeInfoInitialization : public LoadingError -{ -public: - RuntimeInfoInitialization(); -}; - -class WritingPID : public LoadingError -{ -public: - explicit WritingPID(const Yuni::String& file); -}; - -class InvalidNumberOfMCYears : public LoadingError -{ -public: - explicit InvalidNumberOfMCYears(uint nbYears); -}; - -class IncompatibleParallelOptions : public LoadingError -{ -public: - IncompatibleParallelOptions(); -}; - -class IncompatibleOptRangeHydroPricing : public LoadingError -{ -public: - IncompatibleOptRangeHydroPricing(); -}; - -class IncompatibleOptRangeUCMode : public LoadingError -{ -public: - IncompatibleOptRangeUCMode(); -}; - -class InvalidOptimizationRange : public LoadingError -{ -public: - InvalidOptimizationRange(); -}; - -class InvalidSimulationMode : public LoadingError -{ -public: - InvalidSimulationMode(); -}; - -class InvalidSolver : public LoadingError -{ -public: - explicit InvalidSolver(const std::string& solver); -}; - -class InvalidStudy : public LoadingError -{ -public: - explicit InvalidStudy(const Yuni::String& study); -}; - -class NoStudyProvided : public LoadingError -{ -public: - NoStudyProvided(); -}; - -class InvalidVersion : public LoadingError -{ -public: - InvalidVersion(const char* version, const char* latest); -}; - -class IncompatibleDailyOptHeuristicForArea : public LoadingError -{ -public: - explicit IncompatibleDailyOptHeuristicForArea(const Antares::Data::AreaName& name); -}; - -class WritingProgressFile : public LoadingError -{ -public: - explicit WritingProgressFile(const Yuni::String& study); -}; - -class InvalidParametersForThermalClusters : public LoadingError -{ -public: - explicit InvalidParametersForThermalClusters(const std::map& clusterNames); - -private: - std::string buildMessage(const std::map& clusterNames) const; -}; - -class CommandLineArguments : public LoadingError -{ -public: - explicit CommandLineArguments(uint errors); -}; - -class IncompatibleStudyModeForAdqPatch : public LoadingError -{ -public: - IncompatibleStudyModeForAdqPatch(); -}; - -class NoAreaInsideAdqPatchMode : public LoadingError -{ -public: - NoAreaInsideAdqPatchMode(); -}; - -class IncompatibleHurdleCostCSR : public LoadingError -{ -public: - IncompatibleHurdleCostCSR(); -}; - -class AdqPatchDisabledLMR : public LoadingError -{ -public: - AdqPatchDisabledLMR(); -}; - -class IncompatibleOutputOptions : public LoadingError -{ -public: - explicit IncompatibleOutputOptions(const std::string& text); -}; - -class IncompatibleCO2CostColumns : public LoadingError -{ -public: - IncompatibleCO2CostColumns(); -}; - -class IncompatibleFuelCostColumns : public LoadingError -{ -public: - IncompatibleFuelCostColumns(); -}; - -} // namespace Error -} // namespace Antares diff --git a/src/libs/antares/exception/antares/exception/UnfeasibleProblemError.hpp b/src/libs/antares/exception/antares/exception/UnfeasibleProblemError.hpp deleted file mode 100644 index 82949b5461..0000000000 --- a/src/libs/antares/exception/antares/exception/UnfeasibleProblemError.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef ANTARES_DATA_UNFEASIBLEPROBLEMERROR_HPP -#define ANTARES_DATA_UNFEASIBLEPROBLEMERROR_HPP - -#include - -namespace Antares -{ -namespace Data -{ -class UnfeasibleProblemError : public std::runtime_error -{ -public: - explicit UnfeasibleProblemError(const std::string& message); - - ~UnfeasibleProblemError() noexcept override = default; -}; - -} // namespace Data - -} // namespace Antares - -#endif // ANTARES_DATA_UNFEASIBLEPROBLEMERROR_HPP \ No newline at end of file diff --git a/src/libs/antares/exception/include/antares/exception/AssertionError.hpp b/src/libs/antares/exception/include/antares/exception/AssertionError.hpp new file mode 100644 index 0000000000..7fafaeffc3 --- /dev/null +++ b/src/libs/antares/exception/include/antares/exception/AssertionError.hpp @@ -0,0 +1,42 @@ +// /* +// ** Copyright 2007-2024, RTE (https://www.rte-france.com) +// ** See AUTHORS.txt +// ** SPDX-License-Identifier: MPL-2.0 +// ** This file is part of Antares-Simulator, +// ** Adequacy and Performance assessment for interconnected energy networks. +// ** +// ** Antares_Simulator is free software: you can redistribute it and/or modify +// ** it under the terms of the Mozilla Public Licence 2.0 as published by +// ** the Mozilla Foundation, either version 2 of the License, or +// ** (at your option) any later version. +// ** +// ** Antares_Simulator 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 +// ** Mozilla Public Licence 2.0 for more details. +// ** +// ** You should have received a copy of the Mozilla Public Licence 2.0 +// ** along with Antares_Simulator. If not, see . +// * +#ifndef ANTARES_DATA_ASSERTIONERROR_HPP +#define ANTARES_DATA_ASSERTIONERROR_HPP + +#include + +namespace Antares +{ +namespace Data +{ +class AssertionError: public std::runtime_error +{ +public: + explicit AssertionError(const std::string& message); + + ~AssertionError() noexcept override = default; +}; + +} // namespace Data + +} // namespace Antares + +#endif // ANTARES_DATA_ASSERTIONERROR_HPP diff --git a/src/libs/antares/exception/include/antares/exception/InitializationError.hpp b/src/libs/antares/exception/include/antares/exception/InitializationError.hpp new file mode 100644 index 0000000000..4ec88fdab5 --- /dev/null +++ b/src/libs/antares/exception/include/antares/exception/InitializationError.hpp @@ -0,0 +1,36 @@ +// /* +// ** Copyright 2007-2024, RTE (https://www.rte-france.com) +// ** See AUTHORS.txt +// ** SPDX-License-Identifier: MPL-2.0 +// ** This file is part of Antares-Simulator, +// ** Adequacy and Performance assessment for interconnected energy networks. +// ** +// ** Antares_Simulator is free software: you can redistribute it and/or modify +// ** it under the terms of the Mozilla Public Licence 2.0 as published by +// ** the Mozilla Foundation, either version 2 of the License, or +// ** (at your option) any later version. +// ** +// ** Antares_Simulator 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 +// ** Mozilla Public Licence 2.0 for more details. +// ** +// ** You should have received a copy of the Mozilla Public Licence 2.0 +// ** along with Antares_Simulator. If not, see . +// * + +#pragma once + +#include + +namespace Antares::Solver::Initialization::Error +{ +class NoQueueService: public std::runtime_error +{ +public: + NoQueueService(): + std::runtime_error("No queue service") + { + } +}; +} // namespace Antares::Solver::Initialization::Error diff --git a/src/libs/antares/exception/include/antares/exception/LoadingError.hpp b/src/libs/antares/exception/include/antares/exception/LoadingError.hpp new file mode 100644 index 0000000000..c79b1a791e --- /dev/null +++ b/src/libs/antares/exception/include/antares/exception/LoadingError.hpp @@ -0,0 +1,222 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: MPL-2.0 +*/ + +#pragma once + +#include +#include +#include + +#include +#include + +#include "antares/study/fwd.h" + +namespace Antares +{ +namespace Error +{ +class LoadingError: public std::runtime_error +{ +public: + using std::runtime_error::runtime_error; +}; + +class StudyFolderDoesNotExist: public LoadingError +{ +public: + explicit StudyFolderDoesNotExist(const Yuni::String& folder); +}; + +class ReadingStudy: public LoadingError +{ +public: + ReadingStudy(); +}; + +class NoAreas: public LoadingError +{ +public: + NoAreas(); +}; + +class InvalidFileName: public LoadingError +{ +public: + InvalidFileName(); +}; + +class RuntimeInfoInitialization: public LoadingError +{ +public: + RuntimeInfoInitialization(); +}; + +class WritingPID: public LoadingError +{ +public: + explicit WritingPID(const Yuni::String& file); +}; + +class IncompatibleParallelOptions: public LoadingError +{ +public: + IncompatibleParallelOptions(); +}; + +class IncompatibleMILPWithoutOrtools: public LoadingError +{ +public: + IncompatibleMILPWithoutOrtools(); +}; + +class IncompatibleMILPOrtoolsSolver: public LoadingError +{ +public: + IncompatibleMILPOrtoolsSolver(); +}; + +class IncompatibleOptRangeHydroPricing: public LoadingError +{ +public: + IncompatibleOptRangeHydroPricing(); +}; + +class IncompatibleOptRangeUCMode: public LoadingError +{ +public: + IncompatibleOptRangeUCMode(); +}; + +class InvalidOptimizationRange: public LoadingError +{ +public: + InvalidOptimizationRange(); +}; + +class InvalidSimulationMode: public LoadingError +{ +public: + InvalidSimulationMode(); +}; + +class InvalidSolver: public LoadingError +{ +public: + explicit InvalidSolver(const std::string& solver, const std::string& availableSolverList); +}; + +class InvalidSolverSpecificParameters: public LoadingError +{ +public: + explicit InvalidSolverSpecificParameters(const std::string& solver, + const std::string& specificParameters); +}; + +class InvalidStudy: public LoadingError +{ +public: + explicit InvalidStudy(const Yuni::String& study); +}; + +class NoStudyProvided: public LoadingError +{ +public: + NoStudyProvided(); +}; + +class InvalidVersion: public LoadingError +{ +public: + InvalidVersion(const std::string& version, const std::string& latest); +}; + +class IncompatibleDailyOptHeuristicForArea: public LoadingError +{ +public: + explicit IncompatibleDailyOptHeuristicForArea(const Antares::Data::AreaName& name); +}; + +class InvalidParametersForThermalClusters: public LoadingError +{ +public: + explicit InvalidParametersForThermalClusters(const std::map& clusterNames); + +private: + std::string buildMessage(const std::map& clusterNames) const; +}; + +class CommandLineArguments: public LoadingError +{ +public: + explicit CommandLineArguments(uint errors); +}; + +class IncompatibleSimulationModeForAdqPatch: public LoadingError +{ +public: + IncompatibleSimulationModeForAdqPatch(); +}; + +class NoAreaInsideAdqPatchMode: public LoadingError +{ +public: + NoAreaInsideAdqPatchMode(); +}; + +class IncompatibleHurdleCostCSR: public LoadingError +{ +public: + IncompatibleHurdleCostCSR(); +}; + +class AdqPatchDisabledLMR: public LoadingError +{ +public: + AdqPatchDisabledLMR(); +}; + +class IncompatibleOutputOptions: public LoadingError +{ +public: + explicit IncompatibleOutputOptions(const std::string& text); +}; + +class IncompatibleCO2CostColumns: public LoadingError +{ +public: + IncompatibleCO2CostColumns(); +}; + +class IncompatibleFuelCostColumns: public LoadingError +{ +public: + IncompatibleFuelCostColumns(); +}; + +} // namespace Error +} // namespace Antares diff --git a/src/libs/antares/exception/include/antares/exception/UnfeasibleProblemError.hpp b/src/libs/antares/exception/include/antares/exception/UnfeasibleProblemError.hpp new file mode 100644 index 0000000000..27586f9f7c --- /dev/null +++ b/src/libs/antares/exception/include/antares/exception/UnfeasibleProblemError.hpp @@ -0,0 +1,48 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: MPL-2.0 +*/ +#ifndef ANTARES_DATA_UNFEASIBLEPROBLEMERROR_HPP +#define ANTARES_DATA_UNFEASIBLEPROBLEMERROR_HPP + +#include + +namespace Antares +{ +namespace Data +{ +class UnfeasibleProblemError: public std::runtime_error +{ +public: + explicit UnfeasibleProblemError(const std::string& message); + + ~UnfeasibleProblemError() noexcept override = default; +}; + +} // namespace Data + +} // namespace Antares + +#endif // ANTARES_DATA_UNFEASIBLEPROBLEMERROR_HPP diff --git a/src/libs/antares/fatal-error.h b/src/libs/antares/fatal-error.h deleted file mode 100644 index bb87ab21bc..0000000000 --- a/src/libs/antares/fatal-error.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_FATAL_ERROR_H__ -#define __ANTARES_LIB_FATAL_ERROR_H__ - -#include - -namespace Antares { - -/*! -** \brief A generic exception for errors that should end the program. -*/ -class FatalError : public std::runtime_error -{ -public: - using std::runtime_error::runtime_error; -}; - -} - -#endif // __ANTARES_LIB_FATAL_ERROR_H__ diff --git a/src/libs/antares/file-tree-study-loader/CMakeLists.txt b/src/libs/antares/file-tree-study-loader/CMakeLists.txt new file mode 100644 index 0000000000..08c2065dc3 --- /dev/null +++ b/src/libs/antares/file-tree-study-loader/CMakeLists.txt @@ -0,0 +1,30 @@ +set(PROJ file-tree-study-loader) +set(SRC_PROJ + include/antares/file-tree-study-loader/FileTreeStudyLoader.h + FileTreeStudyLoader.cpp +) +source_group("file-study-tree-loader" FILES ${SRC_PROJ}) + +add_library(${PROJ}) +add_library(Antares::${PROJ} ALIAS ${PROJ}) +target_sources(${PROJ} + PRIVATE + ${SRC_PROJ} +) + +target_link_libraries(${PROJ} + PUBLIC + Antares::study-loader + Antares::result_writer + Antares::study + Antares::application +) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/file-tree-study-loader/FileTreeStudyLoader.cpp b/src/libs/antares/file-tree-study-loader/FileTreeStudyLoader.cpp new file mode 100644 index 0000000000..8ff1c2730d --- /dev/null +++ b/src/libs/antares/file-tree-study-loader/FileTreeStudyLoader.cpp @@ -0,0 +1,72 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/file-tree-study-loader/FileTreeStudyLoader.h" + +#include +#include + +#include "antares/application/application.h" + +namespace Antares +{ +FileTreeStudyLoader::FileTreeStudyLoader(std::filesystem::path study_path): + study_path_{std::move(study_path)} +{ +} + +namespace +{ +/** + * @brief Prepares arguments for the Antares Solver application. + * + * This function prepares the arguments required by the Antares Solver application. + * It takes a span of char pointers and a string_view representing the study path. + * The function creates copies of the required arguments and stores them in a vector. + * The original char pointers in the span are updated to point to the newly created copies. + * Lifetime of values inside argv is determined be the content of the returned vector + * + * @param argv A span of char pointers to be filled with the prepared arguments. + * @param study_path A string_view representing the study path. + * @return std::vector A vector of strings containing the prepared arguments. + */ +void prepareArgs(std::array& argv, std::span data) +{ + argv[0] = data[0].data(); + argv[1] = data[1].data(); +} +} // namespace + +std::unique_ptr FileTreeStudyLoader::load() const +{ + using namespace std::literals::string_literals; + Antares::Solver::Application application; + constexpr unsigned int argc = 2; + std::array keep_alive{""s, study_path_.string()}; + std::array argv; + prepareArgs(argv, keep_alive); + application.prepare(argc, argv.data()); + + return application.acquireStudy(); +} + +} // namespace Antares diff --git a/src/libs/antares/file-tree-study-loader/include/antares/file-tree-study-loader/FileTreeStudyLoader.h b/src/libs/antares/file-tree-study-loader/include/antares/file-tree-study-loader/FileTreeStudyLoader.h new file mode 100644 index 0000000000..7b46a95c3a --- /dev/null +++ b/src/libs/antares/file-tree-study-loader/include/antares/file-tree-study-loader/FileTreeStudyLoader.h @@ -0,0 +1,63 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include + +#include "antares/study-loader/IStudyLoader.h" + +namespace Antares +{ +namespace Data +{ +class Study; +} + +/** + * @class FileTreeStudyLoader + * @brief A class to load studies from the file tree. + * + * This class is responsible for loading studies from files in file system. + * + * @note This class inherits from the IStudyLoader interface. + */ +class FileTreeStudyLoader: public IStudyLoader +{ +public: + explicit FileTreeStudyLoader(std::filesystem::path study_path); + ~FileTreeStudyLoader() override = default; + + /** + * @brief Loads a study from the file tree. + * + * This function prepares the arguments required by the Antares Solver application and then + * calls the application's prepare method. + * It then returns the study loaded by the application. + * + * @return std::shared_ptr A shared_ptr to the loaded Study object. + */ + [[nodiscard]] std::unique_ptr load() const override; + +private: + std::filesystem::path study_path_; +}; +} // namespace Antares diff --git a/src/libs/antares/Enum.hpp b/src/libs/antares/include/antares/antares/Enum.hpp similarity index 78% rename from src/libs/antares/Enum.hpp rename to src/libs/antares/include/antares/antares/Enum.hpp index 1e74ed1352..dcc6ca20e5 100644 --- a/src/libs/antares/Enum.hpp +++ b/src/libs/antares/include/antares/antares/Enum.hpp @@ -5,8 +5,8 @@ ** This file is part of Antares_Simulator. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** ** There are special exceptions to the terms and conditions of the @@ -17,12 +17,12 @@ ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** SPDX-License-Identifier: MPL-2.0 */ #ifndef ANTARES_DATA_ENUM_HPP #define ANTARES_DATA_ENUM_HPP @@ -65,6 +65,6 @@ inline typename std::enable_if::value, std::ostream&>::type oper } // namespace Antares -#include +#include -#endif // ANTARES_DATA_ENUM_HPP \ No newline at end of file +#endif // ANTARES_DATA_ENUM_HPP diff --git a/src/libs/antares/include/antares/antares/Enum.hxx b/src/libs/antares/include/antares/antares/Enum.hxx new file mode 100644 index 0000000000..787061c390 --- /dev/null +++ b/src/libs/antares/include/antares/antares/Enum.hxx @@ -0,0 +1,75 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef ANTARES_DATA_ENUM_HXX +#define ANTARES_DATA_ENUM_HXX + +#include +#include + +#include +#include +#include "antares/antares/Enum.hpp" + +namespace Antares::Data::Enum +{ +template +E fromString(const std::string& name) +{ + const auto& names = getNames(); + const auto& it = std::find(names.begin(), names.end(), name); + if (it == names.end()) + { + throw AssertionError("Unexpected " + stdcxx::simpleClassName() + " name " + name); + } + + return static_cast(it - names.begin()); +} + +template +std::string toString(const E& value) +{ + auto index = static_cast(value); + const auto& names = getNames(); + if (index >= names.size()) + { + throw AssertionError("Unexpected " + stdcxx::simpleClassName() + " value " + + std::to_string(index)); + } + return *(names.begin() + index); +} + +template +std::list enumList() +{ + std::list result; + const auto& names = getNames(); + for (auto name: names) + { + result.push_back(fromString(name)); + } + + return result; +} + +} // namespace Antares::Data::Enum + +#endif // ANTARES_DATA_ENUM_HXX diff --git a/src/libs/antares/include/antares/antares/antares.h b/src/libs/antares/include/antares/antares/antares.h new file mode 100644 index 0000000000..346e0e95b8 --- /dev/null +++ b/src/libs/antares/include/antares/antares/antares.h @@ -0,0 +1,29 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_H__ +#define __ANTARES_H__ + +#include +#include + +#define foreach YUNI_FOREACH + +#endif // __ANTARES_H__ diff --git a/src/libs/antares/include/antares/antares/constants.h b/src/libs/antares/include/antares/antares/constants.h new file mode 100644 index 0000000000..c29e81c1ef --- /dev/null +++ b/src/libs/antares/include/antares/antares/constants.h @@ -0,0 +1,73 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: MPL-2.0 +*/ +#ifndef __ANTARES_LIBS_CONSTANTS_H__ +#define __ANTARES_LIBS_CONSTANTS_H__ + +#include + +const unsigned int HOURS_PER_DAY = 24; + +const unsigned int MONTHS_PER_YEAR = 12; +const unsigned int WEEKS_PER_YEAR = 53; +const unsigned int DAYS_PER_YEAR = 365; +const unsigned int HOURS_PER_YEAR = 8760; + +namespace Antares::Constants +{ +extern const std::array daysPerMonth; +extern const unsigned int nbHoursInAWeek; +} // namespace Antares::Constants + +enum AntaresConstants +{ + ant_k_area_name_max_length = 128, + ant_k_cluster_name_max_length = 128, + ant_k_constraint_name_max_length = 128, +}; + +#endif /* __ANTARES_LIBS_CONSTANTS_H__ */ diff --git a/src/libs/antares/include/antares/antares/fatal-error.h b/src/libs/antares/include/antares/antares/fatal-error.h new file mode 100644 index 0000000000..279dc170f8 --- /dev/null +++ b/src/libs/antares/include/antares/antares/fatal-error.h @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include + +namespace Antares +{ + +/*! +** \brief A generic exception for errors that should end the program. +*/ +class FatalError: public std::runtime_error +{ +public: + using std::runtime_error::runtime_error; +}; + +} // namespace Antares diff --git a/src/libs/antares/include/antares/antares/version.h b/src/libs/antares/include/antares/antares/version.h new file mode 100644 index 0000000000..706c6de13c --- /dev/null +++ b/src/libs/antares/include/antares/antares/version.h @@ -0,0 +1,38 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_VERSION_H__ +#define __ANTARES_LIBS_VERSION_H__ + +namespace Antares +{ +/*! +** \brief Get the version of Antares in a C-string format +*/ +const char* VersionToCString(); + +/*! +** \brief Print the version of Antares on the standard output +*/ +void PrintVersionToStdCout(); + +} // namespace Antares + +#endif // __ANTARES_LIBS_VERSION_H__ diff --git a/src/libs/antares/inifile/CMakeLists.txt b/src/libs/antares/inifile/CMakeLists.txt index c324e4c9f9..089591f002 100644 --- a/src/libs/antares/inifile/CMakeLists.txt +++ b/src/libs/antares/inifile/CMakeLists.txt @@ -1,8 +1,8 @@ set(SRC_INI - antares/inifile/inifile.h - antares/inifile/inifile.hxx + include/antares/inifile/inifile.h + include/antares/inifile/inifile.hxx inifile.cpp - ) +) source_group("misc\\inifile" FILES ${SRC_INI}) @@ -12,13 +12,19 @@ add_library(inifile add_library(Antares::inifile ALIAS inifile) target_link_libraries(inifile + PUBLIC + yuni-static-core PRIVATE io logs - yuni-static-core - ) + Boost::headers +) target_include_directories(inifile PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ) \ No newline at end of file + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/inifile/antares/inifile/inifile.hxx b/src/libs/antares/inifile/antares/inifile/inifile.hxx deleted file mode 100644 index d72c458658..0000000000 --- a/src/libs/antares/inifile/antares/inifile/inifile.hxx +++ /dev/null @@ -1,152 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_INIFILE_HXX__ -#define __ANTARES_LIBS_INIFILE_HXX__ - -namespace Antares -{ -inline bool IniFile::loaded() const -{ - return not pFilename.empty(); -} - -inline bool IniFile::empty() const -{ - return not firstSection; -} - -inline IniFile::Section::Section() : firstProperty(nullptr), lastProperty(nullptr), next(nullptr) -{ -} - -inline IniFile::Section::Section(const AnyString& name) : - name(name), firstProperty(nullptr), lastProperty(nullptr), next(nullptr) -{ -} - -template -IniFile::Property::Property(const AnyString& key, const U& value) : - key(key), value(value), next(nullptr) -{ - this->key.trim(); - this->key.toLower(); - this->value.trim(); -} - -inline bool IniFile::Section::empty() const -{ - return (NULL == firstProperty); -} - -template -IniFile::Property* IniFile::Section::add(const AnyString& key, const U& value) -{ - auto* p = new Property(key, value); - if (!lastProperty) - firstProperty = p; - else - lastProperty->next = p; - lastProperty = p; - return p; -} - -template -IniFile::Property* IniFile::Section::add(const AnyString& key, const std::optional& value) -{ - if (value.has_value()) - return add(key, value.value()); - return nullptr; -} - -template -inline U IniFile::Section::read(const StringT& key, const U& defValue) const -{ - auto* property = find(key); - return (property ? property->value.template to() : defValue); -} - -inline IniFile::Section* IniFile::addSection(const AnyString& name) -{ - return add(new Section(name)); -} - -inline const YString& IniFile::filename() const -{ - return pFilename; -} - -template -void IniFile::each(const CallbackT& callback) -{ - for (auto* section = firstSection; section; section = section->next) - callback(*section); -} - -template -void IniFile::each(const CallbackT& callback) const -{ - for (auto* section = firstSection; section; section = section->next) - callback(*section); -} - -template -void IniFile::Section::each(const CallbackT& callback) -{ - for (auto* property = firstProperty; property; property = property->next) - callback(*property); -} - -template -void IniFile::Section::each(const CallbackT& callback) const -{ - for (auto* property = firstProperty; property; property = property->next) - callback(*property); -} - -template -void IniFile::properties(const CallbackT& callback) -{ - for (auto* section = firstSection; section; section = section->next) - { - for (auto* property = section->firstProperty; property; property = property->next) - callback(*property); - } -} - -template -void IniFile::properties(const CallbackT& callback) const -{ - for (auto* section = firstSection; section; section = section->next) - { - for (auto* property = section->firstProperty; property; property = property->next) - callback(*property); - } -} - -} // namespace Antares - -#endif // __ANTARES_LIBS_INIFILE_HXX__ diff --git a/src/libs/antares/inifile/antares/inifile/inifile.h b/src/libs/antares/inifile/include/antares/inifile/inifile.h similarity index 81% rename from src/libs/antares/inifile/antares/inifile/inifile.h rename to src/libs/antares/inifile/include/antares/inifile/inifile.h index 51e7df3465..22dc679b5e 100644 --- a/src/libs/antares/inifile/antares/inifile/inifile.h +++ b/src/libs/antares/inifile/include/antares/inifile/inifile.h @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#ifndef __ANTARES_LIBS_INIFILE_INIFILE_H__ -#define __ANTARES_LIBS_INIFILE_INIFILE_H__ +#pragma once + +#include #include #include -#include namespace Antares { @@ -48,14 +42,13 @@ class IniFile final class Property final { public: - Property(); + Property() = default; explicit Property(const AnyString& key); template Property(const AnyString& key, const U& value); - ~Property(); + ~Property() = default; - template - void saveToStream(StreamT& file, uint64_t& written) const; + void saveToStream(std::ostream& file, uint64_t& written) const; public: //! The key @@ -63,7 +56,7 @@ class IniFile final //! Its associated value YString value; //! The next value - Property* next; + Property* next = nullptr; }; /*! @@ -73,7 +66,7 @@ class IniFile final class Section final { public: - Section(); + Section() = default; explicit Section(const AnyString& name); ~Section(); @@ -86,8 +79,9 @@ class IniFile final template Property* add(const AnyString& key, const std::optional& value); - template - void saveToStream(StreamT& file, uint64_t& written) const; + void add(const Property& property); + + void saveToStream(std::ostream& file, uint64_t& written) const; Property* find(const AnyString& key); const Property* find(const AnyString& key) const; @@ -157,11 +151,11 @@ class IniFile final //! The name of the section Yuni::ShortString256 name; //! The first property of the section - IniFile::Property* firstProperty; + IniFile::Property* firstProperty = nullptr; //! The last property of the section - IniFile::Property* lastProperty; + IniFile::Property* lastProperty = nullptr; //! The next section - Section* next; + Section* next = nullptr; }; // class Section @@ -171,11 +165,11 @@ class IniFile final /*! ** \brief Default Constructor */ - IniFile(); + IniFile() = default; /*! ** \brief Load an INI file */ - explicit IniFile(const AnyString& filename); + explicit IniFile(const std::filesystem::path& filename); /*! ** \brief Destructor */ @@ -200,17 +194,22 @@ class IniFile final ** \param filename Filename to load ** \return True if the operation succeeded, false otherwise */ - bool open(const AnyString& filename, bool warnings = true); + bool open(const std::string& filename, bool warnings = true); + + bool open(const std::filesystem::path& filename, bool warnings = true); + + bool readStream(std::istream& in_stream); /*! ** \brief Save the entire INI into a file */ bool save(const AnyString& filename) const; + void saveToStream(std::ostream&, uint64_t&) const; - void saveToString(std::string& str) const; + std::string toString() const; //! Get the last filename saved or loaded - const YString& filename() const; + const std::string& filename() const; //@} //! \name Sections @@ -310,10 +309,8 @@ class IniFile final //@} public: - //! The first section - Section* firstSection; - //! The last section - Section* lastSection; + Section* firstSection = nullptr; + Section* lastSection = nullptr; private: /*! @@ -322,12 +319,10 @@ class IniFile final ** \internal This variable to keep const-correctness for the ** public API (cf save). */ - mutable YString pFilename; + std::string filename_; }; // class IniFile } // namespace Antares #include "inifile.hxx" - -#endif /* __ANTARES_LIBS_INIFILE_INIFILE_H__ */ diff --git a/src/libs/antares/inifile/include/antares/inifile/inifile.hxx b/src/libs/antares/inifile/include/antares/inifile/inifile.hxx new file mode 100644 index 0000000000..20498c3ee2 --- /dev/null +++ b/src/libs/antares/inifile/include/antares/inifile/inifile.hxx @@ -0,0 +1,158 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +namespace Antares +{ +inline bool IniFile::loaded() const +{ + return not filename_.empty(); +} + +inline bool IniFile::empty() const +{ + return not firstSection; +} + +inline IniFile::Section::Section(const AnyString& name): + name(name) +{ +} + +template +IniFile::Property::Property(const AnyString& key, const U& value): + key(key), + value(value) +{ + this->key.trim(); + this->key.toLower(); + this->value.trim(); +} + +inline bool IniFile::Section::empty() const +{ + return !firstProperty; +} + +template +IniFile::Property* IniFile::Section::add(const AnyString& key, const U& value) +{ + auto* p = new Property(key, value); + if (!lastProperty) + { + firstProperty = p; + } + else + { + lastProperty->next = p; + } + lastProperty = p; + return p; +} + +template +IniFile::Property* IniFile::Section::add(const AnyString& key, const std::optional& value) +{ + if (value.has_value()) + { + return add(key, value.value()); + } + return nullptr; +} + +template +inline U IniFile::Section::read(const StringT& key, const U& defValue) const +{ + auto* property = find(key); + return (property ? property->value.template to() : defValue); +} + +inline IniFile::Section* IniFile::addSection(const AnyString& name) +{ + return add(new Section(name)); +} + +inline const std::string& IniFile::filename() const +{ + return filename_; +} + +template +void IniFile::each(const CallbackT& callback) +{ + for (auto* section = firstSection; section; section = section->next) + { + callback(*section); + } +} + +template +void IniFile::each(const CallbackT& callback) const +{ + for (auto* section = firstSection; section; section = section->next) + { + callback(*section); + } +} + +template +void IniFile::Section::each(const CallbackT& callback) +{ + for (auto* property = firstProperty; property; property = property->next) + { + callback(*property); + } +} + +template +void IniFile::Section::each(const CallbackT& callback) const +{ + for (auto* property = firstProperty; property; property = property->next) + { + callback(*property); + } +} + +template +void IniFile::properties(const CallbackT& callback) +{ + for (auto* section = firstSection; section; section = section->next) + { + for (auto* property = section->firstProperty; property; property = property->next) + { + callback(*property); + } + } +} + +template +void IniFile::properties(const CallbackT& callback) const +{ + for (auto* section = firstSection; section; section = section->next) + { + for (auto* property = section->firstProperty; property; property = property->next) + { + callback(*property); + } + } +} + +} // namespace Antares diff --git a/src/libs/antares/inifile/inifile.cpp b/src/libs/antares/inifile/inifile.cpp index 7c59dcaf7e..8cfa6b9607 100644 --- a/src/libs/antares/inifile/inifile.cpp +++ b/src/libs/antares/inifile/inifile.cpp @@ -1,157 +1,74 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/inifile/inifile.h" -#include -#include +#include +#include #include +#include -using namespace Yuni; +#include -namespace Antares -{ -static inline IniFile::Section* AnalyzeIniLine(const String& pFilename, - IniFile* d, - IniFile::Section* section, - char* line, - uint64_t& read) -{ - enum Type - { - typeUnknown = 0, - typeSection = 1, - typeProperty = 2, - }; - - uint bytesRead = 0; - Type type = typeUnknown; - char* p = line; - const char* key = line; - const char* value = nullptr; - - while ('\0' != *p) - { - ++bytesRead; - if (typeUnknown == type) - { - if ('[' == *p) - { - type = typeSection; - ++p; - value = p; - continue; - } - else if ('=' == *p) - { - type = typeProperty; - *p = '\0'; - ++p; - value = p; - continue; - } - } - else - { - if (typeSection == type) - { - if (']' == *p) - { - *p = '\0'; - break; - } - } - else - { - if (('\n' == *p) - or ('\r' == *p)) // or (*p == '/' and ('/' == *(p + 1) or '*' == *(p + 1)))) - { - *p = '\0'; - break; - } - } - } - ++p; - } +#include +#include - read += bytesRead; +using namespace Yuni; - if (typeProperty == type) - { - if (section and *value != '\0' and value) - section->add(key, value); - return section; - } - if (typeSection == type and value and '\0' != *value) - return d->addSection(value); +namespace fs = std::filesystem; - CString<255, false> k = key; - k.trim(" \r\n\t"); - if (not k.empty() and k[0] != ';' and k[0] != '#') - { - logs.error() << pFilename << ": invalid INI format. Got a key without any value '" << k - << "'"; - } - return section; -} +namespace Antares +{ -IniFile::Property::Property(const AnyString& key) : key(key), next(nullptr) +IniFile::Property::Property(const AnyString& key): + key(key) { this->key.trim(); this->key.toLower(); } -IniFile::Property::Property() : next(nullptr) +inline void IniFile::Property::saveToStream(std::ostream& stream_out, uint64_t& written) const { + written += key.size() + value.size() + 4; + stream_out << key << " = " << value << '\n'; } -IniFile::Property::~Property() +void IniFile::Section::add(const Property& property) { + add(property.key, property.value); } -template -inline void IniFile::Property::saveToStream(StreamT& file, uint64_t& written) const -{ - written += key.size() + value.size() + 4; - file << key << " = " << value << '\n'; -} - -template -void IniFile::Section::saveToStream(StreamT& file, uint64_t& written) const +void IniFile::Section::saveToStream(std::ostream& stream_out, uint64_t& written) const { if (!firstProperty) + { return; - file << '[' << name << "]\n"; + } + stream_out << '[' << name << "]\n"; written += 4 /* []\n\n */ + name.size(); - for (auto* property = firstProperty; property; property = property->next) - property->saveToStream(file, written); + each([&stream_out, &written](const IniFile::Property& p) + { p.saveToStream(stream_out, written); }); - file << '\n'; + stream_out << '\n'; } IniFile::Section::~Section() @@ -169,11 +86,7 @@ IniFile::Section::~Section() } } -IniFile::IniFile() : firstSection(nullptr), lastSection(nullptr) -{ -} - -IniFile::IniFile(const AnyString& filename) : firstSection(nullptr), lastSection(nullptr) +IniFile::IniFile(const fs::path& filename) { open(filename); } @@ -230,7 +143,9 @@ void IniFile::clear() uint IniFile::Section::size() const { if (!firstProperty) + { return 0; + } uint count = 0; auto* p = firstProperty; do @@ -241,80 +156,148 @@ uint IniFile::Section::size() const return count; } -bool IniFile::open(const AnyString& filename, bool warnings) +static bool isStartingSection(std::string line) { - // clear - clear(); - pFilename = filename; + boost::trim(line); + return line.starts_with("[") && line.ends_with("]"); +} + +static std::string getSectionName(const std::string& line) +{ + std::vector splitLine; + boost::split(splitLine, line, boost::is_any_of("[]")); + return splitLine[1]; +} + +static bool isProperty(std::string_view line) +{ + return std::ranges::count(line, '=') == 1; +} + +static IniFile::Property getProperty(std::string line) +{ + boost::trim(line); + std::vector splitLine; + boost::split(splitLine, line, boost::is_any_of("=")); + + return IniFile::Property(splitLine[0], splitLine[1]); +} - // Load the file - IO::File::Stream file; - if (file.open(filename)) +static bool isComment(std::string line) +{ + boost::trim_left(line); + return line.starts_with("#") || line.starts_with(";"); +} + +bool isEmpty(std::string line) +{ + boost::trim(line); + return line.empty(); +} + +bool IniFile::readStream(std::istream& in_stream) +{ + std::string line; + IniFile::Section* currentSection(nullptr); + uint64_t read = 0; + while (std::getline(in_stream, line)) { - enum + read += line.size(); + if (isStartingSection(line)) + { + currentSection = addSection(getSectionName(line)); + continue; + } + + if (isProperty(line)) + { + // Note : if a property not in a section, it's simply skipped + if (currentSection) + { + currentSection->add(getProperty(line)); + } + continue; + } + + if (isComment(line) || isEmpty(line)) { - lineHardLimit = 2048 - }; - auto* line = new char[lineHardLimit]; + continue; + } - IniFile::Section* lastSection = nullptr; - uint64_t read = 0; + logs.error() << "INI content : unknown format for line '" << line << "'"; + return false; + } + if (read) + { + Statistics::HasReadFromDisk(read); + } - // analyzing each line - while (file.readline(line, lineHardLimit)) - lastSection = AnalyzeIniLine(pFilename, this, lastSection, line, read); + return true; +} - delete[] line; +bool IniFile::open(const std::string& filename, bool warnings) +{ + fs::path filepath = filename; + return open(filepath, warnings); +} - if (read) - Statistics::HasReadFromDisk(read); +bool IniFile::open(const fs::path& filename, bool warnings) +{ + clear(); + filename_ = filename.string(); // storing filename for further use + + if (std::ifstream file(filename); file.is_open()) + { + if (!readStream(file)) + { + logs.error() << "Invalid INI file : " << filename; + return false; + } return true; } - // Error if (warnings) + { logs.error() << "I/O error: " << filename << ": Impossible to read the file"; - pFilename.clear(); + } return false; } -void IniFile::saveToString(std::string& str) const +void IniFile::saveToStream(std::ostream& stream_out, uint64_t& written) const { - uint64_t written = 0; - std::ostringstream ostream; - // save all sections - for (auto* section = firstSection; section; section = section->next) - section->saveToStream(ostream, written); + each([&stream_out, &written](const IniFile::Section& s) + { s.saveToStream(stream_out, written); }); if (written != 0) + { Statistics::HasWrittenToDisk(written); + } +} - str = ostream.str(); +std::string IniFile::toString() const +{ + uint64_t written = 0; + std::ostringstream ostream; + + this->saveToStream(ostream, written); + + return ostream.str(); } bool IniFile::save(const AnyString& filename) const { logs.debug() << " :: writing `" << filename << '`'; - IO::File::Stream f; - if (f.openRW(filename)) + + std::ofstream of(filename.to()); + if (of.good()) { - pFilename = filename; uint64_t written = 0; - - // save all sections - for (auto* section = firstSection; section; section = section->next) - section->saveToStream(f, written); - - if (written != 0) - Statistics::HasWrittenToDisk(written); + this->saveToStream(of, written); return true; } - else - { - pFilename.clear(); - logs.error() << "I/O error: " << filename << ": Impossible to write the file"; - return false; - } + + logs.error() << "I/O error: " << filename << ": Impossible to write the file"; + return false; } IniFile::Property* IniFile::Section::find(const AnyString& key) @@ -322,7 +305,9 @@ IniFile::Property* IniFile::Section::find(const AnyString& key) for (auto* property = firstProperty; property; property = property->next) { if (property->key == key) + { return property; + } } return nullptr; } @@ -332,7 +317,9 @@ const IniFile::Property* IniFile::Section::find(const AnyString& key) const for (auto* property = firstProperty; property; property = property->next) { if (property->key == key) + { return property; + } } return nullptr; } @@ -342,7 +329,9 @@ IniFile::Section* IniFile::find(const AnyString& name) for (auto* section = firstSection; section; section = section->next) { if (section->name == name) + { return section; + } } return nullptr; } @@ -352,7 +341,9 @@ const IniFile::Section* IniFile::find(const AnyString& name) const for (auto* section = firstSection; section; section = section->next) { if (section->name == name) + { return section; + } } return nullptr; } diff --git a/src/libs/antares/io/CMakeLists.txt b/src/libs/antares/io/CMakeLists.txt index 778177e192..9e3211e14b 100644 --- a/src/libs/antares/io/CMakeLists.txt +++ b/src/libs/antares/io/CMakeLists.txt @@ -1,25 +1,29 @@ set(HEADERS - antares/io/statistics.h - antares/io/file.h + include/antares/io/statistics.h + include/antares/io/file.h ) set(SRC_IO ${HEADERS} statistics.cpp file.cpp - ) +) source_group("io" FILES ${SRC_IO}) add_library(io ${SRC_IO} - ) +) target_link_libraries(io PRIVATE yuni-static-core logs - ) +) target_include_directories(io - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ) \ No newline at end of file + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/io/antares/io/file.h b/src/libs/antares/io/antares/io/file.h deleted file mode 100644 index 0d87a63c01..0000000000 --- a/src/libs/antares/io/antares/io/file.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_ANTARES_IO_FILE_H__ -#define __LIBS_ANTARES_IO_FILE_H__ - -#include -#include - -/*! -** \brief Reset the content of a file -** -** This routine will wait if there is not enough disk space -*/ -bool IOFileSetContent(const AnyString& filename, const AnyString& content); - -#endif // __LIBS_ANTARES_IO_FILE_H__ diff --git a/src/libs/antares/io/file.cpp b/src/libs/antares/io/file.cpp index d5a8e01480..8ef66b3a3d 100644 --- a/src/libs/antares/io/file.cpp +++ b/src/libs/antares/io/file.cpp @@ -1,59 +1,82 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/io/file.h" -#include + #include #include +#include + #ifdef YUNI_OS_WINDOWS -#include #include + +#include #else -#include #include +#include #endif #include +#include + #include -using namespace Yuni; -using namespace Antares; +namespace fs = std::filesystem; + +constexpr int retryTimeout = 35; // seconds + +namespace Antares::IO +{ + +static void logErrorAndThrow [[noreturn]] (const std::string& errorMessage) +{ + Antares::logs.error() << errorMessage; + throw std::runtime_error(errorMessage); +} -enum +std::string readFile(const fs::path& filePath) { - retryTimeout = 35, // seconds -}; + std::ifstream file(filePath, std::ios_base::binary | std::ios_base::in); + if (!file.is_open()) + { + logErrorAndThrow(filePath.string() + ": file does not exist"); + } + + using Iterator = std::istreambuf_iterator; + std::string content(Iterator{file}, Iterator{}); + if (!file) + { + logErrorAndThrow("Read failed '" + filePath.string() + "'"); + } + return content; +} -bool IOFileSetContent(const AnyString& filename, const AnyString& content) +bool fileSetContent(const std::string& filename, const std::string& content) { - if (System::windows) + if (Yuni::System::windows) { // On Windows, there is still the hard limit to 256 chars even if the API allows more if (filename.size() >= 256) + { logs.warning() << "I/O error: Maximum path length limitation (> 256 characters)"; + } } uint attempt = 0; @@ -68,17 +91,17 @@ bool IOFileSetContent(const AnyString& filename, const AnyString& content) << " (probably not enough disk space)."; // Notification via the UI interface - String text; - DateTime::TimestampToString(text, "%H:%M"); + Yuni::String text; + Yuni::DateTime::TimestampToString(text, "%H:%M"); logs.info() << "Not enough disk space since " << text << ". Waiting..."; // break; } // waiting a little... - Suspend(retryTimeout); + Yuni::Suspend(retryTimeout); } ++attempt; - IO::File::Stream out(filename, IO::OpenMode::write); + Yuni::IO::File::Stream out(filename, Yuni::IO::OpenMode::write); if (not out.opened()) { switch (errno) @@ -99,7 +122,9 @@ bool IOFileSetContent(const AnyString& filename, const AnyString& content) } if (content.empty()) // ok, good, it's over + { return true; + } // little io trick : when the size if greater than a page size, it is possible // to use ftruncate to reduce block disk allocation @@ -120,7 +145,9 @@ bool IOFileSetContent(const AnyString& filename, const AnyString& content) } } if (content.size() != out.write(content)) + { continue; // not enough disk space + } // OK, good // Notifying the user / logs that we can safely continue. It could be interresting @@ -138,3 +165,5 @@ bool IOFileSetContent(const AnyString& filename, const AnyString& content) return false; } + +} // namespace Antares::IO diff --git a/src/libs/antares/io/include/antares/io/file.h b/src/libs/antares/io/include/antares/io/file.h new file mode 100644 index 0000000000..b401b1cece --- /dev/null +++ b/src/libs/antares/io/include/antares/io/file.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __LIBS_ANTARES_IO_FILE_H__ +#define __LIBS_ANTARES_IO_FILE_H__ + +#include + +#include + +namespace Antares::IO +{ +/*! +** \brief Reset the content of a file +** +** This routine will wait if there is not enough disk space +*/ +bool fileSetContent(const std::string& filename, const std::string& content); + +std::string readFile(const std::filesystem::path&); + +} // namespace Antares::IO + +#endif // __LIBS_ANTARES_IO_FILE_H__ diff --git a/src/libs/antares/io/antares/io/statistics.h b/src/libs/antares/io/include/antares/io/statistics.h similarity index 77% rename from src/libs/antares/io/antares/io/statistics.h rename to src/libs/antares/io/include/antares/io/statistics.h index d22c4f3f1b..f81d697a2d 100644 --- a/src/libs/antares/io/antares/io/statistics.h +++ b/src/libs/antares/io/include/antares/io/statistics.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_IO_STATISTICS_H__ #define __ANTARES_LIBS_IO_STATISTICS_H__ diff --git a/src/libs/antares/io/statistics.cpp b/src/libs/antares/io/statistics.cpp index 7795abe2f6..e78beb0c00 100644 --- a/src/libs/antares/io/statistics.cpp +++ b/src/libs/antares/io/statistics.cpp @@ -1,32 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/io/statistics.h" -#include + +#include + #include using namespace Yuni; @@ -37,71 +33,60 @@ namespace Statistics { namespace // anonymous namespace { -static uint64_t gReadFromDisk; -static uint64_t gWrittenToDisk; -static uint64_t gReadFromNetwork; -static uint64_t gWrittenToNetwork; - -static uint64_t gReadFromDiskSinceStartup; -static uint64_t gWrittenToDiskSinceStartup; -static uint64_t gReadFromNetworkSinceStartup; -static uint64_t gWrittenToNetworkSinceStartup; +std::atomic gReadFromDisk; +std::atomic gWrittenToDisk; +std::atomic gReadFromNetwork; +std::atomic gWrittenToNetwork; -static Yuni::Mutex gMutex; +std::atomic gReadFromDiskSinceStartup; +std::atomic gWrittenToDiskSinceStartup; +std::atomic gReadFromNetworkSinceStartup; +std::atomic gWrittenToNetworkSinceStartup; } // anonymous namespace uint64_t ReadFromDisk() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gReadFromDisk; + return gReadFromDisk; } uint64_t WrittenToDisk() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gWrittenToDisk; + return gWrittenToDisk; } uint64_t ReadFromDiskSinceStartup() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gReadFromDiskSinceStartup; + return gReadFromDiskSinceStartup; } uint64_t WrittenToDiskSinceStartup() { - Yuni::MutexLocker locker(gMutex); return (int64_t)gWrittenToDiskSinceStartup; } uint64_t ReadFromNetwork() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gReadFromNetwork; + return gReadFromNetwork; } uint64_t WrittenToNetwork() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gWrittenToNetwork; + return gWrittenToNetwork; } uint64_t ReadFromNetworkSinceStartup() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gReadFromNetworkSinceStartup; + return gReadFromNetworkSinceStartup; } uint64_t WrittenToNetworkSinceStartup() { - Yuni::MutexLocker locker(gMutex); - return (uint64_t)gWrittenToNetworkSinceStartup; + return gWrittenToNetworkSinceStartup; } void Reset() { - Yuni::MutexLocker locker(gMutex); gReadFromDisk = 0; gReadFromNetwork = 0; gWrittenToDisk = 0; @@ -110,7 +95,6 @@ void Reset() void DumpToLogs() { - Yuni::MutexLocker locker(gMutex); logs.info() << "[statistics] disk: read: " << (gReadFromDisk / 1024) << " ko, written: " << (gWrittenToDisk / 1024) << " ko"; logs.info() << "[statistics] network: read: " << (gReadFromNetwork / 1024) @@ -119,28 +103,24 @@ void DumpToLogs() void HasReadFromDisk(uint64_t size) { - Yuni::MutexLocker locker(gMutex); gReadFromDisk += size; gReadFromDiskSinceStartup += size; } void HasWrittenToDisk(uint64_t size) { - Yuni::MutexLocker locker(gMutex); gWrittenToDisk += size; gWrittenToDiskSinceStartup += size; } void HasReadFromNetwork(uint64_t size) { - Yuni::MutexLocker locker(gMutex); gReadFromNetwork += size; gReadFromNetworkSinceStartup += size; } void HasWrittenToNetwork(uint64_t size) { - Yuni::MutexLocker locker(gMutex); gWrittenToNetwork += size; gWrittenToNetworkSinceStartup += size; } diff --git a/src/libs/antares/jit.h b/src/libs/antares/jit.h deleted file mode 100644 index bc9b10619a..0000000000 --- a/src/libs/antares/jit.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_JIT_H__ -#define __ANTARES_LIBS_JIT_H__ - -#include - -#endif // __ANTARES_LIBS_JIT_H__ diff --git a/src/libs/antares/jit/CMakeLists.txt b/src/libs/antares/jit/CMakeLists.txt index 0c9016cf13..fa561e4c92 100644 --- a/src/libs/antares/jit/CMakeLists.txt +++ b/src/libs/antares/jit/CMakeLists.txt @@ -1,18 +1,18 @@ set(SRC_JIT # JIT (Just in Time) - antares/jit/jit.h - antares/jit/jit.hxx + include/antares/jit/jit.h + include/antares/jit/jit.hxx jit.cpp - ) +) source_group("misc\\jit" FILES ${SRC_JIT}) add_library(jit ${SRC_JIT} - ) +) target_include_directories(jit - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC + $ ) target_link_libraries(jit @@ -20,4 +20,8 @@ target_link_libraries(jit yuni-static-core PUBLIC logs #templated function use logs - ) \ No newline at end of file +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/jit/antares/jit/jit.h b/src/libs/antares/jit/antares/jit/jit.h deleted file mode 100644 index b8b3a2051a..0000000000 --- a/src/libs/antares/jit/antares/jit/jit.h +++ /dev/null @@ -1,192 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_JIT_JIT_H__ -#define __ANTARES_LIBS_JIT_JIT_H__ - -#include -#include - -namespace Antares -{ -template -class Matrix; -} - -class JIT final -{ -public: - // Forward declaration - class Informations; - - /*! - ** \brief Reset the source filename - */ - static Informations* Reset(Informations* jit, const AnyString& filename); - - /*! - ** \brief Reset the source filename - */ - static Informations* Reset(Informations* jit); - - /*! - ** \brief Mark the attached object as not loaded - */ - static void MarkAsNotLoaded(Informations* j); - - /*! - ** \brief Mark the attached object as modified - */ - static void Invalidate(Informations* j); - - /*! - ** \brief Get if the data has been loaded - */ - static bool IsReady(Informations* j); - -public: - class just_in_time_manager - { - public: - just_in_time_manager(JIT::Informations* jit, const AnyString filename) : - jit_(jit), file_name_(filename) - { - } - void record_current_jit_state(unsigned width, unsigned height); - inline JIT::Informations* jit_recorded_state() - { - return jit_record_; - } - bool matrix_content_in_memory_is_same_as_on_disk() - { - return not jit_->modified; - } - bool jit_activated() - { - return jit_; - } - bool do_we_force_matrix_load_from_disk(); - - template - void load_matrix(const Antares::Matrix* mtx); - - template - void clear_matrix(const Antares::Matrix* mtx); - - template - void unload_matrix_properly_from_memory(const Antares::Matrix* mtx); - ~just_in_time_manager() - { - delete jit_record_; - } - - private: - JIT::Informations* jit_; - JIT::Informations* jit_record_; - AnyString file_name_; - }; - -public: - /*! - ** \brief - */ - class Informations final - { - public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Informations(); - //! Copy constructor - Informations(const Informations& rhs); - //! Destructor - ~Informations(); - //@} - - /*! - ** \brief Mark the associated data as modified - */ - void markAsModified(); - - //! Get the amount of memory currently used - uint64_t memoryUsage() const; - - public: - //! Filename/folder to consider if some data should be loaded - YString sourceFilename; - - //! Flag to determine wheter if the associated data have already been loaded - bool alreadyLoaded; - //! Flag to determine wheter if the associated data have already been modified - bool modified; - //! Flag to determine wheter if the associated data have already been reload - // The item will be considered as modified - bool loadDataIfNotAlreadyDone; - - //! The option to the matrix - unsigned options; - /*! - ** \brief Minimum width expected (for Matrices) - ** - ** It is the 'width' if fixedSize != 0 - */ - unsigned minWidth; - /*! - ** \brief Minimum height expected (for Matrices) - ** - ** It is the 'height' if fixedSize != 0 - */ - unsigned maxHeight; - - //! The estimated number of columns and rows - unsigned estimatedSize[2]; - - //! Timestamp of the last modification - int64_t lastModification; - - }; // class Informations - -public: - /*! - ** \brief Flag to enable/disable JIT informations - ** - ** This variable must be set before the loading of any study. - ** Disabled by default. - */ - static bool enabled; - - /*! - ** \brief Flag to know if the library is called from the User interface - */ - static bool usedFromGUI; - -}; // class JIT - -#include "jit.hxx" - -#endif // __ANTARES_LIBS_JIT_JIT_H__ diff --git a/src/libs/antares/jit/include/antares/jit/jit.h b/src/libs/antares/jit/include/antares/jit/jit.h new file mode 100644 index 0000000000..9354a792d4 --- /dev/null +++ b/src/libs/antares/jit/include/antares/jit/jit.h @@ -0,0 +1,193 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_JIT_JIT_H__ +#define __ANTARES_LIBS_JIT_JIT_H__ + +#include +#include + +namespace Antares +{ +template +class Matrix; +} + +class JIT final +{ +public: + // Forward declaration + class Informations; + + /*! + ** \brief Reset the source filename + */ + static Informations* Reset(Informations* jit, const AnyString& filename); + + /*! + ** \brief Reset the source filename + */ + static Informations* Reset(Informations* jit); + + /*! + ** \brief Mark the attached object as not loaded + */ + static void MarkAsNotLoaded(Informations* j); + + /*! + ** \brief Mark the attached object as modified + */ + static void Invalidate(Informations* j); + + /*! + ** \brief Get if the data has been loaded + */ + static bool IsReady(Informations* j); + +public: + class just_in_time_manager + { + public: + just_in_time_manager(JIT::Informations* jit, const AnyString filename): + jit_(jit), + file_name_(filename) + { + } + + void record_current_jit_state(unsigned width, unsigned height); + + inline JIT::Informations* jit_recorded_state() + { + return jit_record_; + } + + bool matrix_content_in_memory_is_same_as_on_disk() + { + return not jit_->modified; + } + + bool jit_activated() + { + return jit_; + } + + bool do_we_force_matrix_load_from_disk(); + + template + void load_matrix(const Antares::Matrix* mtx); + + template + void clear_matrix(const Antares::Matrix* mtx); + + template + void unload_matrix_properly_from_memory(const Antares::Matrix* mtx); + + ~just_in_time_manager() + { + delete jit_record_; + } + + private: + JIT::Informations* jit_; + JIT::Informations* jit_record_; + AnyString file_name_; + }; + +public: + /*! + ** \brief + */ + class Informations final + { + public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Informations(); + //! Copy constructor + Informations(const Informations& rhs); + //! Destructor + ~Informations(); + //@} + + /*! + ** \brief Mark the associated data as modified + */ + void markAsModified(); + + //! Get the amount of memory currently used + uint64_t memoryUsage() const; + + public: + //! Filename/folder to consider if some data should be loaded + YString sourceFilename; + + //! Flag to determine wheter if the associated data have already been loaded + bool alreadyLoaded; + //! Flag to determine wheter if the associated data have already been modified + bool modified; + //! Flag to determine wheter if the associated data have already been reload + // The item will be considered as modified + bool loadDataIfNotAlreadyDone; + + //! The option to the matrix + unsigned options; + /*! + ** \brief Minimum width expected (for Matrices) + ** + ** It is the 'width' if fixedSize != 0 + */ + unsigned minWidth; + /*! + ** \brief Minimum height expected (for Matrices) + ** + ** It is the 'height' if fixedSize != 0 + */ + unsigned maxHeight; + + //! The estimated number of columns and rows + unsigned estimatedSize[2]; + + //! Timestamp of the last modification + int64_t lastModification; + + }; // class Informations + +public: + /*! + ** \brief Flag to enable/disable JIT informations + ** + ** This variable must be set before the loading of any study. + ** Disabled by default. + */ + static bool enabled; + + /*! + ** \brief Flag to know if the library is called from the User interface + */ + static bool usedFromGUI; + +}; // class JIT + +#include "jit.hxx" + +#endif // __ANTARES_LIBS_JIT_JIT_H__ diff --git a/src/libs/antares/jit/antares/jit/jit.hxx b/src/libs/antares/jit/include/antares/jit/jit.hxx similarity index 77% rename from src/libs/antares/jit/antares/jit/jit.hxx rename to src/libs/antares/jit/include/antares/jit/jit.hxx index a987b21a5d..a19342e7e4 100644 --- a/src/libs/antares/jit/antares/jit/jit.hxx +++ b/src/libs/antares/jit/include/antares/jit/jit.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_JUST_IN_TIME_INFORMATIONS_HXX__ #define __ANTARES_LIBS_JUST_IN_TIME_INFORMATIONS_HXX__ @@ -85,10 +79,10 @@ void JIT::just_in_time_manager::unload_matrix_properly_from_memory(const Matrix< jit_ = JIT::Reset(jit_, buffer); mtx->jit = jit_; JIT::MarkAsNotLoaded(jit_); - jit_->minWidth - = (0 != (jit_recorded_state()->options & Matrix::optFixedSize)) - ? jit_recorded_state()->minWidth - : 1; + jit_->minWidth = (0 + != (jit_recorded_state()->options & Matrix::optFixedSize)) + ? jit_recorded_state()->minWidth + : 1; jit_->maxHeight = jit_recorded_state()->maxHeight; jit_->options = jit_recorded_state()->options; mtx_not_const->clear(); diff --git a/src/libs/antares/jit/jit.cpp b/src/libs/antares/jit/jit.cpp index 568a95deac..8b95c63e12 100644 --- a/src/libs/antares/jit/jit.cpp +++ b/src/libs/antares/jit/jit.cpp @@ -1,60 +1,55 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/jit/jit.h" + #include #include #include -#include "antares/jit/jit.h" bool JIT::enabled = false; bool JIT::usedFromGUI = false; -JIT::Informations::Informations() : - alreadyLoaded(false), - modified(false), - loadDataIfNotAlreadyDone(false), - options(0), - minWidth(0), - maxHeight(0), - lastModification(0) +JIT::Informations::Informations(): + alreadyLoaded(false), + modified(false), + loadDataIfNotAlreadyDone(false), + options(0), + minWidth(0), + maxHeight(0), + lastModification(0) { estimatedSize[0] = 0; estimatedSize[1] = 0; } -JIT::Informations::Informations(const Informations& rhs) : - alreadyLoaded(true), - modified(true), - loadDataIfNotAlreadyDone(true), - options(rhs.options), - minWidth(rhs.minWidth), - maxHeight(rhs.maxHeight), - lastModification(0) +JIT::Informations::Informations(const Informations& rhs): + alreadyLoaded(true), + modified(true), + loadDataIfNotAlreadyDone(true), + options(rhs.options), + minWidth(rhs.minWidth), + maxHeight(rhs.maxHeight), + lastModification(0) { estimatedSize[0] = 0; estimatedSize[1] = 0; @@ -71,7 +66,9 @@ JIT::Informations* JIT::Reset(JIT::Informations* jit) // if changes, see JIT::Reset(jit, filename) // Allocate the structure if needed if (not jit) + { return new JIT::Informations(); + } // Reset the `sourceFilename` if already set jit->sourceFilename.clear(); @@ -145,4 +142,4 @@ bool JIT::just_in_time_manager::do_we_force_matrix_load_from_disk() // a study into a new one. The study "save" operation (after a change in GUI) does not need such // an enforcement, as the matrix is lying in memory and not on disk. return jit_->loadDataIfNotAlreadyDone; -} \ No newline at end of file +} diff --git a/src/libs/antares/locale.cpp b/src/libs/antares/locale.cpp deleted file mode 100644 index f48cad228e..0000000000 --- a/src/libs/antares/locale.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include - -void InitializeDefaultLocale() -{ -#ifdef YUNI_OS_WINDOWS - if (NULL == std::setlocale(LC_ALL, "English")) - std::cerr << "impossible to set locale to English" << std::endl; - -#else - if (NULL == std::setlocale(LC_ALL, "en_US.utf8")) - std::cerr << "impossible to set locale to en_US.utf8" << std::endl; -#endif -} diff --git a/src/libs/antares/locale.h b/src/libs/antares/locale.h deleted file mode 100644 index d3d58b2dc3..0000000000 --- a/src/libs/antares/locale.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LOCALE_H__ -#define __ANTARES_LOCALE_H__ - -/*! -** \brief Initialize the default locale for Antares -*/ -void InitializeDefaultLocale(); - -#endif // __ANTARES_LOCALE_H__ diff --git a/src/libs/antares/locale/CMakeLists.txt b/src/libs/antares/locale/CMakeLists.txt new file mode 100644 index 0000000000..c23d469f86 --- /dev/null +++ b/src/libs/antares/locale/CMakeLists.txt @@ -0,0 +1,25 @@ +set(PROJ locale) +set(HEADERS + include/antares/locale/locale.h +) +set(SRC_LOCALE + ${HEADERS} + locale.cpp) +source_group("locale" FILES ${SRC_LOCALE}) + +add_library(${PROJ} ${SRC_LOCALE}) #Memory conflict with absl memory when building deps https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/1589 +add_library(Antares::locale ALIAS ${PROJ}) + +target_link_libraries(${PROJ} + PRIVATE + yuni-static-core +) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/locale/include/antares/locale/locale.h b/src/libs/antares/locale/include/antares/locale/locale.h new file mode 100644 index 0000000000..e0c6902c33 --- /dev/null +++ b/src/libs/antares/locale/include/antares/locale/locale.h @@ -0,0 +1,32 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LOCALE_H__ +#define __ANTARES_LOCALE_H__ + +namespace Antares +{ +/*! +** \brief Initialize the default locale for Antares +*/ +void InitializeDefaultLocale(); + +} // namespace Antares +#endif // __ANTARES_LOCALE_H__ diff --git a/src/libs/antares/locale/locale.cpp b/src/libs/antares/locale/locale.cpp new file mode 100644 index 0000000000..238331274a --- /dev/null +++ b/src/libs/antares/locale/locale.cpp @@ -0,0 +1,46 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/locale/locale.h" + +#include +#include + +#include + +namespace Antares +{ +void InitializeDefaultLocale() +{ +#ifdef YUNI_OS_WINDOWS + if (!std::setlocale(LC_ALL, "English")) + { + std::cerr << "impossible to set locale to English" << std::endl; + } + +#else + if (!std::setlocale(LC_ALL, "en_US.utf8")) + { + std::cerr << "impossible to set locale to en_US.utf8" << std::endl; + } +#endif +} +} // namespace Antares diff --git a/src/libs/antares/locator/CMakeLists.txt b/src/libs/antares/locator/CMakeLists.txt new file mode 100644 index 0000000000..4cb3f2b939 --- /dev/null +++ b/src/libs/antares/locator/CMakeLists.txt @@ -0,0 +1,29 @@ +set(PROJ locator) +set(HEADERS + include/antares/${PROJ}/locator.h +) +set(SRC_LOCATOR + ${HEADERS} + locator.cpp +) +source_group("misc\\${PROJ}" FILES ${SRC_LOCATOR}) + +add_library(${PROJ} ${SRC_LOCATOR}) +add_library(Antares::${PROJ} ALIAS ${PROJ}) + +target_link_libraries(${PROJ} + PUBLIC + study + PRIVATE + yuni-static-core + Antares::resources +) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/locator/include/antares/locator/locator.h b/src/libs/antares/locator/include/antares/locator/locator.h new file mode 100644 index 0000000000..3e6fe04949 --- /dev/null +++ b/src/libs/antares/locator/include/antares/locator/locator.h @@ -0,0 +1,66 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_SOLVER_H__ +#define __ANTARES_LIBS_SOLVER_H__ + +#include + +#include "antares/study/version.h" + +namespace Antares +{ +namespace Solver +{ +enum Feature +{ + //! The standard solver + standard = 0, + //! The solver with years computed in parallel + parallel, +}; + +/*! +** \brief Find the location of the solver +** \return A non-empty string if the solver has been found, empty otherwise +*/ +bool FindLocation(Yuni::String& location); + +/*! +** \brief Find the location of the analyzer +** \return A non-empty string if the solver has been found, empty otherwise +*/ +bool FindAnalyzerLocation(Yuni::String& location); + +/*! +** \brief Find the location of the constraints builder +** \return A non-empty string if the solver has been found, empty otherwise +*/ +bool FindConstraintsBuilderLocation(Yuni::String& location); + +/*! +** \brief Try to find the location of `antares-ybyaggregator` +*/ +bool FindYearByYearAggregator(Yuni::String& filename); + +} // namespace Solver +} // namespace Antares + +#endif // __ANTARES_LIBS_SOLVER_H__ diff --git a/src/libs/antares/locator/locator.cpp b/src/libs/antares/locator/locator.cpp new file mode 100644 index 0000000000..fbb4087086 --- /dev/null +++ b/src/libs/antares/locator/locator.cpp @@ -0,0 +1,203 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/locator/locator.h" + +#include +#include "yuni/io/filename-manipulation.h" +#include +#include + +#include "antares/config/config.h" +#include "antares/resources/resources.h" + +using namespace Yuni; + +#define SEP \ + Yuni:; \ + IO::Separator + +namespace Antares::Solver +{ +bool FindLocation(String& location) +{ + // reset + location.clear(); + + // The root folder + String root; + Resources::GetRootFolder(root); + String s; + s.reserve(root.size() + 30 /*arbitrary*/); + + IO::SearchPath searchpaths; + searchpaths.prefixes.push_back((s = "antares-")); + + if (System::windows) + { + searchpaths.extensions.push_back(".exe"); + + searchpaths.directories.push_back((s = root) << "\\..\\bin"); + searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); +#ifdef NDEBUG + searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\solver\\Release"); // msvc +#else + searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\solver\\Debug"); // msvc +#endif + + searchpaths.directories.push_back((s = root) << "\\..\\..\\solver"); // mingw + searchpaths.directories.push_back((s = root)); + } + else + { + searchpaths.directories.push_back((s = root) << "/../../solver"); + searchpaths.directories.push_back(root); // TGZ package + searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); + searchpaths.directories.push_back(s.clear() << "/usr/bin/"); + } + + s.clear(); + bool success = searchpaths.find(s, "solver"); + + if (success) + { + IO::Normalize(location, s); + return true; + } + return false; +} + +bool FindAnalyzerLocation(String& location) +{ + // reset + location.clear(); + + // The root folder + String root; + Resources::GetRootFolder(root); + String s; + s.reserve(root.size() + 30 /*arbitrary*/); + + IO::SearchPath searchpaths; + searchpaths.prefixes.push_back((s = "antares-")); + + if (System::windows) + { + searchpaths.extensions.push_back(".exe"); + searchpaths.directories.push_back((s = root) << "\\..\\bin"); + searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); +#ifdef NDEBUG + searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\analyzer\\Release"); // msvc +#else + searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\analyzer\\Debug"); // msvc +#endif + searchpaths.directories.push_back((s = root) << "\\..\\..\\analyzer"); // mingw + searchpaths.directories.push_back((s = root)); + } + else + { + searchpaths.directories.push_back((s = root) << "/../../analyzer"); + searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); + searchpaths.directories.push_back(s.clear() << "/usr/bin/"); + } + + return searchpaths.find(location, "analyzer"); +} + +bool FindConstraintsBuilderLocation(String& location) +{ + // reset + location.clear(); + + // The root folder + String root; + Resources::GetRootFolder(root); + String s; + s.reserve(root.size() + 30 /*arbitrary*/); + + IO::SearchPath searchpaths; + searchpaths.prefixes.push_back((s = "antares-")); + + if (System::windows) + { + searchpaths.extensions.push_back(".exe"); + searchpaths.directories.push_back((s = root) << "\\..\\bin"); + searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); +#ifdef NDEBUG + searchpaths.directories.push_back((s = root) + << "\\..\\..\\..\\constraints-builder\\Release"); // msvc +#else + searchpaths.directories.push_back((s = root) + << "\\..\\..\\..\\constraints-builder\\Debug"); // msvc +#endif + searchpaths.directories.push_back((s = root) << "\\..\\..\\constraints-builder"); // mingw + searchpaths.directories.push_back((s = root)); + } + else + { + searchpaths.directories.push_back((s = root) << "/../../constraints-builder"); + searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); + searchpaths.directories.push_back(s.clear() << "/usr/bin/"); + } + + return searchpaths.find(location, "constraints-builder"); +} + +bool FindYearByYearAggregator(Yuni::String& location) +{ + // reset + location.clear(); + + // The root folder + String root; + Resources::GetRootFolder(root); + String s; + s.reserve(root.size() + 30 /*arbitrary*/); + + IO::SearchPath searchpaths; + searchpaths.prefixes.push_back((s = "antares-")); + + if (System::windows) + { + searchpaths.extensions.push_back(".exe"); + searchpaths.directories.push_back((s = root) << "\\..\\bin"); + searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); +#ifdef NDEBUG + searchpaths.directories.push_back( + (s = root) << "\\..\\..\\..\\tools\\yby-aggregator\\Release"); // msvc +#else + searchpaths.directories.push_back((s = root) + << "\\..\\..\\..\\tools\\yby-aggregator\\Debug"); // msvc +#endif + searchpaths.directories.push_back((s = root) << "\\..\\..\\tools\\yby-aggregator"); // mingw + searchpaths.directories.push_back((s = root)); + } + else + { + searchpaths.directories.push_back((s = root) << "/../../tools/yby-aggregator"); + searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); + searchpaths.directories.push_back(s.clear() << "/usr/bin/"); + } + + return searchpaths.find(location, "ybyaggregator"); +} + +} // namespace Antares::Solver diff --git a/src/libs/antares/logs/CMakeLists.txt b/src/libs/antares/logs/CMakeLists.txt index 0915bc55de..4fc39516d7 100644 --- a/src/libs/antares/logs/CMakeLists.txt +++ b/src/libs/antares/logs/CMakeLists.txt @@ -1,33 +1,34 @@ set(PROJ logs) set(HEADERS - antares/${PROJ}/cleaner.h - antares/${PROJ}/logs.h - antares/${PROJ}/logs.hxx - antares/${PROJ}/hostinfo.h - antares/${PROJ}/hostname.hxx + include/antares/${PROJ}/logs.h + include/antares/${PROJ}/hostinfo.h + include/antares/${PROJ}/hostname.hxx ) set(SRC_LOGS ${HEADERS} logs.cpp - cleaner.cpp hostinfo.cpp - ) +) source_group("misc\\logs" FILES ${SRC_LOGS}) add_library(${PROJ} ${SRC_LOGS}) add_library(Antares::${PROJ} ALIAS ${PROJ}) -if(WIN32) - find_library(WSOCK32_LIBRARY wsock32) - find_library(WS2_32_LIBRARY ws2_32) - target_link_libraries(${PROJ} PUBLIC wsock32 ws2_32) -endif() +if (WIN32) + find_library(WSOCK32_LIBRARY wsock32) + find_library(WS2_32_LIBRARY ws2_32) + target_link_libraries(${PROJ} PUBLIC wsock32 ws2_32) +endif () target_link_libraries(${PROJ} PUBLIC yuni-static-core - ) +) target_include_directories(${PROJ} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/logs/antares/logs/cleaner.h b/src/libs/antares/logs/antares/logs/cleaner.h deleted file mode 100644 index ce3ad4cbf6..0000000000 --- a/src/libs/antares/logs/antares/logs/cleaner.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LOGS_CLEANER_H__ -#define __ANTARES_LOGS_CLEANER_H__ - -#include -#include - -namespace Antares -{ -enum -{ - defaultRetentionTime = (60 * 60 * 24) * 31, -}; - -/*! -** \brief Purge all log files -*/ -void PurgeLogFiles(const AnyString& path, uint retention = defaultRetentionTime); - -} // namespace Antares - -#endif // __ANTARES_LOGS_CLEANER_H__ diff --git a/src/libs/antares/logs/antares/logs/hostinfo.h b/src/libs/antares/logs/antares/logs/hostinfo.h deleted file mode 100644 index 54d72a6ba7..0000000000 --- a/src/libs/antares/logs/antares/logs/hostinfo.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_HOST_INFO_H__ -#define __ANTARES_LIBS_HOST_INFO_H__ - -#include -#include - -/*! -** \brief Write the host info into logs -*/ -void WriteHostInfoIntoLogs(); - -void AppendHostName(Yuni::String& out); - -#endif // __ANTARES_LIBS_HOST_INFO_H__ diff --git a/src/libs/antares/logs/antares/logs/hostname.hxx b/src/libs/antares/logs/antares/logs/hostname.hxx deleted file mode 100644 index 2ec9cb0155..0000000000 --- a/src/libs/antares/logs/antares/logs/hostname.hxx +++ /dev/null @@ -1,98 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#ifndef YUNI_OS_MSVC -#include -#endif -#ifndef YUNI_OS_WINDOWS -#include -#else -#include -#include -#endif - -namespace // anonymous -{ -template -void InternalAppendHostname(AnyStringT& out) -{ -#ifndef YUNI_OS_WINDOWS - char hostname[256]; - if (0 != gethostname(hostname, sizeof(hostname))) - { - out << ""; - return; - } - hostname[sizeof(hostname) - 1] = '\0'; - - struct addrinfo hints, *info, *p; - int gai_result; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/ - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_CANONNAME; - - if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) - { - out << ""; - return; - } - - for (p = info; p != NULL; p = p->ai_next) - { - const char* const name = p->ai_canonname; - if (name and '\0' != *name) - out << name; - } - - freeaddrinfo(info); - -#else // windows - - WSADATA wsaData; - const WORD wVersionRequested = MAKEWORD(2, 0); - - if (WSAStartup(wVersionRequested, &wsaData) == 0) - { - char name[256]; - if (gethostname(name, sizeof(name)) == 0) - { - name[sizeof(name) - 1] = '\0'; // paranoid - out << (const char*)name; - } - else - out << ""; - WSACleanup(); - } - else - out << ""; - -#endif -} - -} // anonymous namespace diff --git a/src/libs/antares/logs/antares/logs/logs.h b/src/libs/antares/logs/antares/logs/logs.h deleted file mode 100644 index 5744727601..0000000000 --- a/src/libs/antares/logs/antares/logs/logs.h +++ /dev/null @@ -1,148 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_LOGS_LOGS_H__ -#define __ANTARES_LIBS_LOGS_LOGS_H__ - -#include -#include "../../../constants.h" -#include "yuni/core/logs/decorators/message.h" -#include "yuni/core/logs/decorators/time.h" -#include "yuni/core/logs/decorators/verbositylevel.h" -#include "yuni/core/logs/handler/file.h" -#include "yuni/core/logs/handler/stdcout.h" -#include "yuni/core/logs/logs.h" - -/*! -** \defgroup logs Logs -** \ingroup toolbox -*/ - -#ifndef LOG_APPLICATION_NAME -/* This value should be defined by CMake */ -#define LOG_APPLICATION_NAME "unknown-app" -#endif - -/*! Special message to the interface */ -#define LOG_UI "[UI] " - -/*! Special message to the interface for notifying about a progression change */ -#define LOG_PROGRESSION "[UI] progression: " - -/*! Inform the GUI that the progression map is ready */ -#define LOG_UI_PROGRESSION_MAP "[UI] Progression map: " - -/*! Ask to the GUI to show the messages */ -#define LOG_UI_DISPLAY_MESSAGES_ON "[UI] Display messages: On" -/*! Ask to the GUI to hide the messages */ -#define LOG_UI_DISPLAY_MESSAGES_OFF "[UI] Display messages: Off" -/*! Ask to the GUI to hide the progress bar */ -#define LOG_UI_HIDE_PROGRESSBAR "[UI] Progression: Off" -/*! Inform the GUI that the solver has properly ended */ -#define LOG_UI_SOLVER_DONE "[UI] Quitting the solver gracefully" - -#ifdef __cplusplus -// This section is only dedicated to includes from a c++ file -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -// Forward declaration -class Study; - -} // namespace Data -} // namespace Antares - -namespace Antares -{ -//! Handlers for logging -using LoggingHandlers = Yuni::Logs::StdCout< // For writing to the standard output - Yuni::Logs::File< // For writing into a log file - Yuni::Logs::Callback<> // Callback - >>; - -//! Decorators for logging -using LoggingDecorators = Yuni::Logs::Time< // Date/Time when the entry log is added - Yuni::Logs::ApplicationName< // Name of the current running application - Yuni::Logs::VerbosityLevel< // Verbosity level (info, warning...) - Yuni::Logs::Message<> // The real message - >>>; - -//! Our log facility -extern Yuni::Logs::Logger logs; - -} // namespace Antares - -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - - /*! - ** \brief Levels for logging - */ - enum LogLevel - { - logUnknown = 0, - logProgress, /* not really a real log level */ - logFatal, - logError, - logWarning, - logNotice, - logInfo, - logDebug - }; - - /*! - ** \brief Generate a compatibility notice - ** \ingroup logs - ** - ** \param format The format string - ** \return Always 0 - */ - int LogCompatibility(const char format[], ...); - - /*! - ** \brief Display informations about encountered errors - */ - void LogDisplayErrorInfos(uint errors, - uint warnings, - const char* message, - bool printError = true); - -#ifdef __cplusplus -} -#endif - -#include "logs.hxx" - -#endif /* __ANTARES_LIBS_LOGS_LOGS_H__ */ diff --git a/src/libs/antares/logs/antares/logs/logs.hxx b/src/libs/antares/logs/antares/logs/logs.hxx deleted file mode 100644 index 4994431e31..0000000000 --- a/src/libs/antares/logs/antares/logs/logs.hxx +++ /dev/null @@ -1,44 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_LOGS_LOGS_H__ -#define __ANTARES_LIBS_LOGS_LOGS_H__ - -#ifdef __cplusplus -extern "C" -{ -#endif - - inline int LogHasErrors(void) - { - return (LogErrorCount() or LogWarningCount()); - } - -#ifdef __cplusplus -} -#endif - -#endif /* __ANTARES_LIBS_LOGS_LOGS_H__ */ diff --git a/src/libs/antares/logs/cleaner.cpp b/src/libs/antares/logs/cleaner.cpp deleted file mode 100644 index ceaa1cdc32..0000000000 --- a/src/libs/antares/logs/cleaner.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "antares/logs/cleaner.h" -#include "../constants.h" -#include -#include -#include - -using namespace Yuni; - -namespace Antares -{ -static inline bool IsLeapYear(uint year) -{ - if (0 == year % 4) - { - if (0 == year % 100) - return (0 == (year % 400)); - return true; - } - return false; -} - -static bool SuitableForDeletion(const AnyString& name, DateTime::Timestamp now) -{ - auto offset = name.find('-'); - if (offset < name.size()) - { - ++offset; - auto afterDate = name.find('-', offset); - if (afterDate < name.size()) - { - auto afterTime = name.find('.', afterDate); - if (afterTime < name.size()) - { - if (afterTime <= afterDate or afterDate <= offset) - return false; - - AnyString date(name.c_str() + offset, afterDate - offset); - AnyString time(name.c_str() + afterDate + 1, afterTime - afterDate - 1); - if (date.size() != 8 or time.size() != 6) - return false; - - AnyString year(date, 0, 4); - AnyString month(date, 4, 2); - AnyString day(date, 6, 2); - AnyString hours(time, 0, 2); - AnyString minutes(time, 2, 2); - AnyString seconds(time, 4, 2); - seconds.trimLeft("0"); - minutes.trimLeft("0"); - hours.trimLeft("0"); - day.trimLeft("0"); - month.trimLeft("0"); - - DateTime::Timestamp timestamp = seconds.to() + minutes.to() * 60 - + hours.to() * 3600 - + (day.to() - 1) * 24 * 3600; - - uint y = year.to(); - if (!(y < 9999)) // 4 digits - { - y = 1970; - } - else - { - if (y < 1970) - y = 1970; - } - - for (uint i = 1970; i < y; ++i) - { - if (not IsLeapYear(i)) - timestamp += 365 * 24 * 3600; - else - timestamp += 366 * 24 * 3600; - } - - uint m = month.to(); - if (m < 12 and m) - { - for (uint i = 0; i != m - 1; ++i) - { - if (i == 1 and IsLeapYear(y)) - timestamp += 24 * 3600 * (Constants::daysPerMonth[i] + 1); - else - timestamp += 24 * 3600 * Constants::daysPerMonth[i]; - } - } - - if (timestamp < now) - return true; - } - } - } - return false; -} - -void PurgeLogFiles(const AnyString& path, uint retention) -{ - if (path.empty()) - return; - - auto now = DateTime::Now(); - now -= retention; - - IO::Directory::Info info(path); - - auto end = info.file_end(); - for (auto i = info.file_begin(); i != end; ++i) - { - auto& name = *i; - if (not name.startsWith("uisimulator-") or not name.endsWith(".log")) - continue; - - if (SuitableForDeletion(name, now)) - IO::File::Delete(i.filename()); - } -} - -} // namespace Antares diff --git a/src/libs/antares/logs/hostinfo.cpp b/src/libs/antares/logs/hostinfo.cpp index 009a0a96b4..4f4464fdaf 100644 --- a/src/libs/antares/logs/hostinfo.cpp +++ b/src/libs/antares/logs/hostinfo.cpp @@ -1,35 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/logs/hostinfo.h" + #include #include -#include "antares/logs/hostinfo.h" -#include +#include #include "antares/logs/hostname.hxx" using namespace Yuni; diff --git a/src/libs/antares/logs/include/antares/logs/hostinfo.h b/src/libs/antares/logs/include/antares/logs/hostinfo.h new file mode 100644 index 0000000000..4a008551b9 --- /dev/null +++ b/src/libs/antares/logs/include/antares/logs/hostinfo.h @@ -0,0 +1,34 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_HOST_INFO_H__ +#define __ANTARES_LIBS_HOST_INFO_H__ + +#include +#include + +/*! +** \brief Write the host info into logs +*/ +void WriteHostInfoIntoLogs(); + +void AppendHostName(Yuni::String& out); + +#endif // __ANTARES_LIBS_HOST_INFO_H__ diff --git a/src/libs/antares/logs/include/antares/logs/hostname.hxx b/src/libs/antares/logs/include/antares/logs/hostname.hxx new file mode 100644 index 0000000000..4497e8e38a --- /dev/null +++ b/src/libs/antares/logs/include/antares/logs/hostname.hxx @@ -0,0 +1,99 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include +#ifndef YUNI_OS_MSVC +#include +#endif +#ifndef YUNI_OS_WINDOWS +#include +#else +#include + +#include +#endif + +namespace // anonymous +{ +template +void InternalAppendHostname(AnyStringT& out) +{ +#ifndef YUNI_OS_WINDOWS + char hostname[256]; + if (0 != gethostname(hostname, sizeof(hostname))) + { + out << ""; + return; + } + hostname[sizeof(hostname) - 1] = '\0'; + + struct addrinfo hints, *info, *p; + int gai_result; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/ + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_CANONNAME; + + if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) + { + out << ""; + return; + } + + for (p = info; p != NULL; p = p->ai_next) + { + const char* const name = p->ai_canonname; + if (name and '\0' != *name) + { + out << name; + } + } + + freeaddrinfo(info); + +#else // windows + + WSADATA wsaData; + const WORD wVersionRequested = MAKEWORD(2, 0); + + if (WSAStartup(wVersionRequested, &wsaData) == 0) + { + char name[256]; + if (gethostname(name, sizeof(name)) == 0) + { + name[sizeof(name) - 1] = '\0'; // paranoid + out << (const char*)name; + } + else + { + out << ""; + } + WSACleanup(); + } + else + { + out << ""; + } + +#endif +} + +} // anonymous namespace diff --git a/src/libs/antares/logs/include/antares/logs/logs.h b/src/libs/antares/logs/include/antares/logs/logs.h new file mode 100644 index 0000000000..9bf0181cf4 --- /dev/null +++ b/src/libs/antares/logs/include/antares/logs/logs.h @@ -0,0 +1,136 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_LOGS_LOGS_H__ +#define __ANTARES_LIBS_LOGS_LOGS_H__ + +#include +#include "yuni/core/logs/decorators/message.h" +#include "yuni/core/logs/decorators/time.h" +#include "yuni/core/logs/decorators/verbositylevel.h" +#include "yuni/core/logs/handler/file.h" +#include "yuni/core/logs/handler/stdcout.h" +#include "yuni/core/logs/logs.h" + +/*! +** \defgroup logs Logs +** \ingroup toolbox +*/ + +/*! Name of the app to use into logs */ +#define LOG_APPLICATION_NAME "antares" +/*! Vendor */ +#define LOG_APPLICATION_VENDOR "RTE" + +/*! Special message to the interface */ +#define LOG_UI "[UI] " + +/*! Special message to the interface for notifying about a progression change */ +#define LOG_PROGRESSION "[UI] progression: " + +/*! Inform the GUI that the progression map is ready */ +#define LOG_UI_PROGRESSION_MAP "[UI] Progression map: " + +/*! Ask to the GUI to show the messages */ +#define LOG_UI_DISPLAY_MESSAGES_ON "[UI] Display messages: On" +/*! Ask to the GUI to hide the messages */ +#define LOG_UI_DISPLAY_MESSAGES_OFF "[UI] Display messages: Off" +/*! Ask to the GUI to hide the progress bar */ +#define LOG_UI_HIDE_PROGRESSBAR "[UI] Progression: Off" +/*! Inform the GUI that the solver has properly ended */ +#define LOG_UI_SOLVER_DONE "[UI] Quitting the solver gracefully" + +#ifdef __cplusplus +// This section is only dedicated to includes from a c++ file +#include +#include +#include + +namespace Antares +{ +namespace Data +{ +// Forward declaration +class Study; + +} // namespace Data +} // namespace Antares + +namespace Antares +{ +//! Handlers for logging +using LoggingHandlers = Yuni::Logs::StdCout< // For writing to the standard output + Yuni::Logs::File< // For writing into a log file + Yuni::Logs::Callback<> // Callback + >>; + +//! Decorators for logging +using LoggingDecorators = Yuni::Logs::Time< // Date/Time when the entry log is added + Yuni::Logs::ApplicationName< // Name of the current running application + Yuni::Logs::VerbosityLevel< // Verbosity level (info, warning...) + Yuni::Logs::Message<> // The real message + >>>; + +//! Our log facility +extern Yuni::Logs::Logger logs; + +} // namespace Antares + +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +/*! +** \brief Levels for logging +*/ +enum LogLevel +{ + logUnknown = 0, + logProgress, /* not really a real log level */ + logFatal, + logError, + logWarning, + logNotice, + logInfo, + logDebug +}; + +/*! +** \brief Generate a compatibility notice +** \ingroup logs +** +** \param format The format string +** \return Always 0 +*/ +int LogCompatibility(const char format[], ...); + +/*! +** \brief Display informations about encountered errors +*/ +void LogDisplayErrorInfos(uint errors, uint warnings, const char* message, bool printError = true); + +#ifdef __cplusplus +} +#endif + +#endif /* __ANTARES_LIBS_LOGS_LOGS_H__ */ diff --git a/src/libs/antares/logs/logs.cpp b/src/libs/antares/logs/logs.cpp index 978b02fb30..1a595ec52c 100644 --- a/src/libs/antares/logs/logs.cpp +++ b/src/libs/antares/logs/logs.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/logs/logs.h" @@ -83,9 +77,13 @@ void LogDisplayErrorInfos(uint errors, uint warnings, const char* message, bool else { if (errors) + { logs.error() << "Found " << error << ": " << message; + } if (warnings) + { logs.error() << "Found " << warning << ": " << message; + } } } else @@ -97,9 +95,13 @@ void LogDisplayErrorInfos(uint errors, uint warnings, const char* message, bool else { if (errors) + { logs.info() << "Found " << error << ": " << message; + } if (warnings) + { logs.info() << "Found " << warning << ": " << message; + } } } } diff --git a/src/libs/antares/memory/CMakeLists.txt b/src/libs/antares/memory/CMakeLists.txt index fca5f764db..69d83cf468 100644 --- a/src/libs/antares/memory/CMakeLists.txt +++ b/src/libs/antares/memory/CMakeLists.txt @@ -22,5 +22,9 @@ target_link_libraries(${PROJ} target_include_directories(${PROJ} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/memory/include/antares/memory/memory.h b/src/libs/antares/memory/include/antares/memory/memory.h index 2f818b2c66..42515c5fce 100644 --- a/src/libs/antares/memory/include/antares/memory/memory.h +++ b/src/libs/antares/memory/include/antares/memory/memory.h @@ -1,90 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_MEMORY_MEMORY_H__ #define __ANTARES_LIBS_MEMORY_MEMORY_H__ #include -#include #include +#include namespace Antares { /*! ** \brief Custom memory allocator for managed pointers */ -class Memory final : public Yuni::Policy::ObjectLevelLockable +class Memory final: public Yuni::Policy::ObjectLevelLockable { public: - template - class Array final - { - public: - //! \name Constructors - //@{ - /*! - ** \brief Default constructor - */ - Array() = default; - - /*! - ** \brief Constructor from null - */ - explicit Array(const Yuni::NullPtr&); - - /*! - ** \brief Constructor with an initial allocation size - */ - explicit Array(size_t size); - - //! Copy constructor (must be empty) - Array(const Array& copy); - - template - Array(const Array&); - - /*! - ** \brief Destructor - */ - ~Array(); - //@} - - /*! - ** \brief - */ - void allocate(size_t size); - - T& operator[](uint i); - const T& operator[](uint i) const; - - private: - T* pPointer = nullptr; - - }; // class Array - template struct Stored final { @@ -107,7 +55,6 @@ class Memory final : public Yuni::Policy::ObjectLevelLockable template static void Assign(uint count, U* array, const U& value); -public: template static void Allocate(T*& out, size_t size); @@ -123,7 +70,6 @@ class Memory final : public Yuni::Policy::ObjectLevelLockable template static void Release(T*& pointer); -public: //! \name Constructor & Destructor //@{ /*! diff --git a/src/libs/antares/memory/include/antares/memory/memory.hxx b/src/libs/antares/memory/include/antares/memory/memory.hxx index 0417176fec..aeb99b413d 100644 --- a/src/libs/antares/memory/include/antares/memory/memory.hxx +++ b/src/libs/antares/memory/include/antares/memory/memory.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_MEMORY_MEMORY_HXX__ #define __ANTARES_LIBS_MEMORY_MEMORY_HXX__ @@ -34,54 +28,6 @@ inline uint64_t Memory::processID() const return pProcessID; } -template -Memory::Array::Array(const Yuni::NullPtr&) -{ -} - -template -Memory::Array::Array(const Memory::Array&) -{ -} - -template -template -Memory::Array::Array(const Memory::Array&) -{ -} - -template -inline Memory::Array::Array(size_t size) -{ - allocate(size); -} - -template -inline Memory::Array::~Array() -{ - delete[] pPointer; - pPointer = nullptr; -} - -template -void Memory::Array::allocate(size_t size) -{ - delete[] pPointer; - pPointer = new T[size]; -} - -template -T& Memory::Array::operator[](uint i) -{ - return (T&)pPointer[i]; -} - -template -const T& Memory::Array::operator[](uint i) const -{ - return (const T&)pPointer[i]; -} - template inline void Memory::Release(T*& pointer) { @@ -124,7 +70,9 @@ template inline void Memory::Assign(uint count, U* array, const U& value) { for (uint i = 0; i != count; ++i) + { array[i] = value; + } } } // namespace Antares diff --git a/src/libs/antares/memory/include/antares/memory/new_check.hxx b/src/libs/antares/memory/include/antares/memory/new_check.hxx index 3e67f89d51..ebf77c6c38 100644 --- a/src/libs/antares/memory/include/antares/memory/new_check.hxx +++ b/src/libs/antares/memory/include/antares/memory/new_check.hxx @@ -1,6 +1,27 @@ -#include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include +#include + namespace Antares { namespace MemoryUtils diff --git a/src/libs/antares/memory/memory.cpp b/src/libs/antares/memory/memory.cpp index ae8c50fed4..3819cc8036 100644 --- a/src/libs/antares/memory/memory.cpp +++ b/src/libs/antares/memory/memory.cpp @@ -1,52 +1,50 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include +#include + #include +#include +#include + #include #ifndef YUNI_OS_WINDOWS -#include -#include +#include #include #include #include -#include -// man 2 kill #include +#include +// man 2 kill #include +#include #endif #ifdef YUNI_OS_WINDOWS #include #endif -#include "antares/memory/memory.h" -#include #include +#include +#include "antares/memory/memory.h" + using namespace Yuni; #define SEP Yuni::IO::Separator @@ -59,14 +57,16 @@ Memory memory; namespace // anonymous { // Global mutex for memory handler -static Yuni::Mutex gMutex; +static std::mutex gMutex; } // anonymous namespace bool Memory::initializeTemporaryFolder() { - Yuni::MutexLocker locker(gMutex); + std::lock_guard locker(gMutex); if (pAlreadyInitialized) + { return true; + } pAlreadyInitialized = true; pAllowedToChangeCacheFolder = LocalPolicy::ReadAsBool("allow_custom_cache_folder", true); @@ -90,7 +90,9 @@ bool Memory::initializeTemporaryFolder() { System::Environment::Read("TEMPDIR", pCacheFolder); if (pCacheFolder.empty()) + { pCacheFolder = "/tmp"; + } } } } @@ -102,7 +104,9 @@ bool Memory::initializeTemporaryFolder() { System::Environment::Read("TMP", pCacheFolder); if (pCacheFolder.empty()) + { pCacheFolder = "C:"; + } } } } @@ -128,21 +132,23 @@ void Memory::displayInfo() const logs.info() << " memory pool: system info: page size: " << sysconf(_SC_PAGESIZE); #endif - Yuni::MutexLocker locker(gMutex); + std::lock_guard locker(gMutex); logs.info() << " memory pool: cache folder: " << pCacheFolder; } const String& Memory::cacheFolder() const { - MutexLocker locker(gMutex); + std::lock_guard locker(gMutex); return pCacheFolder; } void Memory::cacheFolder(const AnyString& folder) { - MutexLocker locker(gMutex); + std::lock_guard locker(gMutex); if (pAllowedToChangeCacheFolder) + { pCacheFolder = folder; + } } } // namespace Antares diff --git a/src/libs/antares/mersenne-twister/CMakeLists.txt b/src/libs/antares/mersenne-twister/CMakeLists.txt index a61ba1ac00..1bcc3262b9 100644 --- a/src/libs/antares/mersenne-twister/CMakeLists.txt +++ b/src/libs/antares/mersenne-twister/CMakeLists.txt @@ -2,7 +2,6 @@ set(PROJ mersenne) set(SRC_PROJ mersenne-twister.cpp include/antares/mersenne-twister/mersenne-twister.h - include/antares/mersenne-twister/mersenne-twister.hxx ) source_group("mersenne-twister" FILES ${SRC_PROJ}) @@ -16,5 +15,23 @@ target_link_libraries(${PROJ} target_include_directories(${PROJ} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) + +if (${BUILD_MERSENNE_TWISTER_PYBIND11}) + pybind11_add_module(mersenne_twister_pybind11 mersenne_twister_pybind11.cpp) + target_link_libraries(mersenne_twister_pybind11 + PRIVATE + ${PROJ} + yuni-static-core) + + # Fix for clang+pybind11 + # See https://github.com/pybind/pybind11/issues/1604 + if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + target_compile_options(mersenne_twister_pybind11 PRIVATE -fsized-deallocation) + endif() +endif() diff --git a/src/libs/antares/mersenne-twister/include/antares/mersenne-twister/mersenne-twister.h b/src/libs/antares/mersenne-twister/include/antares/mersenne-twister/mersenne-twister.h index 949bc8bb0a..352cf5882d 100644 --- a/src/libs/antares/mersenne-twister/include/antares/mersenne-twister/mersenne-twister.h +++ b/src/libs/antares/mersenne-twister/include/antares/mersenne-twister/mersenne-twister.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __LIB_ANTARES_RANDOM_MERSENNE_H__ #define __LIB_ANTARES_RANDOM_MERSENNE_H__ @@ -43,7 +37,7 @@ namespace Antares ** ** \see http://en.wikipedia.org/wiki/Mersenne_twister */ -class MersenneTwister final : public Yuni::Math::Random::ADistribution +class MersenneTwister final { public: // Name of the distribution @@ -51,8 +45,10 @@ class MersenneTwister final : public Yuni::Math::Random::ADistribution. -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIB_ANTARES_RANDOM_MERSENNE_HXX__ -#define __LIB_ANTARES_RANDOM_MERSENNE_HXX__ - -namespace Antares -{ -inline MersenneTwister::Value MersenneTwister::min() -{ - return 0.; -} - -inline MersenneTwister::Value MersenneTwister::max() -{ - return 1.; -} - -inline void MersenneTwister::reset() -{ - reset(defaultSeed); -} - -} // namespace Antares - -#endif // __LIB_ANTARES_RANDOM_MERSENNE_H__ diff --git a/src/libs/antares/mersenne-twister/mersenne-twister.cpp b/src/libs/antares/mersenne-twister/mersenne-twister.cpp index 580559c023..a6a1764bad 100644 --- a/src/libs/antares/mersenne-twister/mersenne-twister.cpp +++ b/src/libs/antares/mersenne-twister/mersenne-twister.cpp @@ -31,6 +31,7 @@ */ #include "antares/mersenne-twister/mersenne-twister.h" + #include #define MATRIX_A 0x9908b0dfUL // constant vector a @@ -112,4 +113,24 @@ MersenneTwister::Value MersenneTwister::next() const return y * (1.0 / 4294967295.0); } +MersenneTwister::Value MersenneTwister::min() +{ + return 0.; +} + +MersenneTwister::Value MersenneTwister::max() +{ + return 1.; +} + +void MersenneTwister::reset() +{ + reset(defaultSeed); +} + +MersenneTwister::Value MersenneTwister::operator()() +{ + return next(); +} + } // namespace Antares diff --git a/src/libs/antares/mersenne-twister/mersenne_twister_pybind11.cpp b/src/libs/antares/mersenne-twister/mersenne_twister_pybind11.cpp new file mode 100644 index 0000000000..0eda367d9d --- /dev/null +++ b/src/libs/antares/mersenne-twister/mersenne_twister_pybind11.cpp @@ -0,0 +1,16 @@ +#include + +#include + +namespace py = pybind11; + +PYBIND11_MODULE(mersenne_twister_pybind11, m) +{ + using namespace Antares; + py::class_(m, "mersenne_twister") + .def(py::init<>()) // default constructor + .def("reset", py::overload_cast(&MersenneTwister::reset)) + .def("next", &MersenneTwister::next) + .def_static("min", &MersenneTwister::min) + .def_static("max", &MersenneTwister::max); +} diff --git a/src/libs/antares/net/net.h b/src/libs/antares/net/net.h deleted file mode 100644 index 998c1af806..0000000000 --- a/src/libs/antares/net/net.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_NET_NET_H__ -#define __ANTARES_LIBS_NET_NET_H__ - -#include - -#endif // __ANTARES_LIBS_NET_NET_H__ diff --git a/src/libs/antares/net/request.h b/src/libs/antares/net/request.h deleted file mode 100644 index c2232465f9..0000000000 --- a/src/libs/antares/net/request.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_NET_REQUEST_H__ -#define __ANTARES_LIBS_NET_REQUEST_H__ - -namespace Antares -{ -namespace Net -{ -enum Method -{ - rmGET, - rmPOST -}; - -//! Event -using EventOnSuccess = Yuni::Bind; - -void Request(Method method, - const AnyString& url, - const EventOnSuccess& onSuccess, - const EventOnError& onError); - -} // namespace Net -} // namespace Antares - -#endif // __ANTARES_LIBS_NET_REQUEST_H__ diff --git a/src/libs/antares/object/CMakeLists.txt b/src/libs/antares/object/CMakeLists.txt deleted file mode 100644 index 774ec2dfd3..0000000000 --- a/src/libs/antares/object/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -set(SRC_OBJECT - intrusive-reference.h - intrusive-reference.hxx - object.h - object.hxx - object.cpp - ref.h - ) -source_group("object" FILES ${SRC_OBJECT}) - -add_library(object - ${SRC_OBJECT}) -add_library(Antares::object ALIAS object) - -target_link_libraries(object - PRIVATE - yuni-static-core - yuni-static-uuid - ) \ No newline at end of file diff --git a/src/libs/antares/object/intrusive-reference.h b/src/libs/antares/object/intrusive-reference.h deleted file mode 100644 index a30c9fde26..0000000000 --- a/src/libs/antares/object/intrusive-reference.h +++ /dev/null @@ -1,132 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_ASSEMBLY_INTRUSIVEREFERENCE_H__ -#define __ANTARES_LIB_ASSEMBLY_INTRUSIVEREFERENCE_H__ - -#include "../antares.h" -#include - -namespace Antares -{ -/*! -** \brief Give to inherited classes an intrusive counting through CRTP. -** -** \tparam ChildT Child class type -** \tparam TP Threading policy. Set by default for a single thread -*/ -template class TP = Yuni::Policy::ObjectLevelLockable> -class IIntrusiveReference : public TP> -{ -public: - //! Simplified type name of the instance for the current child type & threading policy. - using IntrusiveRef = IIntrusiveReference; - //! Threading policy type - using ThreadingPolicy = TP; - - /*! - ** \brief Class Helper to determine the most suitable smart pointer for a class - ** according the current threading policy - */ - template - class SmartPtr - { - public: - //! A thread-safe type - using PtrThreadSafe = Yuni::SmartPtr; - //! A default type - using PtrSingleThreaded = Yuni::SmartPtr; - //! The most suitable smart pointer for T - using Ptr = typename Yuni::Static:: - If::ResultType; - }; // class SmartPtr - -public: - //! \name Pointer management - //@{ - //! Increment the internal reference counter - void addRef() const; - //! Decrement the internal reference counter - bool release() const; - //! Get if the object is an unique reference (COW idiom) - bool unique() const; - //@} - - /*! - ** \brief Action to do when the release method is called - ** - ** For now, does nothing. - ** Called by children through static polymorphism (CRTP). - ** \attention Thread safe - */ - void onRelease(); - -protected: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - IIntrusiveReference(); - - /*! - ** \brief Destructor - ** - ** \internal The keyword 'virtual' is mandatory to have a proper call to the - ** destructor - */ - virtual ~IIntrusiveReference(); - - /*! - ** \brief Copy constructor - ** \param rhs Copy source - */ - explicit IIntrusiveReference(const IIntrusiveReference& rhs); - //@} - - /*! - ** \brief Assignment operator - ** \param rhs Assignment source - ** \return Reference to "this" - */ - IIntrusiveReference& operator=(const IIntrusiveReference& rhs) const; - -private: - using ReferenceCounterType = typename ThreadingPolicy::template Volatile::Type; - //! Intrusive reference count - mutable ReferenceCounterType pRefCount; - - // debug - mutable std::list> pTraces; - mutable std::list> pTracesFree; - -}; // class IIntrusiveReference - -} // namespace Antares - -#include "intrusive-reference.hxx" - -#endif // __ANTARES_LIB_ASSEMBLY_INTRUSIVEREFERENCE_H__ diff --git a/src/libs/antares/object/intrusive-reference.hxx b/src/libs/antares/object/intrusive-reference.hxx deleted file mode 100644 index c70e504e50..0000000000 --- a/src/libs/antares/object/intrusive-reference.hxx +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_ASSEMBLY_INTRUSIVEREFERENCE_HXX__ -#define __ANTARES_LIB_ASSEMBLY_INTRUSIVEREFERENCE_HXX__ - -#include - -namespace Antares -{ -template class TP> -inline IIntrusiveReference::IIntrusiveReference() : pRefCount(0) -{ -} - -template class TP> -inline IIntrusiveReference::~IIntrusiveReference() -{ -} - -template class TP> -inline IIntrusiveReference::IIntrusiveReference( - const IIntrusiveReference& rhs) : - pRefCount(0) -{ -} - -template class TP> -inline IIntrusiveReference& IIntrusiveReference::operator=( - const IIntrusiveReference& rhs) const -{ - // Does nothing - return *this; -} - -template class TP> -inline void IIntrusiveReference::onRelease() -{ - static_cast(this)->onRelease(); -} - -template class TP> -inline bool IIntrusiveReference::unique() const -{ - typename ThreadingPolicy::MutexLocker locker(*this); - return pRefCount == 1; -} - -template class TP> -inline void IIntrusiveReference::addRef() const -{ - typename ThreadingPolicy::MutexLocker locker(*this); - ++pRefCount; -} - -template class TP> -inline bool IIntrusiveReference::release() const -{ - { - typename ThreadingPolicy::MutexLocker locker(*this); - assert(pRefCount > 0); - - if (--pRefCount != 0) - return false; - } - static_cast(const_cast*>(this))->onRelease(); - return true; -} - -} // namespace Antares - -#endif // __ANTARES_LIB_ASSEMBLY_INTRUSIVEREFERENCE_HXX__ diff --git a/src/libs/antares/object/object.cpp b/src/libs/antares/object/object.cpp deleted file mode 100644 index 3dcd06024b..0000000000 --- a/src/libs/antares/object/object.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "object.h" - -using namespace Yuni; - -namespace Antares -{ -IObject::IObject() : pOID(Ref::fGenerate) // will generate a new uuid -{ - assert(!pOID.null() - and "An object ID must not be NULL ({000000000-0000-0000-0000-0000000000000})"); -} - -IObject::IObject(const Ref& uid) : pOID(uid) -{ - assert(!pOID.null() - and "An object ID must not be NULL ({000000000-0000-0000-0000-0000000000000})"); -} - -IObject::~IObject() -{ - // It would be safer to lock/unlock the inner mutex to prevent - // some rare (and nearly impossible) case where the object is destroyed - // whereas another thread is calling one of our methods. - // The smart pointer should get rid of this issue. - // And anyway, it is pointless here the vtable has been already wiped out - // - // ThreadingPolicy::MutexLocker locker(*this); -} - -void IObject::caption(const AnyString& text) -{ - ThreadingPolicy::MutexLocker locker(*this); - pCaption = text; -} - -} // namespace Antares diff --git a/src/libs/antares/object/object.h b/src/libs/antares/object/object.h deleted file mode 100644 index 7e58d5756c..0000000000 --- a/src/libs/antares/object/object.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_OBJECT_H__ -#define __ANTARES_LIB_OBJECT_H__ - -#include "../antares.h" -#include -#include -#include -#include "ref.h" -#include "intrusive-reference.h" - -namespace Antares -{ -/*! -** \brief Base assembly abstract object -** -** \note An object is disabled by default to avoid race conditions -** in future algorithms (race condtions while initializing for example) -*/ -class IObject : public Yuni::IIntrusiveSmartPtr -{ -public: - //! Ancestor - using Ancestor = Yuni::IIntrusiveSmartPtr; - //! The current threading policy - using ThreadingPolicy = Ancestor::ThreadingPolicy; - - /*! - ** \brief Class Helper to determine the most suitable smart pointer for a class - ** according the current threading policy - */ - template - class SmartPtr - { - public: - //! The most suitable smart pointer for T - using Ptr = typename Ancestor::template SmartPtrType::Ptr; - }; - - //! The most suitable smart pointer for the this class - using Ptr = Ancestor::SmartPtrType::Ptr; - -public: - //! \name Identifiers - //@{ - /*! - ** \brief Object Identifier - */ - const Ref& oid() const; - //@} - - //! \name Caption - //@{ - /*! - ** \brief Get the object's caption - ** \return Object's caption - */ - YString caption() const; - /*! - ** \brief Set the caption field - ** \param caption String to use as caption. - */ - void caption(const AnyString& caption); - //@} - - //! \name Enabled - //@{ - /*! - ** \brief Get the object's state - ** \return Object's state - */ - bool enabled() const; - /*! - ** \brief Set the object stated (enabled or not) - ** \param state State to set - */ - void enabled(bool state); - //@} - - //! \name Events - //@{ - //! The object is about to be destroyed - virtual void onRelease(); - //@} - -protected: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Initialize the new IObject with the given UOID. - */ - IObject(); - /*! - ** \brief Initialize the new IObject with the given assembly name. - */ - explicit IObject(const Ref& oid); - /*! - ** \brief Destructor - */ - virtual ~IObject(); - //@} - -protected: - //! The most suitable type for a bool - using EnableType - = Yuni::Static::If, bool>::ResultType; - - //! Object Identifier - const Ref pOID; - //! Caption - YString pCaption; - //! If the object is enabled. Disabled by default - EnableType pEnabled; - -}; // class IObject - -} // namespace Antares - -#include "object.hxx" - -#endif // __ANTARES_LIB_OBJECT_H__ diff --git a/src/libs/antares/object/object.hxx b/src/libs/antares/object/object.hxx deleted file mode 100644 index fe7df13662..0000000000 --- a/src/libs/antares/object/object.hxx +++ /dev/null @@ -1,60 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_OBJECT_HXX__ -#define __ANTARES_LIB_OBJECT_HXX__ - -namespace Antares -{ -inline const Ref& IObject::oid() const -{ - return pOID; -} - -inline YString IObject::caption() const -{ - ThreadingPolicy::MutexLocker locker(*this); - return pCaption; -} - -inline bool IObject::enabled() const -{ - return (pEnabled != 0); -} - -inline void IObject::enabled(bool state) -{ - pEnabled = state; -} - -inline void IObject::onRelease() -{ - // do nothing -} - -} // namespace Antares - -#endif // __ANTARES_LIB_OBJECT_HXX__ diff --git a/src/libs/antares/object/ref.h b/src/libs/antares/object/ref.h deleted file mode 100644 index 1d7df2be18..0000000000 --- a/src/libs/antares/object/ref.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __OPTIMATE_LIB_ASSEMBLY_OID_H__ -#define __OPTIMATE_LIB_ASSEMBLY_OID_H__ - -#include "../antares.h" -#include -#include - -namespace Yuni -{ -class YUNI_DECL UUID; -} - -namespace Antares -{ -//! Object Unique Identifier -using Ref = Yuni::UUID; - -} // namespace Antares - -namespace std -{ -/*! -** \brief Specialization fot std::hash -** -** This specialization is requiered for std::unordered_map -** (or any hash table from the previous tr1) -*/ -template<> -class hash -{ -public: - inline std::size_t operator()(const Yuni::UUID& value) const - { - return value.hash(); - } -}; // class hash - -} // namespace std - -#endif // __OPTIMATE_LIB_ASSEMBLY_OID_H__ diff --git a/src/libs/antares/optimization-options/CMakeLists.txt b/src/libs/antares/optimization-options/CMakeLists.txt new file mode 100644 index 0000000000..3d507b7e5c --- /dev/null +++ b/src/libs/antares/optimization-options/CMakeLists.txt @@ -0,0 +1,10 @@ +set(PROJ optimization-options) + +add_library(${PROJ} INTERFACE) + +target_include_directories(${PROJ} + INTERFACE + $ +) + +add_library(Antares::${PROJ} ALIAS ${PROJ}) diff --git a/src/libs/antares/optimization-options/include/antares/optimization-options/options.h b/src/libs/antares/optimization-options/include/antares/optimization-options/options.h new file mode 100644 index 0000000000..893c1b1c21 --- /dev/null +++ b/src/libs/antares/optimization-options/include/antares/optimization-options/options.h @@ -0,0 +1,37 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once +#include + +namespace Antares::Solver::Optimization +{ + +struct OptimizationOptions +{ + //! Force ortools use + bool ortoolsUsed = false; + //! The solver name, sirius is the default + std::string ortoolsSolver = "sirius"; + bool solverLogs = false; + std::string solverParameters; +}; +} // namespace Antares::Solver::Optimization diff --git a/src/libs/antares/paths/CMakeLists.txt b/src/libs/antares/paths/CMakeLists.txt index 75592e3fab..9e8a5fbd5b 100644 --- a/src/libs/antares/paths/CMakeLists.txt +++ b/src/libs/antares/paths/CMakeLists.txt @@ -16,5 +16,9 @@ target_link_libraries(${PROJ} target_include_directories(${PROJ} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/paths/include/antares/paths/list.h b/src/libs/antares/paths/include/antares/paths/list.h index 7745c15030..135a18ff95 100644 --- a/src/libs/antares/paths/include/antares/paths/list.h +++ b/src/libs/antares/paths/include/antares/paths/list.h @@ -1,38 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_PATHS_LIST_H__ #define __ANTARES_LIBS_PATHS_LIST_H__ -#include -#include -#include #include #include +#include +#include +#include + enum PathListOption { //! Not found @@ -57,6 +52,7 @@ class PathList size_t size; enum PathListOption options; }; + using ItemList = std::map; using iterator = ItemList::iterator; @@ -66,6 +62,7 @@ class PathList PathList() { } + ~PathList() { } @@ -74,14 +71,17 @@ class PathList { return item.begin(); } + const_iterator begin() const { return item.begin(); } + iterator end() { return item.end(); } + const_iterator end() const { return item.end(); @@ -149,17 +149,23 @@ class PathList internalPrepare(s); ItemList::iterator i = item.find(pTmp); if (i != item.end()) + { item.erase(i); + } } } void remove(const PathList& toDelete) { if (item.empty() || toDelete.empty()) + { return; + } const ItemList::const_iterator end = toDelete.item.end(); for (ItemList::const_iterator i = toDelete.item.begin(); i != end; ++i) + { this->remove(i->first); + } } uint size() const @@ -176,7 +182,9 @@ class PathList size_t sizeOnDisk(const StringT& sourceFolder) const { if (item.empty()) + { return 0; + } pTmp = sourceFolder; return (!pTmp) ? 0 : internalSizeOnDisk(); } @@ -187,7 +195,9 @@ class PathList uint deleteAllEmptyFolders(const StringT& sourceFolder) { if (item.empty()) + { return 0; + } pTmp = sourceFolder; return internalDeleteAllEmptyFolders(); } @@ -196,7 +206,9 @@ class PathList uint deleteAllFiles(const StringT& sourceFolder) { if (item.empty()) + { return 0; + } pTmp = sourceFolder; return internalDeleteAllFiles(); } @@ -205,7 +217,7 @@ class PathList /*! ** \brief Event triggered from time to time */ - Yuni::Bind onProgress; + std::function onProgress; private: template @@ -216,10 +228,14 @@ class PathList { #ifdef YUNI_OS_WINDOWS if (pTmp[i] == '/') + { pTmp[i] = '\\'; + } #else if (pTmp[i] == '\\') + { pTmp[i] = '/'; + } #endif } } diff --git a/src/libs/antares/paths/list.cpp b/src/libs/antares/paths/list.cpp index 208d7c300b..5369e24513 100644 --- a/src/libs/antares/paths/list.cpp +++ b/src/libs/antares/paths/list.cpp @@ -1,35 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/paths/list.h" + +#include + #include #include #include -#include "antares/paths/list.h" -#include #ifdef YUNI_OS_WINDOWS #include #endif @@ -68,14 +64,18 @@ size_t PathList::totalSizeInBytes() const const ItemList::const_iterator end = item.end(); for (ItemList::const_iterator i = item.begin(); i != end; ++i) + { size += i->second.size; + } return size; } uint PathList::internalDeleteAllEmptyFolders() { if (!pTmp || item.empty()) + { return 0; + } Clob buffer; uint count = 0; @@ -89,9 +89,13 @@ uint PathList::internalDeleteAllEmptyFolders() buffer.clear() << pTmp << SEP << i->first; if (IO::Directory::Remove(buffer) || !IO::Directory::Exists(buffer)) + { ++count; + } else + { logs.warning() << "I/O error: could not remove " << buffer; + } } } return count; @@ -100,7 +104,9 @@ uint PathList::internalDeleteAllEmptyFolders() uint PathList::internalDeleteAllFiles() { if (!pTmp || item.empty()) + { return 0; + } Clob buffer; uint count = 0; @@ -113,25 +119,32 @@ uint PathList::internalDeleteAllFiles() { buffer.clear() << pTmp << SEP << i->first; if (IO::File::Delete(buffer) || !IO::File::Exists(buffer)) + { ++count; + } else + { logs.warning() << "I/O error: could not delete " << buffer; + } } } return count; } -class PathListIterator : public IO::Directory::IIterator +class PathListIterator: public IO::Directory::IIterator { public: using IteratorType = IO::Directory::IIterator; using Flow = IO::Flow; public: - PathListIterator(PathList& l, const PathList& e, Yuni::Bind& progress) : - list(l), exclude(e), onProgress(progress) + PathListIterator(PathList& l, const PathList& e, std::function& progress): + list(l), + exclude(e), + onProgress(progress) { } + virtual ~PathListIterator() { // For code robustness and to avoid corrupt vtable @@ -158,7 +171,9 @@ class PathListIterator : public IO::Directory::IIterator virtual Flow onFile(const String& filename, const String&, const String&, uint64_t size) { if (pathListOptNotFound == exclude.find(filename.c_str() + offset)) + { list.add(filename.c_str() + offset, (size_t)size); + } return IO::flowContinue; } @@ -166,7 +181,7 @@ class PathListIterator : public IO::Directory::IIterator PathList& list; const PathList& exclude; uint offset; - Yuni::Bind& onProgress; + std::function& onProgress; }; void PathList::internalAddFromFolder(const Clob& folder, const PathList& exclude) diff --git a/src/libs/antares/resources/CMakeLists.txt b/src/libs/antares/resources/CMakeLists.txt new file mode 100644 index 0000000000..554f191fa5 --- /dev/null +++ b/src/libs/antares/resources/CMakeLists.txt @@ -0,0 +1,28 @@ +set(PROJ resources) +set(HEADERS + include/antares/resources/resources.h +) +set(SRC_RESOURCES + ${HEADERS} + resources.cpp) +source_group("resources" FILES ${SRC_RESOURCES}) + +add_library(${PROJ} ${SRC_RESOURCES}) #Memory conflict with absl memory when building deps https://github.com/AntaresSimulatorTeam/Antares_Simulator/issues/1589 +add_library(Antares::resources ALIAS ${PROJ}) + +target_link_libraries(${PROJ} + PUBLIC + yuni-static-core + PRIVATE + Antares::logs + Antares::config +) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/resources/include/antares/resources/resources.h b/src/libs/antares/resources/include/antares/resources/resources.h new file mode 100644 index 0000000000..d7a905cc45 --- /dev/null +++ b/src/libs/antares/resources/include/antares/resources/resources.h @@ -0,0 +1,65 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_RESOURCE_H__ +#define __ANTARES_LIBS_RESOURCE_H__ + +#include +#include + +namespace Antares +{ +namespace Resources +{ +/*! +** \brief Get the full path of a resource file +** +** \param relFileName The filename of the resource, relative to the resource folder +** \return The full path of the resource file if found, an empty string otherwise +*/ +bool FindFile(YString& out, const AnyString& filename); + +/*! +** \brief Get the full path of a resource file +** +** \param relFileName The filename of the resource, relative to the resource folder +** \return The full path of the resource file if found, an empty string otherwise +*/ +bool FindFirstOf(YString& out, const char* const* const list); + +/*! +** \brief Try to find the examples folder +*/ +bool FindExampleFolder(YString& folder); + +/*! +** \brief Initialize variables about resource handling +*/ +void Initialize(int argc, char* argv[], bool initializeSearchPath = false); + +/*! +** \brief Copy the root folder +*/ +void GetRootFolder(YString& out); + +} // namespace Resources +} // namespace Antares + +#endif // __ANTARES_LIBS_RESOURCE_H__ diff --git a/src/libs/antares/resources/resources.cpp b/src/libs/antares/resources/resources.cpp index 4d9fcb54d1..650d10e99a 100644 --- a/src/libs/antares/resources/resources.cpp +++ b/src/libs/antares/resources/resources.cpp @@ -1,35 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/resources/resources.h" + #include #include -#include "resources.h" + #include -#include "../config.h" +#include "antares/config/config.h" using namespace Yuni; @@ -62,7 +58,9 @@ bool FindFile(Yuni::String& out, const AnyString& filename) IO::Normalize(out, tmp); if (IO::File::Exists(out)) + { return true; + } } } out.clear(); @@ -85,14 +83,18 @@ bool FindExampleFolder(Yuni::String& folder) s.clear() << RootFolder << SEP << ".." << SEP << "examples"; IO::Normalize(folder, s); if (IO::Directory::Exists(folder)) + { return true; + } #else // First guess - typical unix install s.clear() << RootFolder << SEP << ".." << SEP << "examples"; s.clear() << "/usr/share/antares/" << ANTARES_VERSION << "/examples"; IO::Normalize(folder, s); if (IO::Directory::Exists(folder)) + { return true; + } #endif // Second guess : Dev mode, from the source repository @@ -100,7 +102,9 @@ bool FindExampleFolder(Yuni::String& folder) << SEP << "examples"; IO::Normalize(folder, s); if (IO::Directory::Exists(folder)) + { return true; + } // Other guesses, Dev mode, special folders when ran from the SVN // repository and from Visual Studio @@ -110,14 +114,18 @@ bool FindExampleFolder(Yuni::String& folder) s.clear() << RootFolder << "\\..\\Debug\\..\\..\\..\\..\\resources\\examples"; IO::Normalize(folder, s); if (IO::Directory::Exists(folder)) + { return true; + } } else { s.clear() << RootFolder << "\\..\\Release\\..\\..\\..\\..\\resources\\examples"; IO::Normalize(folder, s); if (IO::Directory::Exists(folder)) + { return true; + } } #endif @@ -128,7 +136,7 @@ bool FindExampleFolder(Yuni::String& folder) void Initialize(int argc, char** argv, bool initializeSearchPath) { - if (argc < 1 or argv[0] == NULL) + if (argc < 1 or !argv[0]) { logs.error() << "Impossible to find the root folder"; return; @@ -137,7 +145,7 @@ void Initialize(int argc, char** argv, bool initializeSearchPath) String p; IO::MakeAbsolute(p, argv[0]); String tt; - IO::ExtractFilePath(tt, p); + IO::parent_path(tt, p); IO::Normalize(RootFolder, tt); @@ -187,7 +195,9 @@ bool FindFirstOf(String& out, const char* const* const list) tmp.clear() << SearchPaths[i] << list[j]; IO::Normalize(out, tmp); if (IO::File::Exists(out)) + { return true; + } } } out.clear(); diff --git a/src/libs/antares/resources/resources.h b/src/libs/antares/resources/resources.h deleted file mode 100644 index 72e239919c..0000000000 --- a/src/libs/antares/resources/resources.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_RESOURCE_H__ -#define __ANTARES_LIBS_RESOURCE_H__ - -#include -#include - -namespace Antares -{ -namespace Resources -{ -/*! -** \brief Get the full path of a resource file -** -** \param relFileName The filename of the resource, relative to the resource folder -** \return The full path of the resource file if found, an empty string otherwise -*/ -bool FindFile(YString& out, const AnyString& filename); - -/*! -** \brief Get the full path of a resource file -** -** \param relFileName The filename of the resource, relative to the resource folder -** \return The full path of the resource file if found, an empty string otherwise -*/ -bool FindFirstOf(YString& out, const char* const* const list); - -/*! -** \brief Try to find the examples folder -*/ -bool FindExampleFolder(YString& folder); - -/*! -** \brief Initialize variables about resource handling -*/ -void Initialize(int argc, char* argv[], bool initializeSearchPath = false); - -/*! -** \brief Copy the root folder -*/ -void GetRootFolder(YString& out); - -} // namespace Resources -} // namespace Antares - -#endif // __ANTARES_LIBS_RESOURCE_H__ diff --git a/src/libs/antares/series/CMakeLists.txt b/src/libs/antares/series/CMakeLists.txt new file mode 100644 index 0000000000..5f9da57ab2 --- /dev/null +++ b/src/libs/antares/series/CMakeLists.txt @@ -0,0 +1,23 @@ +add_library(series) +add_library(Antares::series ALIAS series) + +set(SRC_STUDY_PART_SERIES + include/antares/series/series.h + series.cpp +) +target_sources(series + PRIVATE + $ + $ +) + +target_link_libraries(series PUBLIC Antares::array) + +target_include_directories(series + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/series/include/antares/series/series.h b/src/libs/antares/series/include/antares/series/series.h new file mode 100644 index 0000000000..d3dde6d092 --- /dev/null +++ b/src/libs/antares/series/include/antares/series/series.h @@ -0,0 +1,120 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_COMMON_TIMESERIES_H__ +#define __ANTARES_LIBS_STUDY_PARTS_COMMON_TIMESERIES_H__ + +#include +#include +#include + +#include + +namespace Antares::Data +{ +/*! + ** \class TimeSeries + ** \brief This class is used to represent the generic time series + ** + ** The goal is to handle indexing with the time series numbers: getCoefficient() + ** and also providing a wrapper for all the Matrix<> functions such as resize() + */ +class TimeSeries; + +class TimeSeriesNumbers +{ +public: + void registerSeries(const TimeSeries* s, std::string label); + // Return a description of the error in case of inconsistent number of columns, std::nullopt + // otherwis + std::optional checkSeriesNumberOfColumnsConsistency() const; + + uint32_t operator[](uint y) const; + uint32_t& operator[](uint y); + + void clear(); + void reset(uint h); + + uint height() const; + + void saveToBuffer(std::string& data) const; + +private: + Matrix tsNumbers; + std::map series; +}; + +class TimeSeries +{ +public: + using TS = Matrix; + + explicit TimeSeries(TimeSeriesNumbers& tsNumbers); + /*! + ** \brief Load series from a file + ** + ** \param path path of the file + ** \param average used to average timeseries + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool loadFromFile(const std::string& path, const bool average); + /*! + ** \brief Save time series to a file + ** + ** \param areaID The ID of the area associated to the data series + ** \param folder The target folder + ** \param prefix the prefix for the filename + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + int saveToFolder(const AreaName& areaID, + const std::string& folder, + const std::string& prefix) const; + + int saveToFile(const std::string& filename, bool saveEvenIfAllZero) const; + + double getCoefficient(uint32_t year, uint32_t timestep) const; + const double* getColumn(uint32_t year) const; + uint32_t getSeriesIndex(uint32_t year) const; + + /// \brief overload operator to return a column + /// Unlike getColumn() it uses direct indexing and not timeseriesNumbers + double* operator[](uint32_t index); + + void reset(); + void reset(uint32_t width, uint32_t height); + uint32_t numberOfColumns() const; + void unloadFromMemory() const; + void roundAllEntries(); + void resize(uint32_t timeSeriesCount, uint32_t timestepCount); + void fill(double value); + void averageTimeseries(); + + bool forceReload(bool reload = false) const; + void markAsModified() const; + uint64_t memoryUsage() const; + + TS timeSeries; + TimeSeriesNumbers& timeseriesNumbers; + + static const std::vector emptyColumn; ///< used in getColumn if timeSeries empty +}; + +} // namespace Antares::Data +#endif /* __ANTARES_LIBS_STUDY_PARTS_COMMON_TIMESERIES_H__ */ diff --git a/src/libs/antares/series/series.cpp b/src/libs/antares/series/series.cpp new file mode 100644 index 0000000000..9116a5b5da --- /dev/null +++ b/src/libs/antares/series/series.cpp @@ -0,0 +1,230 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/series/series.h" + +#include +#include +#include + +#include +#include +#include + +using namespace Yuni; + +#define SEP IO::Separator + +namespace Antares::Data +{ +void TimeSeriesNumbers::registerSeries(const TimeSeries* s, std::string label) +{ + series[std::move(label)] = s; +} + +// TODO[FOM] Code duplication +static bool checkAllElementsIdenticalOrOne(std::vector w) +{ + auto first_one = std::remove(w.begin(), w.end(), 1); // Reject all 1 to the end + return std::adjacent_find(w.begin(), first_one, std::not_equal_to()) == first_one; +} + +static std::string errorMessage(const std::map& series) +{ + std::ostringstream msg; + auto isLast = [&series](std::size_t& idx) + { + idx++; + return idx == series.size(); + }; + for (std::size_t idx = 0; const auto& [label, s]: series) + { + msg << label << ": " << s->numberOfColumns() << (isLast(idx) ? "" : ", "); + } + return msg.str(); +} + +uint TimeSeriesNumbers::height() const +{ + return tsNumbers.height; +} + +uint32_t TimeSeriesNumbers::operator[](uint y) const +{ + return tsNumbers[0][y]; +} + +uint32_t& TimeSeriesNumbers::operator[](uint y) +{ + return tsNumbers[0][y]; +} + +void TimeSeriesNumbers::reset(uint h) +{ + tsNumbers.reset(1, h); +} + +void TimeSeriesNumbers::clear() +{ + tsNumbers.clear(); +} + +void TimeSeriesNumbers::saveToBuffer(std::string& data) const +{ + const auto add1 = [](uint32_t x) { return x + 1; }; + tsNumbers.saveToBuffer(data, 0, true, add1, true); +} + +std::optional TimeSeriesNumbers::checkSeriesNumberOfColumnsConsistency() const +{ + std::vector width; + for (const auto& [_, s]: series) + { + width.push_back(s->numberOfColumns()); + } + + if (!checkAllElementsIdenticalOrOne(width)) + { + return errorMessage(series); + } + return std::nullopt; +} + +TimeSeries::TimeSeries(TimeSeriesNumbers& tsNumbers): + timeseriesNumbers(tsNumbers) +{ +} + +bool TimeSeries::loadFromFile(const std::string& path, const bool average) +{ + bool ret = true; + Matrix<>::BufferType dataBuffer; + ret = timeSeries.loadFromCSVFile(path, 1, HOURS_PER_YEAR, &dataBuffer) && ret; + + if (average) + { + timeSeries.averageTimeseries(); + } + + timeseriesNumbers.clear(); + + return ret; +} + +int TimeSeries::saveToFolder(const AreaName& areaID, + const std::string& folder, + const std::string& prefix) const +{ + Clob buffer; + buffer.clear() << folder << SEP << prefix << areaID << ".txt"; + return timeSeries.saveToCSVFile(buffer, 0); +} + +int TimeSeries::saveToFile(const std::string& filename, bool saveEvenIfAllZero) const +{ + return timeSeries.saveToCSVFile(filename, 6, false, saveEvenIfAllZero); +} + +double TimeSeries::getCoefficient(uint32_t year, uint32_t timestep) const +{ + return timeSeries[getSeriesIndex(year)][timestep]; +} + +const double* TimeSeries::getColumn(uint32_t year) const +{ + return timeSeries[getSeriesIndex(year)]; +} + +uint32_t TimeSeries::getSeriesIndex(uint32_t year) const +{ + // If the timeSeries only has one column, we have no choice but to use it. + if (numberOfColumns() == 1) + { + return 0; + } + + return timeseriesNumbers[year]; +} + +double* TimeSeries::operator[](uint32_t index) +{ + if (timeSeries.width <= index) + { + return nullptr; + } + return timeSeries[index]; +} + +void TimeSeries::reset() +{ + timeSeries.reset(1, HOURS_PER_YEAR); +} + +void TimeSeries::reset(uint32_t width, uint32_t height) +{ + timeSeries.reset(width, height); +} + +uint32_t TimeSeries::numberOfColumns() const +{ + return timeSeries.width; +} + +void TimeSeries::resize(uint32_t timeSeriesCount, uint32_t timestepCount) +{ + timeSeries.resize(timeSeriesCount, timestepCount); +} + +void TimeSeries::fill(double value) +{ + timeSeries.fill(value); +} + +void TimeSeries::roundAllEntries() +{ + timeSeries.roundAllEntries(); +} + +void TimeSeries::averageTimeseries() +{ + timeSeries.averageTimeseries(); +} + +void TimeSeries::unloadFromMemory() const +{ + timeSeries.unloadFromMemory(); +} + +bool TimeSeries::forceReload(bool reload) const +{ + return timeSeries.forceReload(reload); +} + +void TimeSeries::markAsModified() const +{ + timeSeries.markAsModified(); +} + +uint64_t TimeSeries::memoryUsage() const +{ + return timeSeries.memoryUsage(); +} +} // namespace Antares::Data diff --git a/src/libs/antares/solver.cpp b/src/libs/antares/solver.cpp deleted file mode 100644 index be7b7a95dc..0000000000 --- a/src/libs/antares/solver.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include "solver.h" -#include "resources/resources.h" -#include "config.h" -#include -#include - -using namespace Yuni; - -#define SEP \ - Yuni:; \ - IO::Separator - -namespace Antares -{ -namespace Solver -{ -bool FindLocation(String& location) -{ - // reset - location.clear(); - - // The root folder - String root; - Resources::GetRootFolder(root); - String s; - s.reserve(root.size() + 30 /*arbitrary*/); - - IO::SearchPath searchpaths; - searchpaths.prefixes.push_back((s = "antares-" ANTARES_VERSION "-")); - - if (System::windows) - { - searchpaths.extensions.push_back(".exe"); - - searchpaths.directories.push_back((s = root) << "\\..\\bin"); - searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); -#ifdef NDEBUG - searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\solver\\Release"); // msvc -#else - searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\solver\\Debug"); // msvc -#endif - - searchpaths.directories.push_back((s = root) << "\\..\\..\\solver"); // mingw - searchpaths.directories.push_back((s = root)); - } - else - { - searchpaths.directories.push_back((s = root) << "/../../solver"); - searchpaths.directories.push_back(root); // TGZ package - searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); - searchpaths.directories.push_back(s.clear() << "/usr/bin/"); - } - - s.clear(); - bool success = searchpaths.find(s, "solver"); - - if (success) - { - IO::Normalize(location, s); - return true; - } - return false; -} - -bool FindAnalyzerLocation(String& location) -{ - // reset - location.clear(); - - // The root folder - String root; - Resources::GetRootFolder(root); - String s; - s.reserve(root.size() + 30 /*arbitrary*/); - - IO::SearchPath searchpaths; - searchpaths.prefixes.push_back((s = "antares-" ANTARES_VERSION "-")); - - if (System::windows) - { - searchpaths.extensions.push_back(".exe"); - searchpaths.directories.push_back((s = root) << "\\..\\bin"); - searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); -#ifdef NDEBUG - searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\analyzer\\Release"); // msvc -#else - searchpaths.directories.push_back((s = root) << "\\..\\..\\..\\analyzer\\Debug"); // msvc -#endif - searchpaths.directories.push_back((s = root) << "\\..\\..\\analyzer"); // mingw - searchpaths.directories.push_back((s = root)); - } - else - { - searchpaths.directories.push_back((s = root) << "/../../analyzer"); - searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); - searchpaths.directories.push_back(s.clear() << "/usr/bin/"); - } - - return searchpaths.find(location, "analyzer"); -} - -bool FindConstraintsBuilderLocation(String& location) -{ - // reset - location.clear(); - - // The root folder - String root; - Resources::GetRootFolder(root); - String s; - s.reserve(root.size() + 30 /*arbitrary*/); - - IO::SearchPath searchpaths; - searchpaths.prefixes.push_back((s = "antares-" ANTARES_VERSION "-")); - - if (System::windows) - { - searchpaths.extensions.push_back(".exe"); - searchpaths.directories.push_back((s = root) << "\\..\\bin"); - searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); -#ifdef NDEBUG - searchpaths.directories.push_back((s = root) - << "\\..\\..\\..\\constraints-builder\\Release"); // msvc -#else - searchpaths.directories.push_back((s = root) - << "\\..\\..\\..\\constraints-builder\\Debug"); // msvc -#endif - searchpaths.directories.push_back((s = root) << "\\..\\..\\constraints-builder"); // mingw - searchpaths.directories.push_back((s = root)); - } - else - { - searchpaths.directories.push_back((s = root) << "/../../constraints-builder"); - searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); - searchpaths.directories.push_back(s.clear() << "/usr/bin/"); - } - - return searchpaths.find(location, "constraints-builder"); -} - -bool FindYearByYearAggregator(Yuni::String& location) -{ - // reset - location.clear(); - - // The root folder - String root; - Resources::GetRootFolder(root); - String s; - s.reserve(root.size() + 30 /*arbitrary*/); - - IO::SearchPath searchpaths; - searchpaths.prefixes.push_back((s = "antares-" ANTARES_VERSION "-")); - - if (System::windows) - { - searchpaths.extensions.push_back(".exe"); - searchpaths.directories.push_back((s = root) << "\\..\\bin"); - searchpaths.directories.push_back((s = root) << "\\Resources\\tools"); -#ifdef NDEBUG - searchpaths.directories.push_back( - (s = root) << "\\..\\..\\..\\tools\\yby-aggregator\\Release"); // msvc -#else - searchpaths.directories.push_back((s = root) - << "\\..\\..\\..\\tools\\yby-aggregator\\Debug"); // msvc -#endif - searchpaths.directories.push_back((s = root) << "\\..\\..\\tools\\yby-aggregator"); // mingw - searchpaths.directories.push_back((s = root)); - } - else - { - searchpaths.directories.push_back((s = root) << "/../../tools/yby-aggregator"); - searchpaths.directories.push_back(s.clear() << "/usr/local/bin/"); - searchpaths.directories.push_back(s.clear() << "/usr/bin/"); - } - - return searchpaths.find(location, "ybyaggregator"); -} - -} // namespace Solver -} // namespace Antares diff --git a/src/libs/antares/solver.h b/src/libs/antares/solver.h deleted file mode 100644 index 9a22256fc0..0000000000 --- a/src/libs/antares/solver.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_SOLVER_H__ -#define __ANTARES_LIBS_SOLVER_H__ - -#include -#include "study/version.h" - -namespace Antares -{ -namespace Solver -{ -enum Feature -{ - //! The standard solver - standard = 0, - //! The solver with years computed in parallel - parallel, -}; - -/*! -** \brief Find the location of the solver -** \return A non-empty string if the solver has been found, empty otherwise -*/ -bool FindLocation(Yuni::String& location); - -/*! -** \brief Find the location of the analyzer -** \return A non-empty string if the solver has been found, empty otherwise -*/ -bool FindAnalyzerLocation(Yuni::String& location); - -/*! -** \brief Find the location of the constraints builder -** \return A non-empty string if the solver has been found, empty otherwise -*/ -bool FindConstraintsBuilderLocation(Yuni::String& location); - -/*! -** \brief Try to find the location of `antares-ybyaggregator` -*/ -bool FindYearByYearAggregator(Yuni::String& filename); - -} // namespace Solver -} // namespace Antares - -#endif // __ANTARES_LIBS_SOLVER_H__ diff --git a/src/libs/antares/stdcxx/CMakeLists.txt b/src/libs/antares/stdcxx/CMakeLists.txt index dbff9ebc02..c44a2a91e9 100644 --- a/src/libs/antares/stdcxx/CMakeLists.txt +++ b/src/libs/antares/stdcxx/CMakeLists.txt @@ -1,10 +1,10 @@ set(PROJ stdcxx) set(HEADERS - include/antares/${PROJ}/demangle.hpp + include/antares/${PROJ}/class_name.h ) set(SRC_PROJ ${HEADERS} - demangle.cpp + class_name.cpp ) source_group("stdcxx" FILES ${SRC_STDCXX}) @@ -16,6 +16,10 @@ add_library(Antares::${PROJ} ALIAS ${PROJ}) #) target_include_directories(${PROJ} - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + PUBLIC + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/stdcxx/class_name.cpp b/src/libs/antares/stdcxx/class_name.cpp new file mode 100644 index 0000000000..9c4cf9b566 --- /dev/null +++ b/src/libs/antares/stdcxx/class_name.cpp @@ -0,0 +1,42 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include + +namespace stdcxx +{ + +std::string simpleClassName(const char* className) +{ + const std::string& strClassName = className; + std::size_t index = strClassName.find_last_of("::"); + + return (index == std::string::npos) ? strClassName + : strClassName.substr(index + 1, strClassName.size()); +} + +template<> +std::string simpleClassName(const std::type_info& type) +{ + return simpleClassName(type.name()); +} + +} // namespace stdcxx diff --git a/src/libs/antares/stdcxx/demangle.cpp b/src/libs/antares/stdcxx/demangle.cpp deleted file mode 100644 index 5f1115d2be..0000000000 --- a/src/libs/antares/stdcxx/demangle.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include - -namespace stdcxx -{ -std::string demangle(const char* name) -{ - // TODO : for now no boost include, no demangle of class name - /* - #if defined(_WIN32) || defined(WIN32) - // under windows typeid(T).name() does not return a mangled name, but returns : - // - "class T" if T is a class - // - "struct T" if T is a struct - // - "enum T" if T is an enum - // - "union T" if T is an union - // so remove this useless prefix by removing everything found before the last ' ' character - std::string simplifiedName = name; - std::size_t index = simplifiedName.rfind(' '); - if (index != std::string::npos) { - simplifiedName = simplifiedName.substr(index + 1); - } - - return boost::core::demangle(simplifiedName.c_str()); - #else - return boost::core::demangle(name); - #endif - */ - - return name; -} - -template<> -std::string demangle(const std::type_info& type) -{ - return demangle(type.name()); -} - -std::string simpleClassName(const char* className) -{ - const std::string& strClassName = demangle(className); - std::size_t index = strClassName.find_last_of("::"); - - return (index == std::string::npos) ? strClassName - : strClassName.substr(index + 1, strClassName.size()); -} - -template<> -std::string simpleClassName(const std::type_info& type) -{ - return simpleClassName(type.name()); -} - -} // namespace stdcxx \ No newline at end of file diff --git a/src/libs/antares/stdcxx/include/antares/stdcxx/class_name.h b/src/libs/antares/stdcxx/include/antares/stdcxx/class_name.h new file mode 100644 index 0000000000..29a358467d --- /dev/null +++ b/src/libs/antares/stdcxx/include/antares/stdcxx/class_name.h @@ -0,0 +1,43 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include + +namespace stdcxx +{ + +std::string simpleClassName(const char* className); + +template +std::string simpleClassName() +{ + return simpleClassName(typeid(T).name()); +} + +template +std::string simpleClassName(const T& type) +{ + return simpleClassName(typeid(type).name()); +} + +} // namespace stdcxx diff --git a/src/libs/antares/stdcxx/include/antares/stdcxx/demangle.hpp b/src/libs/antares/stdcxx/include/antares/stdcxx/demangle.hpp deleted file mode 100644 index 5187705b85..0000000000 --- a/src/libs/antares/stdcxx/include/antares/stdcxx/demangle.hpp +++ /dev/null @@ -1,68 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef ANTARES_STDCXX_DEMANGLE_HPP -#define ANTARES_STDCXX_DEMANGLE_HPP - -#include -#include - -namespace stdcxx -{ -std::string demangle(const char* name); - -template -std::string demangle() -{ - return demangle(typeid(T).name()); -} - -template -std::string demangle(const T& type) -{ - return demangle(typeid(type).name()); -} - -template<> -std::string demangle(const std::type_info& type); - -std::string simpleClassName(const char* className); - -template -std::string simpleClassName() -{ - return simpleClassName(typeid(T).name()); -} - -template -std::string simpleClassName(const T& type) -{ - return simpleClassName(typeid(type).name()); -} - -} // namespace stdcxx - -#endif // ANTARES_STDCXX_DEMANGLE_HPP \ No newline at end of file diff --git a/src/libs/antares/study-loader/CMakeLists.txt b/src/libs/antares/study-loader/CMakeLists.txt new file mode 100644 index 0000000000..bd169a76bc --- /dev/null +++ b/src/libs/antares/study-loader/CMakeLists.txt @@ -0,0 +1,12 @@ +#Header only library, nothing is compiled hence usage of INTERFACE +add_library(study-loader INTERFACE) +add_library(Antares::study-loader ALIAS study-loader) + +target_sources(study-loader INTERFACE + $ +) + +target_include_directories(study-loader + INTERFACE + $ +) \ No newline at end of file diff --git a/src/libs/antares/study-loader/include/antares/study-loader/IStudyLoader.h b/src/libs/antares/study-loader/include/antares/study-loader/IStudyLoader.h new file mode 100644 index 0000000000..7d6f25373b --- /dev/null +++ b/src/libs/antares/study-loader/include/antares/study-loader/IStudyLoader.h @@ -0,0 +1,48 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +namespace Antares +{ + +namespace Data +{ +class Study; +} + +/** + * @class IStudyLoader + * @brief The IStudyLoader class is an interface for loading studies. + * @details It declares the load method. + */ +class IStudyLoader +{ +public: + virtual ~IStudyLoader() = default; + /** + * @brief The load method is used to load a study. + * @return A shared pointer to a Study object. + */ + [[nodiscard]] virtual std::unique_ptr load() const = 0; +}; +} // namespace Antares diff --git a/src/libs/antares/study/CMakeLists.txt b/src/libs/antares/study/CMakeLists.txt index b4db365a29..65ad5398a6 100644 --- a/src/libs/antares/study/CMakeLists.txt +++ b/src/libs/antares/study/CMakeLists.txt @@ -1,276 +1,261 @@ set(SRC_STUDY_SCENARIO_BUILDER - scenario-builder/scBuilderDataInterface.h - scenario-builder/TSnumberData.h + include/antares/study/scenario-builder/scBuilderDataInterface.h + include/antares/study/scenario-builder/TSnumberData.h scenario-builder/TSnumberData.cpp - scenario-builder/hydroLevelsData.h + include/antares/study/scenario-builder/hydroLevelsData.h scenario-builder/hydroLevelsData.cpp - scenario-builder/rules.h - scenario-builder/rules.hxx + include/antares/study/scenario-builder/rules.h + include/antares/study/scenario-builder/rules.hxx scenario-builder/rules.cpp - scenario-builder/sets.h - scenario-builder/sets.hxx + include/antares/study/scenario-builder/sets.h + include/antares/study/scenario-builder/sets.hxx scenario-builder/sets.cpp - scenario-builder/updater.hxx - scenario-builder/scBuilderUtils.h + include/antares/study/scenario-builder/updater.hxx + include/antares/study/scenario-builder/scBuilderUtils.h scenario-builder/scBuilderUtils.cpp scenario-builder/BindingConstraintsTSNumbersData.cpp scenario-builder/NTCTSNumberData.cpp - scenario-builder/NTCTSNumberData.h - scenario-builder/BindingConstraintsTSNumbersData.h - scenario-builder/RenewableTSNumberData.h + include/antares/study/scenario-builder/NTCTSNumberData.h + include/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h + include/antares/study/scenario-builder/RenewableTSNumberData.h scenario-builder/RenewableTSNumberData.cpp scenario-builder/ThermalTSNumberData.cpp - scenario-builder/ThermalTSNumberData.h - scenario-builder/HydroTSNumberData.h + include/antares/study/scenario-builder/ThermalTSNumberData.h + include/antares/study/scenario-builder/HydroTSNumberData.h scenario-builder/HydroTSNumberData.cpp scenario-builder/SolarTSNumberData.cpp - scenario-builder/solarTSNumberData.h - scenario-builder/WindTSNumberData.h + include/antares/study/scenario-builder/solarTSNumberData.h + include/antares/study/scenario-builder/WindTSNumberData.h scenario-builder/WindTSNumberData.cpp - scenario-builder/LoadTSNumberData.h + include/antares/study/scenario-builder/LoadTSNumberData.h scenario-builder/LoadTSNumberData.cpp - scenario-builder/applyToMatrix.hxx + include/antares/study/scenario-builder/applyToMatrix.hxx ) source_group("study\\scenario builder" FILES ${SRC_MATRIX}) set(SRC_AREAS - area/constants.h - area/area.h - area/area.hxx - area/scratchpad.h + include/antares/study/area/constants.h + include/antares/study/area/area.h + include/antares/study/area/area.hxx + include/antares/study/area/scratchpad.h area/scratchpad.cpp area/area.cpp area/links.cpp - area/links.h + include/antares/study/area/links.h area/store-timeseries-numbers.cpp - area/store-timeseries-numbers.h - area/store-timeseries-numbers.hxx + include/antares/study/area/store-timeseries-numbers.h + include/antares/study/area/store-timeseries-numbers.hxx area/list.cpp ) source_group("study\\area" FILES ${SRC_AREAS}) set(SRC_STUDY_AREA_UI - area/ui.h + include/antares/study/area/ui.h area/ui.cpp ) source_group("study\\area\\ui" FILES ${SRC_STUDY_AREA_UI}) set(SRC_STUDY_PART_COMMON - parts/common/series.h - parts/common/series.cpp parts/common/cluster.cpp - parts/common/cluster.h - parts/common/cluster_list.h + include/antares/study/parts/common/cluster.h + include/antares/study/parts/common/cluster_list.h parts/common/cluster_list.cpp ) source_group("study\\part\\common" FILES ${SRC_STUDY_PART_COMMON}) set(SRC_STUDY_PART_THERMAL - parts/thermal/container.h - parts/thermal/container.hxx + include/antares/study/parts/thermal/container.h parts/thermal/container.cpp - parts/thermal/prepro.h - parts/thermal/prepro.hxx - parts/thermal/prepro.cpp - parts/thermal/ecoInput.h + include/antares/study/parts/thermal/ecoInput.h parts/thermal/ecoInput.cpp - parts/thermal/cluster.h - parts/thermal/cluster.hxx + include/antares/study/parts/thermal/cluster.h + include/antares/study/parts/thermal/cluster.hxx parts/thermal/cluster.cpp - parts/thermal/cluster_list.h + include/antares/study/parts/thermal/cluster_list.h parts/thermal/cluster_list.cpp - parts/thermal/pollutant.h + include/antares/study/parts/thermal/pollutant.h parts/thermal/pollutant.cpp ) source_group("study\\part\\thermal" FILES ${SRC_STUDY_PART_THERMAL}) set(SRC_STUDY_PART_RENEWABLE - parts/renewable/container.h - parts/renewable/container.hxx + include/antares/study/parts/renewable/container.h + include/antares/study/parts/renewable/container.hxx parts/renewable/container.cpp - parts/renewable/cluster.h + include/antares/study/parts/renewable/cluster.h parts/renewable/cluster.cpp - parts/renewable/cluster_list.h + include/antares/study/parts/renewable/cluster_list.h parts/renewable/cluster_list.cpp ) source_group("study\\part\\renewable" FILES ${SRC_STUDY_PART_RENEWABLE}) set(SRC_STUDY_PART_SHORT_TERM_STORAGE - parts/short-term-storage/container.h + include/antares/study/parts/short-term-storage/container.h parts/short-term-storage/container.cpp - parts/short-term-storage/properties.h + include/antares/study/parts/short-term-storage/properties.h parts/short-term-storage/properties.cpp parts/short-term-storage/series.cpp - parts/short-term-storage/series.h - parts/short-term-storage/cluster.h + include/antares/study/parts/short-term-storage/series.h + include/antares/study/parts/short-term-storage/cluster.h parts/short-term-storage/cluster.cpp - parts/short-term-storage/STStorageOutputCaptions.h - parts/short-term-storage/STStorageOutputCaptions.cpp ) source_group("study\\part\\short-term-storage" FILES ${SRC_STUDY_PART_SHORT_TERM_SOTRAGE}) set(SRC_STUDY_PART_WIND - parts/wind/container.h + include/antares/study/parts/wind/container.h parts/wind/container.cpp - parts/wind/series.h - parts/wind/series.hxx - parts/wind/series.cpp - parts/wind/prepro.h - parts/wind/prepro.hxx + include/antares/study/parts/wind/prepro.h + include/antares/study/parts/wind/prepro.hxx parts/wind/prepro.cpp ) source_group("study\\part\\wind" FILES ${SRC_STUDY_PART_WIND}) set(SRC_STUDY_PART_HYDRO - parts/hydro/container.h + include/antares/study/parts/hydro/container.h parts/hydro/container.cpp - parts/hydro/series.h - parts/hydro/series.hxx + include/antares/study/parts/hydro/series.h parts/hydro/series.cpp - parts/hydro/prepro.h + include/antares/study/parts/hydro/prepro.h parts/hydro/prepro.cpp - parts/hydro/allocation.h - parts/hydro/allocation.hxx + include/antares/study/parts/hydro/allocation.h + include/antares/study/parts/hydro/allocation.hxx parts/hydro/allocation.cpp + include/antares/study/parts/hydro/finalLevelValidator.h + parts/hydro/finalLevelValidator.cpp + include/antares/study/parts/hydro/hydromaxtimeseriesreader.h + parts/hydro/hydromaxtimeseriesreader.cpp ) source_group("study\\part\\hydro" FILES ${SRC_STUDY_PART_HYDRO}) set(SRC_STUDY_UI - ui-runtimeinfos.h + include/antares/study/ui-runtimeinfos.h ui-runtimeinfos.cpp ) source_group(study\\UI FILES ${SRC_STUDY_UI}) set(SRC_STUDY_PARAMETERS - parameters.h + include/antares/study/parameters.h parameters.cpp - parameters/adq-patch-params.h + include/antares/study/parameters/adq-patch-params.h parameters/adq-patch-params.cpp UnfeasibleProblemBehavior.cpp # TODO JMK : should be in a target_include_directories : but need to remove all .h from all SRC - UnfeasibleProblemBehavior.hpp + include/antares/study/UnfeasibleProblemBehavior.hpp ) source_group("study\\general data" FILES ${SRC_STUDY_PARAMETERS}) set(SRC_STUDY_FINDER - finder.h finder/finder.cpp - finder/finder.h + include/antares/study/finder/finder.h ) source_group("study\\finder" FILES ${SRC_STUDY_FINDER}) set(SRC_STUDY_BINDING_CONSTRAINT - constraint.h - binding_constraint/BindingConstraint.h - binding_constraint/BindingConstraint.hxx + include/antares/study/constraint.h + include/antares/study/binding_constraint/BindingConstraint.h + include/antares/study/binding_constraint/BindingConstraint.hxx binding_constraint/BindingConstraint.cpp - binding_constraint/BindingConstraintsRepository.h - binding_constraint/BindingConstraintsRepository.h - binding_constraint/BindingConstraintsRepository.hxx + include/antares/study/binding_constraint/BindingConstraintsRepository.h + include/antares/study/binding_constraint/BindingConstraintsRepository.h + include/antares/study/binding_constraint/BindingConstraintsRepository.hxx binding_constraint/BindingConstraintsRepository.cpp binding_constraint/BindingConstraintLoader.cpp - binding_constraint/BindingConstraintLoader.h + include/antares/study/binding_constraint/BindingConstraintLoader.h binding_constraint/BindingConstraintSaver.cpp - binding_constraint/BindingConstraintSaver.h - binding_constraint/EnvForLoading.h - binding_constraint/BindingConstraintStructures.h + include/antares/study/binding_constraint/BindingConstraintSaver.h + include/antares/study/binding_constraint/EnvForLoading.h + include/antares/study/binding_constraint/BindingConstraintStructures.h binding_constraint/BindingConstraintGroup.cpp - binding_constraint/BindingConstraintGroup.h + include/antares/study/binding_constraint/BindingConstraintGroup.h binding_constraint/BindingConstraintGroupRepository.cpp - binding_constraint/BindingConstraintGroupRepository.h + include/antares/study/binding_constraint/BindingConstraintGroupRepository.h ) source_group("study\\constraint" FILES ${SRC_STUDY_BINDING_CONSTRAINT}) set(SRC_XCAST - xcast.h - xcast/xcast.h - xcast/xcast.hxx + include/antares/study/xcast.h + include/antares/study/xcast/xcast.h + include/antares/study/xcast/xcast.hxx xcast/xcast.cpp ) source_group("study\\xcast" FILES ${SRC_XCAST}) set(SRC_STUDY # all - parts/parts.h + include/antares/study/parts/parts.h # Load - parts/load/container.h + include/antares/study/parts/load/container.h parts/load/container.cpp - parts/load/series.h - parts/load/series.hxx - parts/load/series.cpp parts/load/prepro.cpp - parts/load/prepro.h - parts/load/prepro.hxx + include/antares/study/parts/load/prepro.h + include/antares/study/parts/load/prepro.hxx # Solar - parts/solar/container.h + include/antares/study/parts/solar/container.h parts/solar/container.cpp - parts/solar/series.h - parts/solar/series.hxx - parts/solar/series.cpp parts/solar/prepro.cpp - parts/solar/prepro.h - parts/solar/prepro.hxx + include/antares/study/parts/solar/prepro.h + include/antares/study/parts/solar/prepro.hxx # Study - header.h - header.hxx + include/antares/study/header.h header.cpp - load-options.h + include/antares/study/load-options.h load-options.cpp - runtime/runtime.h - runtime/runtime.hxx + include/antares/study/runtime/runtime.h + include/antares/study/runtime/runtime.hxx runtime/runtime.cpp - runtime.h - study.h - study.hxx - fwd.h + include/antares/study/runtime.h + include/antares/study/study.h + include/antares/study/study.hxx + include/antares/study/fwd.h fwd.cpp - study.h + include/antares/study/study.h study.cpp - correlation-updater.hxx + include/antares/study/correlation-updater.hxx study.importprepro.cpp importlogs.cpp load.cpp save.cpp study.extra.cpp - version.h + include/antares/study/version.h version.cpp - cleaner.h - cleaner/cleaner.cpp cleaner/versions.h + include/antares/study/cleaner.h + cleaner/cleaner.cpp + include/antares/study/cleaner/versions.h cleaner/cleaner-v20.cpp output.cpp - output.h - output.hxx + include/antares/study/output.h + include/antares/study/output.hxx layerdata.cpp - layerdata.h + include/antares/study/layerdata.h # progression - progression/progression.h - progression/progression.hxx + include/antares/study/progression/progression.h + include/antares/study/progression/progression.hxx progression/progression.cpp # Simulation - simulation.h + include/antares/study/simulation.h simulation.cpp # Filter - filter.h + include/antares/study/filter.h filter.cpp # Sets - sets.h - sets.hxx + include/antares/study/sets.h + include/antares/study/sets.hxx # variable selection - variable-print-info.h + include/antares/study/variable-print-info.h variable-print-info.cpp ) @@ -299,26 +284,34 @@ add_library(study ${SRC_ALL}) add_library(Antares::study ALIAS study) target_link_libraries(study - PUBLIC - Boost::boost + PUBLIC yuni-static-core - Antares::array #xcast Antares::date #parameters Antares::inifile #parameters Antares::stdcxx #enum.hxx Antares::utils #area.hxx + Antares::solverUtils #sim_structure_probleme_economique.h -> optimization_statistics.h Antares::correlation Antares::path Antares::mersenne Antares::result_writer #study.h - Antares::object - PRIVATE + Antares::series + antares-core + antares-solver-simulation + Antares::hydro + PRIVATE Antares::exception Antares::benchmarking + antares-solver-variable ) target_include_directories(study - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/../.. #Dirty trick to allow inclusion via + PUBLIC + $ + # Make more than just study visible but it's the lesser evil for now ) + +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/libs/antares/study/UnfeasibleProblemBehavior.cpp b/src/libs/antares/study/UnfeasibleProblemBehavior.cpp index c806605865..b26ef1a401 100644 --- a/src/libs/antares/study/UnfeasibleProblemBehavior.cpp +++ b/src/libs/antares/study/UnfeasibleProblemBehavior.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -30,8 +24,7 @@ #include #include - -#include +#include "antares/antares/Enum.hpp" namespace Antares::Data { @@ -118,11 +111,12 @@ const std::initializer_list& getNames() { // Enum must be stored in lower case and without spaces because values are trimmed and lowered // in ini load - static std::initializer_list s_unfeasibleProblemBehaviorNames{ - "warning-dry", "warning-verbose", "error-dry", "error-verbose"}; + static std::initializer_list s_unfeasibleProblemBehaviorNames{"warning-dry", + "warning-verbose", + "error-dry", + "error-verbose"}; return s_unfeasibleProblemBehaviorNames; } } // namespace Enum } // namespace Antares::Data - diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index 030af80586..130c56a0d6 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -1,37 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/study/area/area.h" + #include -#include "../study.h" -#include "area.h" -#include "ui.h" -#include "scratchpad.h" + +#include + +#include "antares/study//study.h" +#include "antares/study/area/scratchpad.h" +#include "antares/study/area/ui.h" #include "antares/study/parts/load/prepro.h" +#include "antares/utils/utils.h" using namespace Yuni; @@ -41,34 +39,32 @@ void Area::internalInitialize() { // Make sure we have if (JIT::usedFromGUI) + { ui = new AreaUI(); + } } -Area::Area() : +Area::Area(): reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR) { internalInitialize(); } -Area::Area(const AnyString& name) : - reserves(fhrMax, HOURS_PER_YEAR), - miscGen(fhhMax, HOURS_PER_YEAR) +Area::Area(const AnyString& name): + Area() { internalInitialize(); this->name = name; - Antares::TransformNameIntoID(this->name, this->id); + this->id = Antares::transformNameIntoID(this->name); } -Area::Area(const AnyString& name, const AnyString& id) : - - reserves(fhrMax, HOURS_PER_YEAR), - miscGen(fhhMax, HOURS_PER_YEAR) +Area::Area(const AnyString& name, const AnyString& id): + Area() { internalInitialize(); this->name = name; - AreaName givenID = id; - Antares::TransformNameIntoID(givenID, this->id); + this->id = Antares::transformNameIntoID(id); } Area::~Area() @@ -93,7 +89,9 @@ void Area::clearAllLinks() { auto end = links.end(); for (auto i = links.begin(); i != end; ++i) + { delete i->second; + } } // Empty the container links.clear(); @@ -103,13 +101,17 @@ void Area::clearAllLinks() void Area::detachAllLinks() { while (not links.empty()) + { AreaLinkRemove((links.begin())->second); + } } AreaLink* Area::findExistingLinkWith(Area& with) { if (&with == this) + { return nullptr; + } if (not links.empty()) { @@ -117,7 +119,9 @@ AreaLink* Area::findExistingLinkWith(Area& with) for (AreaLink::Map::iterator i = links.begin(); i != end; ++i) { if (i->second->from == &with or i->second->with == &with) + { return i->second; + } } } if (!with.links.empty()) @@ -125,7 +129,9 @@ AreaLink* Area::findExistingLinkWith(Area& with) for (auto i = with.links.begin(); i != with.links.end(); ++i) { if (i->second->from == this or i->second->with == this) + { return i->second; + } } } return nullptr; @@ -141,7 +147,9 @@ const AreaLink* Area::findExistingLinkWith(const Area& with) const for (auto i = links.begin(); i != end; ++i) { if (i->second->from == &with or i->second->with == &with) + { return i->second; + } } } if (!with.links.empty()) @@ -150,7 +158,9 @@ const AreaLink* Area::findExistingLinkWith(const Area& with) const for (auto i = with.links.begin(); i != end; ++i) { if (i->second->from == this or i->second->with == this) + { return i->second; + } } } } @@ -177,7 +187,9 @@ uint64_t Area::memoryUsage() const // Hydro ret += PreproHydroMemoryUsage(hydro.prepro); if (hydro.series) + { ret += hydro.series->memoryUsage(); + } // Thermal ret += thermal.list.memoryUsage(); @@ -187,12 +199,16 @@ uint64_t Area::memoryUsage() const // UI if (ui) + { ret += ui->memoryUsage(); + } // links auto end = links.end(); for (auto i = links.begin(); i != end; ++i) + { ret += (i->second)->memoryUsage(); + } return ret; } @@ -205,27 +221,30 @@ void Area::createMissingData() void Area::createMissingTimeSeries() { - if (!load.series) - load.series = new DataSeriesLoad(); - if (!solar.series) - solar.series = new DataSeriesSolar(); - if (!wind.series) - wind.series = new DataSeriesWind(); if (!hydro.series) + { hydro.series = new DataSeriesHydro(); - thermal.list.ensureDataTimeSeries(); - renewable.list.ensureDataTimeSeries(); + } } + void Area::createMissingPrepros() { if (!load.prepro) + { load.prepro = new Data::Load::Prepro(); + } if (!solar.prepro) + { solar.prepro = new Data::Solar::Prepro(); + } if (!wind.prepro) + { wind.prepro = new Data::Wind::Prepro(); + } if (!hydro.prepro) + { hydro.prepro = new PreproHydro(); + } thermal.list.ensureDataPrepro(); } @@ -264,50 +283,28 @@ void Area::resetToDefaultValues() invalidateJIT = true; } -void Area::resizeAllTimeseriesNumbers(uint n) +void Area::resizeAllTimeseriesNumbers(uint nbYears) { - assert(n < 200000); // arbitrary number - - // asserts - assert(load.series and "load.series must not be nullptr !"); - assert(solar.series and "solar.series must not be nullptr !"); - assert(wind.series and "wind.series must not be nullptr !"); assert(hydro.series and "series must not be nullptr !"); - if (!n) + load.series.timeseriesNumbers.reset(nbYears); + solar.series.timeseriesNumbers.reset(nbYears); + wind.series.timeseriesNumbers.reset(nbYears); + hydro.series->timeseriesNumbers.reset(nbYears); + for (auto& namedLink: links) { - load.series->timeseriesNumbers.clear(); - solar.series->timeseriesNumbers.clear(); - wind.series->timeseriesNumbers.clear(); - hydro.series->timeseriesNumbers.clear(); - for (auto& namedLink : links) - { - AreaLink* link = namedLink.second; - link->timeseriesNumbers.clear(); - } + AreaLink* link = namedLink.second; + link->timeseriesNumbers.reset(nbYears); } - else - { - load.series->timeseriesNumbers.resize(1, n); - solar.series->timeseriesNumbers.resize(1, n); - wind.series->timeseriesNumbers.resize(1, n); - hydro.series->timeseriesNumbers.resize(1, n); - for (auto& namedLink : links) - { - AreaLink* link = namedLink.second; - link->timeseriesNumbers.resize(1, n); - } - } - thermal.resizeAllTimeseriesNumbers(n); - renewable.resizeAllTimeseriesNumbers(n); + thermal.resizeAllTimeseriesNumbers(nbYears); + renewable.resizeAllTimeseriesNumbers(nbYears); } bool Area::thermalClustersMinStablePowerValidity(std::vector& output) const { bool noErrorMinStabPow = true; - for (uint l = 0; l != thermal.clusterCount(); ++l) + for (auto& cluster: thermal.list.each_enabled()) { - auto& cluster = thermal.clusters[l]; logs.debug() << "cluster : " << cluster->name(); if ((not cluster->checkMinStablePower()) || (cluster->minStablePower @@ -351,11 +348,15 @@ bool Area::forceReload(bool reload) const { auto end = self.links.end(); for (auto i = self.links.begin(); i != end; ++i) + { ret = (i->second)->forceReload(reload) and ret; + } } if (ui) + { self.ui->markAsModified(); + } return ret; } @@ -384,17 +385,23 @@ void Area::markAsModified() const { auto end = links.end(); for (auto i = links.begin(); i != end; ++i) + { (i->second)->markAsModified(); + } } if (ui) + { ui->markAsModified(); + } } void Area::detachLinkFromID(const AreaName& id) { auto i = links.find(id); if (i != links.end()) + { links.erase(i); + } } void Area::detachLink(const AreaLink* lnk) @@ -431,4 +438,4 @@ void Area::buildLinksIndexes() } } -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h deleted file mode 100644 index d65d840625..0000000000 --- a/src/libs/antares/study/area/area.h +++ /dev/null @@ -1,867 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_AREAS_H__ -#define __ANTARES_LIBS_STUDY_AREAS_H__ - -#include -#include -#include -#include -#include -#include -#include "../parts/parts.h" -#include -#include -#include "links.h" -#include "ui.h" -#include "constants.h" -#include "antares/study/filter.h" - -namespace Antares -{ -namespace Data -{ -struct CompareAreaName; - -/*! -** \brief Definition for a single area -*/ -class Area final : private Yuni::NonCopyable -{ -public: - using NameSet = std::set; - using Set = std::set; - using LinkMap = std::map; - using Map = std::map; - using Vector = std::vector; - using VectorConst = std::vector; - using List = std::list; - //! Name mapping -> must be replaced by AreaNameMapping - using NameMapping = std::map; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Area(); - /*! - ** \brief Constructor with a given name - ** - ** \param name The name of the area - */ - explicit Area(const AnyString& name); - /*! - ** \brief Constructor - ** - ** \param name Name of the area - ** \param id id of the area - */ - Area(const AnyString& name, const AnyString& id); - /*! - ** \brief Destructor - */ - ~Area(); - //@} - - // !\name isVisibleOnLayer - //@{ - /*! - ** \brief check visibility on layer - */ - bool isVisibleOnLayer(const size_t& layerID) const - { - if (ui == nullptr) - return false; - - std::vector& layerList = ui->mapLayersVisibilityList; - std::vector::iterator layerPosition - = std::find(layerList.begin(), layerList.end(), layerID); - return layerPosition != layerList.end(); - } - - //! \name Links - //@{ - /*! - ** \brief Destroy all links - */ - void clearAllLinks(); - - /*! - ** \brief Properly detach all links attached to an area - ** - ** It is the safe way to add an area and it is mainly used by the GUI - */ - void detachAllLinks(); - - /*! - ** \brief Try to find the attached link from another area id - */ - AreaLink* findLinkByID(const AreaName& id); - const AreaLink* findLinkByID(const AreaName& id) const; - - /*! - ** \brief Detach any link connected from this area to the given area - */ - void detachLinkFromID(const AreaName& id); - - static void detachLink(const AreaLink* lnk); - - /*! - ** \brief Remove a link from its raw pointer - */ - void detachLinkFromItsPointer(const AreaLink* lnk); - //@} - - void buildLinksIndexes(); - /*! - ** \brief Ensure all data are created - */ - void createMissingData(); - - /*! - ** \brief Reset all values to their default one - */ - void resetToDefaultValues(); - - /*! - ** \brief Resize all matrices dedicated to the sampled timeseries numbers - ** - ** \param n A number of years - */ - void resizeAllTimeseriesNumbers(uint n); - - /*! - ** \brief Check if a link with another area is already established - ** - ** \param with Any area - ** \return A pointer to an existing link if found, NULL otherwise - */ - AreaLink* findExistingLinkWith(Area& with); - const AreaLink* findExistingLinkWith(const Area& with) const; - - //! \name Memory management - //@{ - /*! - ** \brief Load all data not already loaded - ** - ** If the load-on-demand is enabled, some data might not be loaded (see `Matrix`) - ** However, we would like to be able to force the load of all data, especially - ** when saving a study. - ** The flag `invalidateJIT` will be reset to false. - ** - ** \param reload True to force the reload of data - ** \return True if the operation succeeded - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark all areas as modified - */ - void markAsModified() const; - - /*! - ** \brief Get the amount of memory currently used by the area - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Try to estimate the amount of memory required by the area for a simulation - */ - - //@} - - //! \name Thermal clusters min stable power validity checking - //@{ - /*! - ** \brief Check the validity of min stable power for all thermal clusters - ** - ** \return True if the value of min stable power is a good one - */ - bool thermalClustersMinStablePowerValidity(std::vector& output) const; - //@} - - /*! - ** \brief Get the XCast data according a given time-series type - */ - template - XCast* xcastData(); - template - const XCast* xcastData() const; - -public: - //! \name General - //@{ - //! Name of the area - AreaName name; - //! Name of the area in lowercase format - AreaName id; - //! Index of the area - only valid when already added to an area list - uint index = (uint)(-1); - //! Use adequacy patch for this area - AdequacyPatch::AdequacyPatchMode adequacyPatchMode = AdequacyPatch::physicalAreaOutsideAdqPatch; - /*@}*/ - - //! \name Associate data */ - //@{ - /*! - ** \brief Reserves - ** - ** Reserves, DSM, D-1... - ** \see enum ReservesIndex - */ - Matrix<> reserves; - /*! - ** \brief Misc Gen - ** - ** (previously called `Fatal hors hydro`) - fhhMax * HOURS_PER_YEAR - ** The sum is done in runtimeinfos.cpp - */ - Matrix<> miscGen; // [fhhMax][HOURS_PER_YEAR] - //@} - - //! \name Load - //@{ - Load::Container load; - //@} - - //! \name Solar - //@{ - Solar::Container solar; - //@} - - //! \name Hydro - //@{ - PartHydro hydro; - //@} - - //! \name Wind - //@{ - //! Wind time-series and Wind prepro data - Wind::Container wind; - //@} - - //! \name Thermal - //@{ - PartThermal thermal; - //@} - - //! \name Renewable - //@{ - PartRenewable renewable; - //@} - - ShortTermStorage::STStorageInput shortTermStorage; - - //! \name Interconnections - //@{ - //! All connections with this area - AreaLink::Map links; - //@} - - //! \name Nodal Optimization - //@{ - //! Nodal optimization (see AreaNodalOptimization) - uint nodalOptimization = anoAll; - //@} - - //! \name Spread - //@{ - //! Spread for the unsupplied energy cost - double spreadUnsuppliedEnergyCost = 0.; - //! Spread for the spilled energy cost - double spreadSpilledEnergyCost = 0.; - //@} - - //! \name Output filtering - //@{ - //! Print results for the area in the simulation synthesis - uint filterSynthesis = filterAll; - //! Print results for the area in the year-by-year mode - uint filterYearByYear = filterAll; - //@} - - //! \name UI - //@{ - //! Information for the UI - AreaUI* ui = nullptr; - //@} - - //! \name Dynamic - //@{ - /*! - ** \brief Scratchpad used temporary calculations (solver only) - */ - mutable std::vector scratchpad; - //@} - - //! \name Data - //@{ - /*! - ** \brief Invalidate (JIT) - ** - ** A non-zero value if the missing data must be loaded from HDD for the next - ** save (only valid if JIT enabled). - */ - mutable bool invalidateJIT = false; - //@} - -private: - void internalInitialize(); - void createMissingTimeSeries(); - void createMissingPrepros(); - - -}; // class Area - -bool saveAreaOptimisationIniFile(const Area& area, const Yuni::Clob& buffer); - -bool saveAreaAdequacyPatchIniFile(const Area& area, const Yuni::Clob& buffer); - -/*! -** \brief A list of areas -** -** Here is one way to iterate through the list : -** \code -** AreaList* l; -** ... -** -** ... -** Area* c = l->first; -** while (NULL != c) -** { -** ... -** -** ... -** c = c->next; -** } -** \endcode -** -** It is possible to directly access to an area via its index : -** \code -** AreaList* l; -** ... -** -** ... -** printf("Area name : `%s`\n", (*(l->byIndex[2])).name); -** \endcode -*/ -class AreaList final : public Yuni::NonCopyable -{ -public: - //! An iterator - using iterator = Area::Map::iterator; - //! A const iterator - using const_iterator = Area::Map::const_iterator; - //! An iterator - using reverse_iterator = Area::Map::reverse_iterator; - //! A const iterator - using const_reverse_iterator = Area::Map::const_reverse_iterator; - //! Key-value type - using value_type = Area::Map::value_type; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - explicit AreaList(Study& study); - //! Destructor - ~AreaList(); - //@} - - //! \name Iterating through all areas - //@{ - /*! - ** \brief Iterate through all areas - */ - template - void each(const PredicateT& predicate); - /*! - ** \brief Iterate through all areas (const) - */ - template - void each(const PredicateT& predicate) const; - - iterator begin(); - const_iterator begin() const; - const_iterator cbegin() const; - - iterator end(); - const_iterator end() const; - const_iterator cend() const; - - reverse_iterator rbegin(); - const_reverse_iterator rbegin() const; - - reverse_iterator rend(); - const_reverse_iterator rend() const; - - //! \name Internal Data TS-Generators / Series - //@{ - /*! - ** \brief Ensure data for time series/prepro are initalized if they should be - ** - ** It initializes data for each area so it would be better to call this - ** routine when areas are already loaded. - */ - - void ensureDataIsInitialized(Parameters& params, bool loadOnlyNeeded); - //@} - - //! \name Import / Export - //@{ - /*! - ** \brief Load all informations about areas from a folder (-> input/generalData) - ** - ** \param l The list of areas - ** \param folder The target folder - */ - bool loadFromFolder(const StudyLoadOptions& options); - - /*! - ** \brief Fill the list of areas from an input file - ** - ** The file structure is merely composed by all names of areas, one line one area - ** - ** \param l The structure - ** \param filename The file to read - ** \return A non-zero value if the operation was successful, 0 otherwise - */ - bool loadListFromFile(const AnyString& filename); - - /*! - ** \brief Save all informations about areas into a folder (-> input/generalData) - ** - ** \param l The list of areas - ** \param folder The target folder - */ - bool saveToFolder(const AnyString& folder) const; - - /*! - ** \brief Write the list of areas into a file - ** - ** The file structure is merely composed by all names of areas, one line one area - ** - ** \param filename The file to read - ** \return A non-zero value if the operation was successful, 0 otherwise - */ - bool saveListToFile(const AnyString& filename) const; - - /*! - ** \brief Write the list of all links into a file - ** - ** \code - ** - ** - ** - ** - ** - ** - ** \endcode - ** - ** \param filename The file to read - ** \return A non-zero value if the operation was successful, 0 otherwise - */ - void saveLinkListToBuffer(Yuni::Clob& buffer) const; - - /*! - ** \brief Preload all areas which have been invalidated - ** - ** \param [out] The number of areas which have been invalidated - */ - bool preloadAndMarkAsModifiedAllInvalidatedAreas(uint* invalidateCount = nullptr) const; - //@} - - //! \name Areas - //@{ - /*! - ** \brief Add an area in the container - */ - Area* add(Area* a); - - /*! - ** \brief Find an area from its unique string id - */ - Area* find(const AreaName& id); - /*! - ** \brief Find an area from its unique string id (const) - */ - const Area* find(const AreaName& id) const; - - /*! - ** \brief Find an area from its name - */ - Area* findFromName(const AreaName& name); - - Area* findFromPosition(const int x, const int y) const; - - /*! - ** \brief Find an area from its name (const) - */ - const Area* findFromName(const AreaName& name) const; - - /*! - ** \brief Resize all matrices dedicated to the sampled timeseries numbers - ** - ** \param n A number of years - */ - void resizeAllTimeseriesNumbers(uint n); - - /*! - ** \brief Remove all elements in the container - */ - void clear(); - - //! Get if the container is empty - bool empty() const; - - - /*! - ** \brief Invalidate all areas - ** - ** \param reload True to reload data in the same time - ** \return True if the operation succeeded - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark all data as modified - */ - void markAsModified() const; - - /*! - ** \brief Rebuild the indexes for accessing areas - ** - ** It is sometimes quite usefull to use a mere index to access to - ** a given area. This is mandatory when used from the solver. - */ - void rebuildIndexes(); - - /*! - ** \brief Remove an area from its ID - ** - ** \warning When used by a study, do not forget to remove all binding - ** constraints which depends upon this area before any call to this - ** routine. - */ - bool remove(const AnyString& id); - - /*! - ** \brief Rename an area - ** - ** \param oldid ID of the area to rename - ** \param newName The new name for the area - ** \return True if the operation succeeded (the area has been renamed) - ** false otherwise (if another area has the same name) - ** - ** \warning This function invalidates the index of all areas. If you need - ** the indexes after a call to this routine, please use AreaListRebuildIndex() - */ - bool renameArea(const AreaName& oldid, const AreaName& newName); - - /*! - ** \brief Rename an area - ** - ** \param oldid ID of the area to rename - ** \param newID The new area ID - ** \param newName The new name for the area - ** \return True if the operation succeeded (the area has been renamed) - ** false otherwise (if another area has the same name) - ** - ** \warning This function invalidates the index of all areas. If you need - ** the indexes after a call to this routine, please use AreaListRebuildIndex() - */ - bool renameArea(const AreaName& oldid, const AreaName& newid, const AreaName& newName); - - /*! - ** \brief Get the total number of areas - */ - uint size() const; - //@} - - //! \name Links - //@{ - /*! - ** \brief Find an interconnection between two areas - ** - ** \param area The name of the first area (in lowercase) - ** \param with The name of the second area (in lowercase) - */ - AreaLink* findLink(const AreaName& area, const AreaName& with); - const AreaLink* findLink(const AreaName& area, const AreaName& with) const; - - /*! - ** \brief Try to find the link from a given INI key (%) - */ - AreaLink* findLinkFromINIKey(const AnyString& key); - - /*! - ** \brief Try to find the cluster from a given INI key (.) - */ - ThermalCluster* findClusterFromINIKey(const AnyString& key); - - /*! - ** \brief Get the total number of interconnections between all areas - */ - uint areaLinkCount() const; - //@} - - //! \name Tools - //@{ - /*! - ** \brief Fix all invalid orientations - */ - void fixOrientationForAllInterconnections(BindingConstraintsRepository& bindingconstraints); - - //! Remove all load timeseries - void removeLoadTimeseries(); - //! Remove all hydro timeseries - void removeHydroTimeseries(); - //! Remove all solar timeseries - void removeSolarTimeseries(); - //! Remove all wind timeseries - void removeWindTimeseries(); - //! Remove all thermal timeseries - void removeThermalTimeseries(); - //@} - - //! \name Memory management - //@{ - /*! - ** \brief Try to estimate the amount of memory required by the class for a simulation - */ - - - /*! - ** \brief Get the average amount of memory currently used by each area - */ - double memoryUsageAveragePerArea() const; - - /*! - ** \brief Get the amount of memory currently used by the class - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Update the name id set - */ - void updateNameIDSet() const; - //@} - - //! \name Operators - //@{ - /*! - ** \brief Get an area from its index - */ - Area* operator[](uint i); - const Area* operator[](uint i) const; - //@} - -public: - //! All areas by their index - Area** byIndex; - //! All areas in the list - Area::Map areas; - - //! Name set (must be updated by updateNameSet) - // used by the copy/paste - mutable Area::NameSet nameidSet; - -private: - //! The parent study - Study& pStudy; - -}; // class AreaList - -void AreaListDeleteLinkFromAreaPtr(AreaList* l, const Area* a); - -/*! -** \brief Establish a link between two areas -** -** No check are made at this stade -** -** \param area The main area from where to establish the link -** \param with The second area -** \return A pointer to the structure used by the link between -** the two areas -*/ -AreaLink* AreaAddLinkBetweenAreas(Area* area, Area* with, bool warning = true); - -/*! -** \brief Load interconnections of a given area from a folder (`input/areas/[area]/ntc`) -** -** \param area The area -** \param folder The target folder -** \return A non-null value if the operation succeeded, 0 otherwise -*/ -bool AreaLinksLoadFromFolder(Study& s, AreaList* l, Area* area, const AnyString& folder); - -/*! -** \brief Save interconnections of a given area into a folder (`input/areas/[area]/ntc`) -** -** \param area The area -** \param folder The target folder -** \return True if the operation succeeded, 0 otherwise -*/ -bool AreaLinksSaveToFolder(const Area* area, const char* const folder); - -// Save a given area's interconnexions configuration file into a folder -bool saveAreaLinksConfigurationFileToFolder(const Area* area, const char* const folder); - -/*! -** \brief Clear all interconnection from an area -*/ -int AreaLinkClear(AreaList* l, Area* area); - -/*! -** \brief Remove a connection -*/ -void AreaLinkRemove(AreaLink* lnk); - -/*! -** \brief Try to find an area by its name (in lowercase) -** -** \param l The area list -** \param lname The name of the area in lowercase -** \return A valid pointer to the area structure if found, NULL otherwise -*/ -Area* AreaListLFind(AreaList* l, const char lname[]); - -/*! -** \brief Try to find an area by its ptr -** -** \param l The area list -** \param ptr The ptr -** \return A valid pointer to the area structure if found, NULL otherwise -*/ -Area* AreaListFindPtr(AreaList* l, const Area* ptr); - -/*! -** \brief Add an area in the list from a given name -** -** \param l The list of areas -** \param name The name of the area -** \return A valid pointer to the area if successful, NULL otherwise -*/ -Area* addAreaToListOfAreas(AreaList& list, const AnyString& name); - -/*! -** \brief Add an area in the list from a given name -** -** \param l The list of areas -** \param name The name of the area -** \param lname The name of the area in lowercase -** \return A valid pointer to the area if successful, NULL otherwise -*/ -Area* AreaListAddFromNames(AreaList& list, - const AnyString& name, - const AnyString& lname); - -/*! -** \brief Try to establish a link between two areas -** -** \param l The list of areas -** \param area The area to make a link -** \param with The area to link with -*/ -AreaLink* AreaListAddLink(AreaList* l, const char area[], const char with[], bool warning = true); - -void AreaListClearAllLinks(AreaList* l); - -/*! -** \brief Ensure data for load time-series are initialized -*/ -void AreaListEnsureDataLoadTimeSeries(AreaList* l); - -/*! -** \brief Ensure data for load prepro are initialized -*/ -void AreaListEnsureDataLoadPrepro(AreaList* l); - -/*! -** \brief Ensure data for load time-series are initialized -*/ -void AreaListEnsureDataSolarTimeSeries(AreaList* l); - -/*! -** \brief Ensure data for solar prepro are initialized -*/ -void AreaListEnsureDataSolarPrepro(AreaList* l); - -/*! -** \brief Ensure data for wind time-series are initialized -*/ -void AreaListEnsureDataWindTimeSeries(AreaList* l); - -/*! -** \brief Ensure data for wind prepro are initialized -*/ -void AreaListEnsureDataWindPrepro(AreaList* l); - -/*! -** \brief Ensure data for hydro time-series are initialized -*/ -void AreaListEnsureDataHydroTimeSeries(AreaList* l); - -/*! -** \brief Ensure data for hydro prepro are initialized -*/ -void AreaListEnsureDataHydroPrepro(AreaList* l); - -/*! -** \brief Ensure data for thermal time-series are initialized -*/ -void AreaListEnsureDataThermalTimeSeries(AreaList* l); - -/*! -** \brief Ensure data for renewable time-series are initialized -*/ -void AreaListEnsureDataRenewableTimeSeries(AreaList* l); - -/*! -** \brief Ensure data for thermal prepro are initialized -*/ -void AreaListEnsureDataThermalPrepro(AreaList* l); - -/*! -** \brief to check that Area name does not contains character * -*/ -inline bool CheckForbiddenCharacterInAreaName(const AnyString& name) -{ - return name.contains('*'); -} - -} // namespace Data -} // namespace Antares - -#include "../load-options.h" -#include "area.hxx" - -#endif // __ANTARES_LIBS_STUDY_AREAS_H__ diff --git a/src/libs/antares/study/area/area.hxx b/src/libs/antares/study/area/area.hxx deleted file mode 100644 index e4e1655125..0000000000 --- a/src/libs/antares/study/area/area.hxx +++ /dev/null @@ -1,170 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include -#include "antares/study/parts/parts.h" -#include "antares/study/parts/load/prepro.h" - -namespace Antares::Data -{ -struct CompareAreaName final -{ - inline bool operator()(const Area* s1, const Area* s2) const - { - return s1->name < s2->name; - } -}; - -inline Area* AreaList::operator[](uint i) -{ - assert(i < areas.size() and "Index out of bounds"); - return byIndex[i]; -} - -inline const Area* AreaList::operator[](uint i) const -{ - assert(i < areas.size() and "Index out of bounds"); - return byIndex[i]; -} - -template -inline XCast* Area::xcastData() -{ - switch (T) - { - case timeSeriesLoad: - return &(load.prepro->xcast); - case timeSeriesSolar: - return &(solar.prepro->xcast); - case timeSeriesWind: - return &(wind.prepro->xcast); - case timeSeriesHydro: - return nullptr; - case timeSeriesThermal: - return nullptr; - } - return nullptr; -} - -template -inline const XCast* Area::xcastData() const -{ - switch (T) - { - case timeSeriesLoad: - return &(load.prepro->xcast); - case timeSeriesSolar: - return &(solar.prepro->xcast); - case timeSeriesWind: - return &(wind.prepro->xcast); - case timeSeriesHydro: - return nullptr; - case timeSeriesThermal: - return nullptr; - } - return nullptr; -} - -template -inline void AreaList::each(const PredicateT& predicate) -{ - auto end = areas.end(); - for (auto i = areas.begin(); i != end; ++i) - { - auto& area = *(i->second); - predicate(area); - } -} - -template -inline void AreaList::each(const PredicateT& predicate) const -{ - auto end = areas.cend(); - for (auto i = areas.cbegin(); i != end; ++i) - { - auto& area = *(i->second); - predicate(area); - } -} - -inline uint AreaList::size() const -{ - return (uint)areas.size(); -} - -inline AreaList::iterator AreaList::begin() -{ - return areas.begin(); -} - -inline AreaList::const_iterator AreaList::begin() const -{ - return areas.begin(); -} - -inline AreaList::const_iterator AreaList::cbegin() const -{ - return areas.begin(); -} - -inline AreaList::iterator AreaList::end() -{ - return areas.end(); -} - -inline AreaList::const_iterator AreaList::end() const -{ - return areas.end(); -} - -inline AreaList::const_iterator AreaList::cend() const -{ - return areas.end(); -} - -inline AreaList::reverse_iterator AreaList::rbegin() -{ - return areas.rbegin(); -} - -inline AreaList::const_reverse_iterator AreaList::rbegin() const -{ - return areas.rbegin(); -} - -inline AreaList::reverse_iterator AreaList::rend() -{ - return areas.rend(); -} - -inline AreaList::const_reverse_iterator AreaList::rend() const -{ - return areas.rend(); -} - -} // namespace Antares diff --git a/src/libs/antares/study/area/constants.h b/src/libs/antares/study/area/constants.h deleted file mode 100644 index 756812c53a..0000000000 --- a/src/libs/antares/study/area/constants.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_AREAS_CONSTANTS_H__ -#define __ANTARES_LIBS_STUDY_AREAS_CONSTANTS_H__ - -namespace Antares -{ -namespace Data -{ -struct CompareAreaName; - -enum LinkParameterIndex -{ - //! Hurdles cost, Direct - fhlHurdlesCostDirect = 0, - //! Hurdles cost, Indirect - fhlHurdlesCostIndirect, - //! Impedances, - fhlImpedances, - //! Loop flow, - fhlLoopFlow, - //! P.shift min, - fhlPShiftMinus, - //! P.shift max, - fhlPShiftPlus, - //! Maximum number of items - fhlMax, -}; - -/*! -** \brief Misc. Gen. -*/ -enum MiscGenIndex -{ - //! CHP - fhhCHP = 0, - //! Bio-Mass - fhhBioMass, - //! BioGaz - fhhBioGaz, - //! Waste - fhhWaste, - //! GeoThermal - fhhGeoThermal, - //! Other */ - fhhOther, - //! PSP - Pump - fhhPSP, - //! Row Balance - fhhRowBalance, - //! Maximum number of items - fhhMax -}; - -enum ReservesIndex -{ - //! Primary reserve - fhrPrimaryReserve = 0, - //! Strategic reserve - fhrStrategicReserve, - //! DSM - fhrDSM, - //! D-1 - fhrDayBefore, - //! Maximum number of items - fhrMax, -}; - -enum AreaNodalOptimization -{ - //! Non Dispatchable power - anoNonDispatchPower = 1, - //! Dispatchable Hydro power - anoDispatchHydroPower = 2, - //! Other dispatchable power - anoOtherDispatchPower = 4, - - //! All features - anoAll = anoNonDispatchPower | anoDispatchHydroPower | anoOtherDispatchPower, -}; - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_AREAS_CONSTANTS_H__ diff --git a/src/libs/antares/study/area/links.cpp b/src/libs/antares/study/area/links.cpp index 678ed9350e..f7b722da49 100644 --- a/src/libs/antares/study/area/links.cpp +++ b/src/libs/antares/study/area/links.cpp @@ -1,53 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/area/links.h" + +#include +#include #include -#include -#include "../study.h" -#include "links.h" -#include "area.h" + +#include #include -#include "../filter.h" -#include "constants.h" -#include "../fwd.h" +#include "antares/study//study.h" +#include "antares/study/area/area.h" +#include "antares/utils/utils.h" using namespace Yuni; using namespace Antares; -namespace // anonymous -{ -struct TSNumbersPredicate -{ - uint32_t operator()(uint32_t value) const - { - return value + 1; - } -}; -} // namespace +namespace fs = std::filesystem; #define SEP (IO::Separator) @@ -60,26 +47,31 @@ namespace Antares { namespace Data { -AreaLink::AreaLink() : - from(nullptr), - with(nullptr), - parameters(fhlMax, HOURS_PER_YEAR), - directCapacities(1, HOURS_PER_YEAR), - indirectCapacities(1, HOURS_PER_YEAR), - useLoopFlow(false), - usePST(false), - useHurdlesCost(false), - transmissionCapacities(LocalTransmissionCapacities::enabled), - assetType(Data::atAC), - index(0), - indexForArea(0), - displayComments(true), - filterSynthesis(filterAll), - filterYearByYear(filterAll), - color{112, 112, 112}, - style(stPlain), - linkWidth(1) -{ +AreaLink::AreaLink(): + from(nullptr), + with(nullptr), + parameters(fhlMax, HOURS_PER_YEAR), + directCapacities(timeseriesNumbers), + indirectCapacities(timeseriesNumbers), + useLoopFlow(false), + usePST(false), + useHurdlesCost(false), + transmissionCapacities(LocalTransmissionCapacities::enabled), + assetType(Data::atAC), + index(0), + indexForArea(0), + displayComments(true), + filterSynthesis(filterAll), + filterYearByYear(filterAll), + color{112, 112, 112}, + style(stPlain), + linkWidth(1) +{ + timeseriesNumbers.registerSeries(&directCapacities, "direct-capacity"); + timeseriesNumbers.registerSeries(&indirectCapacities, "indirect-capacity"); + + directCapacities.reset(); + indirectCapacities.reset(); } AreaLink::~AreaLink() @@ -94,14 +86,16 @@ bool AreaLink::linkLoadTimeSeries_for_version_below_810(const AnyString& folder) // Load link's data Matrix<> tmpMatrix; const uint matrixWidth = 8; - if (!tmpMatrix.loadFromCSVFile( - buffer, matrixWidth, HOURS_PER_YEAR, Matrix<>::optFixedSize | Matrix<>::optImmediate)) + if (!tmpMatrix.loadFromCSVFile(buffer, + matrixWidth, + HOURS_PER_YEAR, + Matrix<>::optFixedSize | Matrix<>::optImmediate)) { return false; } // Store data into link's data container - for (int h = 0; h < HOURS_PER_YEAR; h++) + for (unsigned int h = 0; h < HOURS_PER_YEAR; h++) { directCapacities[0][h] = tmpMatrix[0][h]; indirectCapacities[0][h] = tmpMatrix[1][h]; @@ -131,11 +125,11 @@ bool AreaLink::linkLoadTimeSeries_for_version_820_and_later(const AnyString& fol // Read link's direct capacities time series filename.clear() << capacitiesFolder << SEP << with->id << "_direct.txt"; - success = directCapacities.loadFromCSVFile(filename, 1, HOURS_PER_YEAR) && success; + success = directCapacities.loadFromFile(filename, false) && success; // Read link's indirect capacities time series filename.clear() << capacitiesFolder << SEP << with->id << "_indirect.txt"; - success = indirectCapacities.loadFromCSVFile(filename, 1, HOURS_PER_YEAR) && success; + success = indirectCapacities.loadFromFile(filename, false) && success; return success; } @@ -163,36 +157,43 @@ void AreaLink::overrideTransmissionCapacityAccordingToGlobalParameter( break; case GlobalTransmissionCapacities::nullForPhysicalLinks: // Use '0' only for physical links if (isLinkPhysical()) + { transmissionCapacities = LocalTransmissionCapacities::null; + } break; case GlobalTransmissionCapacities::infiniteForPhysicalLinks: // Use 'infinity' only for physical // links if (isLinkPhysical()) + { transmissionCapacities = LocalTransmissionCapacities::infinite; + } break; default: logs.error() << "Wrong global transmission capacity given to function" << __FUNCTION__; } } -bool AreaLink::loadTimeSeries(const Study& study, const AnyString& folder) +bool AreaLink::loadTimeSeries(const StudyVersion& version, const AnyString& folder) { - if (study.header.version < 820) + if (version < StudyVersion(8, 2)) + { return linkLoadTimeSeries_for_version_below_810(folder); + } else + { return linkLoadTimeSeries_for_version_820_and_later(folder); + } } void AreaLink::storeTimeseriesNumbers(Solver::IResultWriter& writer) const { Clob path; - TSNumbersPredicate predicate; std::string buffer; path << "ts-numbers" << SEP << DIRECTORY_NAME_FOR_TRANSMISSION_CAPACITIES << SEP << from->id << SEP << with->id << ".txt"; - timeseriesNumbers.saveToBuffer(buffer, 0, true, predicate, true); + timeseriesNumbers.saveToBuffer(buffer); writer.addEntryFromBuffer(path.c_str(), buffer); } @@ -210,8 +211,8 @@ void AreaLink::detach() void AreaLink::resetToDefaultValues() { parameters.reset(fhlMax, HOURS_PER_YEAR, true); - directCapacities.reset(1, HOURS_PER_YEAR, true); - indirectCapacities.reset(1, HOURS_PER_YEAR, true); + directCapacities.reset(); + indirectCapacities.reset(); for (uint i = 0; i != HOURS_PER_YEAR; ++i) { @@ -262,7 +263,7 @@ void AreaLink::reverse() indirectCapacities.forceReload(true); // invert NTC values - directCapacities.swap(indirectCapacities); + directCapacities.timeSeries.swap(indirectCapacities.timeSeries); directCapacities.markAsModified(); indirectCapacities.markAsModified(); @@ -271,7 +272,9 @@ void AreaLink::reverse() bool AreaLink::isVisibleOnLayer(const size_t& layerID) const { if (from && with) + { return from->isVisibleOnLayer(layerID) && with->isVisibleOnLayer(layerID); + } return false; } @@ -282,7 +285,9 @@ AreaLink* AreaAddLinkBetweenAreas(Area* area, Area* with, bool warning) assert(with); if (warning && area->id > with->id) + { logs.warning() << "Link: `" << area->id << "` - `" << with->id << "`: Invalid orientation"; + } if (area->id == with->id) { @@ -300,22 +305,41 @@ AreaLink* AreaAddLinkBetweenAreas(Area* area, Area* with, bool warning) namespace // anonymous { + +bool isPropertyUsedForLinkTSgeneration(const std::string& key) +{ + std::array listKeys = {"unitcount", + "nominalcapacity", + "law.planned", + "law.forced", + "volatility.planned", + "volatility.forced", + "force-no-generation"}; + return std::find(listKeys.begin(), listKeys.end(), key) != listKeys.end(); +} + bool AreaLinksInternalLoadFromProperty(AreaLink& link, const String& key, const String& value) { if (key == "hurdles-cost") + { return value.to(link.useHurdlesCost); + } if (key == "loop-flow") + { return value.to(link.useLoopFlow); + } if (key == "use-phase-shifter") + { return value.to(link.usePST); + } if (key == "copper-plate") { bool copperPlate; if (value.to(copperPlate)) { using LocalNTCtype = Data::LocalTransmissionCapacities; - link.transmissionCapacities - = copperPlate ? LocalNTCtype::infinite : LocalNTCtype::enabled; + link.transmissionCapacities = copperPlate ? LocalNTCtype::infinite + : LocalNTCtype::enabled; return true; } return false; @@ -323,15 +347,25 @@ bool AreaLinksInternalLoadFromProperty(AreaLink& link, const String& key, const if (key == "asset-type") { if (value == "ac") + { link.assetType = atAC; + } else if (value == "dc") + { link.assetType = atDC; + } else if (value == "gaz") + { link.assetType = atGas; + } else if (value == "virt") + { link.assetType = atVirt; + } else if (value == "other") + { link.assetType = atOther; + } else { link.assetType = atOther; @@ -342,13 +376,21 @@ bool AreaLinksInternalLoadFromProperty(AreaLink& link, const String& key, const if (key == "link-style") { if (value == "plain") + { link.style = stPlain; + } else if (value == "dot") + { link.style = stDot; + } else if (value == "dash") + { link.style = stDash; + } else if (value == "dotdash") + { link.style = stDotDash; + } else { link.style = stPlain; @@ -356,35 +398,42 @@ bool AreaLinksInternalLoadFromProperty(AreaLink& link, const String& key, const } return true; } + if (key == "link-width") { - link.linkWidth = Math::MinMax(value.to(), 1, 6); + link.linkWidth = std::clamp(value.to(), 1, 6); return true; } if (key == "colorr") { - link.color[0] = Math::MinMax(value.to(), 0, 255); + link.color[0] = std::clamp(value.to(), 0, 255); return true; } if (key == "colorg") { - link.color[1] = Math::MinMax(value.to(), 0, 255); + link.color[1] = std::clamp(value.to(), 0, 255); return true; } if (key == "colorb") { - link.color[2] = Math::MinMax(value.to(), 0, 255); + link.color[2] = std::clamp(value.to(), 0, 255); return true; } if (key == "transmission-capacities") { using LocalNTCtype = Data::LocalTransmissionCapacities; if (value == "enabled") + { link.transmissionCapacities = LocalNTCtype::enabled; + } else if (value == "infinite") + { link.transmissionCapacities = LocalNTCtype::infinite; + } else if (value == "ignore") + { link.transmissionCapacities = LocalNTCtype::null; + } else { link.transmissionCapacities = LocalNTCtype::null; @@ -394,7 +443,9 @@ bool AreaLinksInternalLoadFromProperty(AreaLink& link, const String& key, const } if (key == "display-comments") + { return value.to(link.displayComments); + } if (key == "comments") { link.comments = value; @@ -410,41 +461,42 @@ bool AreaLinksInternalLoadFromProperty(AreaLink& link, const String& key, const link.filterYearByYear = stringIntoDatePrecision(value); return true; } - - return false; + // Properties used by TS generator only. + // We just skip them (otherwise : reading error) + return isPropertyUsedForLinkTSgeneration(key.to()); } -void logLinkDataCheckError(bool& gotFatalError, const AreaLink& link, const String& msg, int hour) +[[noreturn]] void logLinkDataCheckError(const AreaLink& link, const String& msg, int hour) { logs.error() << "Link (" << link.from->name << "/" << link.with->name << "): Invalid values (" << msg << ") for hour " << hour; - gotFatalError = true; + throw Antares::Error::ReadingStudy(); } -void logLinkDataCheckErrorDirectIndirect(bool& gotFatalError, - const AreaLink& link, - uint direct, - uint indirect) +[[noreturn]] void logLinkDataCheckErrorDirectIndirect(const AreaLink& link, + uint direct, + uint indirect) { logs.error() << "Link (" << link.from->name << "/" << link.with->name << "): Found " << direct - << " direct TS " - << " and " << indirect << " indirect TS, expected the same number"; - gotFatalError = true; + << " direct TS " << " and " << indirect + << " indirect TS, expected the same number"; + throw Antares::Error::ReadingStudy(); } } // anonymous namespace -bool AreaLinksLoadFromFolder(Study& study, AreaList* l, Area* area, const AnyString& folder) +bool AreaLinksLoadFromFolder(Study& study, AreaList* areaList, Area* area, const fs::path& folder) { // Assert assert(area); /* Initialize */ - String buffer; - buffer << folder << SEP << "properties.ini"; + fs::path path = folder / "properties.ini"; IniFile ini; - if (!ini.open(buffer)) - return 0; + if (!ini.open(path)) + { + return false; + } bool ret = true; String key; @@ -454,17 +506,16 @@ bool AreaLinksLoadFromFolder(Study& study, AreaList* l, Area* area, const AnyStr for (auto* s = ini.firstSection; s; s = s->next) { // Getting the name of the area - buffer.clear(); - TransformNameIntoID(s->name, buffer); + const std::string targetAreaName = transformNameIntoID(s->name); // Trying to find it - Area* linkedWith = AreaListLFind(l, buffer.c_str()); - if (!linkedWith) + Area* targetArea = AreaListLFind(areaList, targetAreaName.c_str()); + if (!targetArea) { logs.error() << '`' << s->name << "`: Impossible to find the area"; continue; } - AreaLink* lnk = AreaAddLinkBetweenAreas(area, linkedWith); + AreaLink* lnk = AreaAddLinkBetweenAreas(area, targetArea); if (!lnk) { logs.error() << "Impossible to create a link between two areas"; @@ -476,19 +527,16 @@ bool AreaLinksLoadFromFolder(Study& study, AreaList* l, Area* area, const AnyStr link.comments.clear(); link.displayComments = true; - ret = link.loadTimeSeries(study, folder) && ret; + ret = link.loadTimeSeries(study.header.version, folder.string()) && ret; // Checks on loaded link's data if (study.usedByTheSolver) { - // Short names for link's properties - const uint nbDirectTS = link.directCapacities.width; - const uint nbIndirectTS = link.indirectCapacities.width; + const uint nbDirectTS = link.directCapacities.timeSeries.width; + const uint nbIndirectTS = link.indirectCapacities.timeSeries.width; if (nbDirectTS != nbIndirectTS) { - logLinkDataCheckErrorDirectIndirect( - study.gotFatalError, link, nbDirectTS, nbIndirectTS); - return false; + logLinkDataCheckErrorDirectIndirect(link, nbDirectTS, nbIndirectTS); } auto& directHurdlesCost = link.parameters[fhlHurdlesCostDirect]; @@ -499,63 +547,52 @@ bool AreaLinksLoadFromFolder(Study& study, AreaList* l, Area* area, const AnyStr for (uint indexTS = 0; indexTS < nbDirectTS; ++indexTS) { - auto& directCapacities = link.directCapacities[indexTS]; - auto& indirectCapacities = link.indirectCapacities[indexTS]; + const double* directCapacities = link.directCapacities[indexTS]; + const double* indirectCapacities = link.indirectCapacities[indexTS]; // Checks on direct capacities - for (int h = 0; h < HOURS_PER_YEAR; h++) + for (unsigned int h = 0; h < HOURS_PER_YEAR; h++) { if (directCapacities[h] < 0.) { - logLinkDataCheckError(study.gotFatalError, link, "direct capacity < 0", h); - return false; + logLinkDataCheckError(link, "direct capacity < 0", h); } if (directCapacities[h] < loopFlow[h]) { - logLinkDataCheckError( - study.gotFatalError, link, "direct capacity < loop flow", h); - return false; + logLinkDataCheckError(link, "direct capacity < loop flow", h); } } // Checks on indirect capacities - for (int h = 0; h < HOURS_PER_YEAR; h++) + for (unsigned int h = 0; h < HOURS_PER_YEAR; h++) { if (indirectCapacities[h] < 0.) { - logLinkDataCheckError( - study.gotFatalError, link, "indirect capacitity < 0", h); - return false; + logLinkDataCheckError(link, "indirect capacitity < 0", h); } if (indirectCapacities[h] + loopFlow[h] < 0) { - logLinkDataCheckError( - study.gotFatalError, link, "indirect capacity + loop flow < 0", h); - return false; + logLinkDataCheckError(link, "indirect capacity + loop flow < 0", h); } } } // Checks on hurdle costs - for (int h = 0; h < HOURS_PER_YEAR; h++) + for (unsigned int h = 0; h < HOURS_PER_YEAR; h++) { if (directHurdlesCost[h] + indirectHurdlesCost[h] < 0) { - logLinkDataCheckError(study.gotFatalError, - link, + logLinkDataCheckError(link, "hurdle costs direct + hurdle cost indirect < 0", h); - return false; } } // Checks on P. shift min and max - for (int h = 0; h < HOURS_PER_YEAR; h++) + for (unsigned int h = 0; h < HOURS_PER_YEAR; h++) { if (PShiftPlus[h] < PShiftMinus[h]) { - logLinkDataCheckError( - study.gotFatalError, link, "phase shift plus < phase shift minus", h); - return false; + logLinkDataCheckError(link, "phase shift plus < phase shift minus", h); } } } @@ -568,7 +605,9 @@ bool AreaLinksLoadFromFolder(Study& study, AreaList* l, Area* area, const AnyStr key.toLower(); value = p->value; if (!AreaLinksInternalLoadFromProperty(link, key, value)) + { logs.warning() << '`' << p->key << "`: Unknown property"; + } } // From the solver only @@ -590,8 +629,8 @@ bool AreaLinksLoadFromFolder(Study& study, AreaList* l, Area* area, const AnyStr case Data::LocalTransmissionCapacities::null: { // Ignore transmission capacities - link.directCapacities.zero(); - link.indirectCapacities.zero(); + link.directCapacities.timeSeries.zero(); + link.indirectCapacities.timeSeries.zero(); break; } case Data::LocalTransmissionCapacities::infinite: @@ -636,12 +675,12 @@ bool saveAreaLinksTimeSeriesToFolder(const Area* area, const char* const folder) // Save direct capacities time series filename.clear() << capacitiesFolder << SEP << link.with->id << "_direct.txt"; - success = link.directCapacities.saveToCSVFile(filename, 6, false, true) && success; + success = link.directCapacities.saveToFile(filename, true) && success; // Save indirect capacities time series filename.clear() << capacitiesFolder << SEP << link.with->id << "_indirect.txt"; - success = link.indirectCapacities.saveToCSVFile(filename, 6, false, true) && success; + success = link.indirectCapacities.saveToFile(filename, true) && success; } return success; @@ -672,7 +711,9 @@ bool saveAreaLinksConfigurationFileToFolder(const Area* area, const char* const section->add("colorb", link.color[2]); section->add("display-comments", link.displayComments); if (!link.comments.empty()) + { section->add("comments", link.comments); + } section->add("filter-synthesis", datePrecisionIntoString(link.filterSynthesis)); section->add("filter-year-by-year", datePrecisionIntoString(link.filterYearByYear)); } @@ -695,10 +736,14 @@ bool AreaLinksSaveToFolder(const Area* area, const char* const folder) } if (!saveAreaLinksConfigurationFileToFolder(area, folder)) + { return false; + } if (!saveAreaLinksTimeSeriesToFolder(area, folder)) + { return false; + } return true; } @@ -706,7 +751,9 @@ bool AreaLinksSaveToFolder(const Area* area, const char* const folder) void AreaLinkRemove(AreaLink* link) { if (!link) + { return; + } // Asserts assert(link->from); @@ -726,8 +773,8 @@ uint64_t AreaLink::memoryUsage() const { uint64_t to_return = sizeof(AreaLink); to_return += parameters.valuesMemoryUsage(); - to_return += directCapacities.valuesMemoryUsage(); - to_return += indirectCapacities.valuesMemoryUsage(); + to_return += directCapacities.memoryUsage(); + to_return += indirectCapacities.memoryUsage(); return to_return; } diff --git a/src/libs/antares/study/area/links.h b/src/libs/antares/study/area/links.h deleted file mode 100644 index b18d6e28cb..0000000000 --- a/src/libs/antares/study/area/links.h +++ /dev/null @@ -1,225 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_LINKS_H__ -#define __ANTARES_LIBS_STUDY_LINKS_H__ - -#include -#include -#include -#include "../fwd.h" -#include -#include -#include - -//! The minimal allowed value for hurdle costs when not null -#define LINK_MINIMAL_HURDLE_COSTS_NOT_NULL 0.005 - -namespace Antares -{ -namespace Data -{ -struct CompareLinkName; - -/*! -** \brief Definition of a link between two areas (Interconnection) -** -** \ingroup area -*/ -class AreaLink final : public Yuni::NonCopyable -{ -public: - //! Vector of links - using Vector = std::vector; - //! Set of links - using Set = std::set; - //! Map of links - using Map = std::map; - - using NamePair = std::pair; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - AreaLink(); - //! Destructor - ~AreaLink(); - //@} - - bool loadTimeSeries(const Study& study, const AnyString& folder); - - void storeTimeseriesNumbers(Solver::IResultWriter& writer) const; - - //! \name Area - //@{ - /*! - ** \brief Detach the link from the areas - */ - void detach(); - //@} - - //! \name Data management - //@{ - /*! - ** \brief Reverse the link - ** - ** Be careful, this method does not invert the sign of the weight - ** for binding constraints. - */ - void reverse(); - - void resetToDefaultValues(); - - /*! - ** \brief Invalidate all matrices - ** - ** \param reload True to load all missing data - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark the data associated to the link as modified - */ - void markAsModified() const; - //@} - - //! \name Memory management - //@{ - /*! - ** \brief Get the size (bytes) in memory occupied by a `AreaLink` structure - */ - uint64_t memoryUsage() const; - - bool isVisibleOnLayer(const size_t& layerID) const; - - Yuni::String getName() const; - - bool isLinkPhysical() const; - void overrideTransmissionCapacityAccordingToGlobalParameter(GlobalTransmissionCapacities tc); - -private: - bool linkLoadTimeSeries_for_version_below_810(const AnyString& folder); - bool linkLoadTimeSeries_for_version_820_and_later(const AnyString& folder); - NamePair getNamePair() const; - -public: - //! \name Graph - //@{ - //! The orginal Area - Area* from; - //! The other area | Hash ID: with->id - Area* with; - //@} - - //! \name Data - //@{ - /*! - ** \brief Data related to the link - ** - */ - Matrix<> parameters; - Matrix<> directCapacities; - Matrix<> indirectCapacities; - - //! Monte-Carlo - Matrix timeseriesNumbers; - - //! Flag for using loop flow - bool useLoopFlow; - - //! Flag for using the phase shifter - bool usePST; - - //! Flag for using hurdles cost - bool useHurdlesCost; - - //! Flag for the transmission capacities (NTC +infinite) - // previously called copper plate - LocalTransmissionCapacities transmissionCapacities; - //@} - - //! Flag for the asset type (AC/DC/Other) - AssetType assetType; - - //! \name Indexes - //@{ - /*! - ** \brief Index of the link in the entire list if Interconnections - ** - ** \internal This variable must only be used when runtime data are - ** available - */ - uint index; - /*! - ** \brief Index of the link in the list of interconnection of the main area - ** - ** \internal This variable must only be used when runtime data are - ** available - */ - uint indexForArea; - //@} - - //! \name Comments - //@{ - //! Comments - Yuni::String comments; - //! Flag for displaying comments - bool displayComments; - //@} - - //! \name Output filtering - //@{ - //! Print results for the area in the simulation synthesis - uint filterSynthesis; - //! Print results for the area in the year-by-year mode - uint filterYearByYear; - //@} - - //! Colors - int color[3]; - //! Style - StyleType style; - //! link width - int linkWidth; - - friend struct CompareLinkName; -}; // class AreaLink - -struct CompareLinkName final -{ - inline bool operator()(const AreaLink* s1, const AreaLink* s2) const - { - return s1->getNamePair() < s2->getNamePair(); - } -}; - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_LINKS_H__ diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 0526108ee0..de3c2e9b1f 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1,45 +1,45 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../../antares.h" -#include -#include "../study.h" #include -#include "area.h" +#include + +#include + #include #include -#include "constants.h" -#include "antares/study/parts/parts.h" +#include +#include "antares/antares/antares.h" +#include "antares/study//study.h" +#include "antares/study/area/area.h" #include "antares/study/parts/load/prepro.h" +#include "antares/study/parts/parts.h" +#include "antares/utils/utils.h" #define SEP IO::Separator using namespace Yuni; +namespace fs = std::filesystem; + namespace Antares::Data { namespace // anonymous @@ -47,15 +47,19 @@ namespace // anonymous static bool AreaListLoadThermalDataFromFile(AreaList& list, const Clob& filename) { // Reset to 0 - list.each([](Data::Area& area) { - area.thermal.unsuppliedEnergyCost = 0.; - area.thermal.spilledEnergyCost = 0.; - }); + list.each( + [](Data::Area& area) + { + area.thermal.unsuppliedEnergyCost = 0.; + area.thermal.spilledEnergyCost = 0.; + }); IniFile ini; // Try to load the file if (!ini.open(filename)) + { return false; + } auto* section = ini.find("unserverdenergycost"); @@ -66,7 +70,7 @@ static bool AreaListLoadThermalDataFromFile(AreaList& list, const Clob& filename for (IniFile::Property* p = section->firstProperty; p; p = p->next) { id.clear(); - TransformNameIntoID(p->key, id); + id = transformNameIntoID(p->key); Area* area = list.find(id); if (area) { @@ -79,21 +83,29 @@ static bool AreaListLoadThermalDataFromFile(AreaList& list, const Clob& filename // New scheme // MBO 30/10/2014 - Allow negative values - if (Math::Abs(area->thermal.unsuppliedEnergyCost) < 5.e-3) + if (std::abs(area->thermal.unsuppliedEnergyCost) < 5.e-3) + { area->thermal.unsuppliedEnergyCost = 0.; + } else { if (area->thermal.unsuppliedEnergyCost > 5.e4) + { area->thermal.unsuppliedEnergyCost = 5.e4; + } else { if (area->thermal.unsuppliedEnergyCost < -5.e4) + { area->thermal.unsuppliedEnergyCost = -5.e4; + } } } } else + { logs.warning() << filename << ": `" << p->key << "`: Unknown area"; + } } } @@ -106,7 +118,7 @@ static bool AreaListLoadThermalDataFromFile(AreaList& list, const Clob& filename for (IniFile::Property* p = section->firstProperty; p; p = p->next) { id.clear(); - TransformNameIntoID(p->key, id); + id = transformNameIntoID(p->key); auto* area = list.find(id); if (area) { @@ -118,21 +130,29 @@ static bool AreaListLoadThermalDataFromFile(AreaList& list, const Clob& filename // positive"; // MBO 30/10/2014 - allow negative values - if (Math::Abs(area->thermal.spilledEnergyCost) < 5.e-3) + if (std::abs(area->thermal.spilledEnergyCost) < 5.e-3) + { area->thermal.spilledEnergyCost = 0.; + } else { if (area->thermal.spilledEnergyCost > 5.e4) + { area->thermal.spilledEnergyCost = 5.e4; + } else { if (area->thermal.spilledEnergyCost < -5.e4) + { area->thermal.spilledEnergyCost = -5.e4; + } } } } else + { logs.warning() << filename << ": `" << p->key << "`: Unknown area"; + } } } @@ -148,18 +168,26 @@ static bool AreaListSaveThermalDataToFile(const AreaList& list, const AnyString& IniFile ini; IniFile::Section* s = ini.addSection("unserverdenergycost"); - list.each([&](const Data::Area& area) { - // 0 values are skipped - if (!Math::Zero(area.thermal.unsuppliedEnergyCost)) - s->add(area.id, area.thermal.unsuppliedEnergyCost); - }); + list.each( + [&s](const Data::Area& area) + { + // 0 values are skipped + if (!Utils::isZero(area.thermal.unsuppliedEnergyCost)) + { + s->add(area.id, area.thermal.unsuppliedEnergyCost); + } + }); s = ini.addSection("spilledenergycost"); - list.each([&](const Data::Area& area) { - // 0 values are skipped - if (!Math::Zero(area.thermal.spilledEnergyCost)) - s->add(area.id, area.thermal.spilledEnergyCost); - }); + list.each( + [&s](const Data::Area& area) + { + // 0 values are skipped + if (!Utils::isZero(area.thermal.spilledEnergyCost)) + { + s->add(area.id, area.thermal.spilledEnergyCost); + } + }); return ini.save(filename); } @@ -215,11 +243,8 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << area.id; ret = area.load.prepro->saveToFolder(buffer) && ret; } - if (area.load.series) // Series - { - buffer.clear() << folder << SEP << "input" << SEP << "load" << SEP << "series"; - ret = DataSeriesLoadSaveToFolder(area.load.series, area.id, buffer.c_str()) && ret; - } + buffer.clear() << folder << SEP << "input" << SEP << "load" << SEP << "series"; + area.load.series.saveToFolder(area.id, buffer.c_str(), "load_") && ret; } // Solar @@ -230,11 +255,8 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << area.id; ret = area.solar.prepro->saveToFolder(buffer) && ret; } - if (area.solar.series) // Series - { - buffer.clear() << folder << SEP << "input" << SEP << "solar" << SEP << "series"; - ret = DataSeriesSolarSaveToFolder(area.solar.series, area.id, buffer.c_str()) && ret; - } + buffer.clear() << folder << SEP << "input" << SEP << "solar" << SEP << "series"; + ret = area.solar.series.saveToFolder(area.id, buffer.c_str(), "solar_") && ret; } // Hydro @@ -263,11 +285,9 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << area.id; ret = area.wind.prepro->saveToFolder(buffer) && ret; } - if (area.wind.series) // Series - { - buffer.clear() << folder << SEP << "input" << SEP << "wind" << SEP << "series"; - ret = DataSeriesWindSaveToFolder(area.wind.series, area.id, buffer.c_str()) && ret; - } + + buffer.clear() << folder << SEP << "input" << SEP << "wind" << SEP << "series"; + ret = area.wind.series.saveToFolder(area.id, buffer.c_str(), "wind_") && ret; } // Thermal cluster list @@ -296,13 +316,13 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const // Short term storage // save sts in list.ini for this area - buffer.clear() << folder << SEP << "input" << SEP << "st-storage" << SEP << "clusters" - << SEP << area.id; + buffer.clear() << folder << SEP << "input" << SEP << "st-storage" << SEP << "clusters" << SEP + << area.id; ret = area.shortTermStorage.saveToFolder(buffer.c_str()) && ret; // save the series files - buffer.clear() << folder << SEP << "input" << SEP << "st-storage" << SEP << "series" - << SEP << area.id; + buffer.clear() << folder << SEP << "input" << SEP << "st-storage" << SEP << "series" << SEP + << area.id; ret = area.shortTermStorage.saveDataSeriesToFolder(buffer.c_str()) && ret; return ret; @@ -355,7 +375,8 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) return ini.save(buffer); } -AreaList::AreaList(Study& study) : byIndex(nullptr), pStudy(study) +AreaList::AreaList(Study& study): + pStudy(study) { } @@ -380,18 +401,19 @@ AreaLink* AreaListAddLink(AreaList* l, const char area[], const char with[], boo { logs.debug() << " . " << area << " -> " << with; - AreaName name; AreaName givenName = area; - TransformNameIntoID(givenName, name); + AreaName name = transformNameIntoID(givenName); Area* a = AreaListLFind(l, name.c_str()); if (a) { givenName = with; name.clear(); - TransformNameIntoID(givenName, name); + name = transformNameIntoID(givenName); Area* b = l->find(name); if (b && !a->findExistingLinkWith(*b)) + { return AreaAddLinkBetweenAreas(a, b, warning); + } } } return nullptr; @@ -404,7 +426,9 @@ AreaLink* AreaList::findLink(const AreaName& area, const AreaName& with) { auto j = areas.find(with); if (j != areas.end()) + { return (*(i->second)).findExistingLinkWith(*(j->second)); + } } return nullptr; } @@ -416,7 +440,9 @@ const AreaLink* AreaList::findLink(const AreaName& area, const AreaName& with) c { auto j = areas.find(with); if (j != areas.end()) + { return (*(i->second)).findExistingLinkWith(*(j->second)); + } } return nullptr; } @@ -433,7 +459,9 @@ void AreaList::clear() auto end = copy.end(); for (auto i = copy.begin(); i != end; ++i) + { delete i->second; + } } } @@ -482,24 +510,22 @@ Area* AreaList::add(Area* a) } return a; } + Area* addAreaToListOfAreas(AreaList& list, const AnyString& name) { // Initializing names - AreaName cname; - AreaName lname; - cname = name; - TransformNameIntoID(cname, lname); + AreaName lname = transformNameIntoID(name); // Add the area - return AreaListAddFromNames(list, cname, lname); + return AreaListAddFromNames(list, name, lname); } -Area* AreaListAddFromNames(AreaList& list, - const AnyString& name, - const AnyString& lname) +Area* AreaListAddFromNames(AreaList& list, const AnyString& name, const AnyString& lname) { if (!name || !lname) + { return nullptr; + } // Look up if (!AreaListLFind(&list, lname.c_str())) { @@ -515,14 +541,16 @@ Area* AreaListAddFromNames(AreaList& list, return ret; } else + { logs.warning() << "The area `" << name << "` can not be added (dupplicate)"; + } return nullptr; } bool AreaList::loadListFromFile(const AnyString& filename) { - IO::File::Stream file; - if (!file.open(filename)) + std::ifstream file(filename); + if (!file.is_open()) { logs.error() << "I/O error: " << filename << ": Impossible to open the file"; return false; @@ -535,20 +563,21 @@ bool AreaList::loadListFromFile(const AnyString& filename) AreaName name; AreaName lname; // Each lines in the file - String buffer; - buffer.reserve(1024 /* to force the allocation */); + std::string buffer; uint line = 0; - while (file.readline(buffer)) + while (std::getline(file, buffer)) { ++line; // The area name name = buffer; name.trim(" \t\n\r"); if (name.empty()) + { continue; + } lname.clear(); - TransformNameIntoID(name, lname); + lname = transformNameIntoID(name); if (lname.empty()) { logs.warning() << "ignoring invalid area name: `" << name << "`, " << filename @@ -580,18 +609,24 @@ bool AreaList::loadListFromFile(const AnyString& filename) void AreaList::saveLinkListToBuffer(Yuni::Clob& buffer) const { - each([&](const Data::Area& area) { - buffer << area.id << '\n'; - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - buffer << '\t' << (i->second)->with->id << '\n'; - }); + each( + [&buffer](const Data::Area& area) + { + buffer << area.id << '\n'; + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + buffer << '\t' << (i->second)->with->id << '\n'; + } + }); } bool AreaList::saveListToFile(const AnyString& filename) const { if (!filename) + { return false; + } Clob data; { @@ -601,19 +636,23 @@ bool AreaList::saveListToFile(const AnyString& filename) const { auto end = areas.end(); for (auto i = areas.begin(); i != end; ++i) + { list.push_back((i->second)->name.c_str()); + } list.sort(); } { auto end = list.end(); for (auto i = list.begin(); i != end; ++i) + { data << *i << '\n'; + } } } // Writing data into the appropriate file - IO::File::Stream file; - if (file.openRW(filename)) + std::ofstream file(filename); + if (file.is_open()) { file << data; return true; @@ -626,25 +665,29 @@ bool AreaList::preloadAndMarkAsModifiedAllInvalidatedAreas(uint* invalidateCount { bool ret = true; uint count = 0; - each([&](const Data::Area& area) { - if (area.invalidateJIT) - { - logs.info() << "Preparing the area " << area.name; - // invalidating all data belonging to the area - ret = area.forceReload(true) && ret; - // marking the area as modified to force the incremental save - area.markAsModified(); - ++count; - } - }); + each( + [&ret, &count](const Data::Area& area) + { + if (area.invalidateJIT) + { + logs.info() << "Preparing the area " << area.name; + // invalidating all data belonging to the area + ret = area.forceReload(true) && ret; + // marking the area as modified to force the incremental save + area.markAsModified(); + ++count; + } + }); if (invalidateCount) + { *invalidateCount = count; + } return ret; } void AreaList::markAsModified() const { - each([&](const Data::Area& area) { area.markAsModified(); }); + each([](const Data::Area& area) { area.markAsModified(); }); } bool AreaList::saveToFolder(const AnyString& folder) const @@ -726,11 +769,13 @@ bool AreaList::saveToFolder(const AnyString& folder) const ret = AreaListSaveThermalDataToFile(*this, buffer) && ret; // Save all areas - each([&](const Data::Area& area) { - logs.info() << "Exporting the area " << (area.index + 1) << '/' << areas.size() << ": " - << area.name; - ret = AreaListSaveToFolderSingleArea(area, buffer, folder) && ret; - }); + each( + [&ret, &buffer, &folder, this](const Data::Area& area) + { + logs.info() << "Exporting the area " << (area.index + 1) << '/' << areas.size() << ": " + << area.name; + ret = AreaListSaveToFolderSingleArea(area, buffer, folder) && ret; + }); // Hydro // The hydro files must be saved after the area has been invalidated @@ -746,7 +791,7 @@ bool AreaList::saveToFolder(const AnyString& folder) const template static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) { - if (study.header.version >= 830) + if (study.header.version >= StudyVersion(8, 3)) { buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; @@ -764,16 +809,23 @@ static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) auto value = (p->value).toLower(); if (value == "virtual") + { area.adequacyPatchMode = Data::AdequacyPatch::virtualArea; + } else if (value == "inside") + { area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaInsideAdqPatch; + } else + { area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; + } } } } } } + template static bool AreaListLoadFromFolderSingleArea(Study& study, AreaList* list, @@ -781,14 +833,6 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, StringT& buffer, const StudyLoadOptions& options) { - // Progression - options.progressTicks = 0; - options.progressTickCount - = area.thermal.list.size() * (options.loadOnlyNeeded ? 1 : 2) // prepro+series - + 1 // links - + 4 // load,solar,wind,hydro - + 1; // DSM,misc... - // Reset area.filterSynthesis = filterAll; area.filterYearByYear = filterAll; @@ -798,6 +842,7 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, area.spreadSpilledEnergyCost = 0.; bool ret = true; + const auto studyVersion = study.header.version; // DSM, Reserves, D-1 buffer.clear() << study.folderInput << SEP << "reserves" << SEP << area.id << ".txt"; @@ -808,11 +853,17 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, if (study.usedByTheSolver) { if (!study.parameters.include.reserve.dayAhead) + { area.reserves.columnToZero(fhrDayBefore); + } if (!study.parameters.include.reserve.strategic) + { area.reserves.columnToZero(fhrStrategicReserve); + } if (!study.parameters.include.reserve.primary) + { area.reserves.columnToZero(fhrPrimaryReserve); + } } // Fatal hors hydro - Misc Gen. @@ -827,27 +878,25 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, MatrixTestForPositiveValues_LimitWidth(buffer.c_str(), &area.miscGen, fhhPSP); } - ++options.progressTicks; - options.pushProgressLogs(); - // Links { - buffer.clear() << study.folderInput << SEP << "links" << SEP << area.id; - ret = AreaLinksLoadFromFolder(study, list, &area, buffer) && ret; - ++options.progressTicks; - options.pushProgressLogs(); + fs::path folder = fs::path(study.folderInput.c_str()) / "links" / area.id.c_str(); + ret = AreaLinksLoadFromFolder(study, list, &area, folder) && ret; } // UI if (JIT::usedFromGUI) { if (!area.ui) + { area.ui = new AreaUI(); + } buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "ui.ini"; ret = area.ui->loadFromFile(buffer) && ret; } + bool averageTs = (study.usedByTheSolver && study.parameters.derated); // Load { if (area.load.prepro) // Prepro @@ -857,15 +906,12 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, << area.id; ret = area.load.prepro->loadFromFolder(buffer) && ret; } - if (area.load.series && (!options.loadOnlyNeeded || !area.load.prepro)) // Series + if (!options.loadOnlyNeeded || !area.load.prepro) // Series { - buffer.clear() << study.folderInput << SEP << "load" << SEP << "series"; - ret = DataSeriesLoadLoadFromFolder(study, area.load.series, area.id, buffer.c_str()) - && ret; + buffer.clear() << study.folderInput << SEP << "load" << SEP << "series" << SEP + << "load_" << area.id << ".txt"; + ret = area.load.series.loadFromFile(buffer.c_str(), averageTs) && ret; } - - ++options.progressTicks; - options.pushProgressLogs(); } // Solar @@ -877,15 +923,12 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, << area.id; ret = area.solar.prepro->loadFromFolder(buffer) && ret; } - if (area.solar.series && (!options.loadOnlyNeeded || !area.solar.prepro)) // Series + if (!options.loadOnlyNeeded || !area.solar.prepro) // Series { - buffer.clear() << study.folderInput << SEP << "solar" << SEP << "series"; - ret = DataSeriesSolarLoadFromFolder(study, area.solar.series, area.id, buffer.c_str()) - && ret; + buffer.clear() << study.folderInput << SEP << "solar" << SEP << "series" << SEP + << "solar_" << area.id << ".txt"; + ret = area.solar.series.loadFromFile(buffer.c_str(), averageTs) && ret; } - - ++options.progressTicks; - options.pushProgressLogs(); } // Hydro @@ -893,22 +936,41 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, // Allocation buffer.clear() << study.folderInput << SEP << "hydro" << SEP << "allocation" << SEP << area.id << ".ini"; - ret = area.hydro.allocation.loadFromFile(area.id, buffer) && ret; + ret = area.hydro.allocation.loadFromFile(area.id, buffer.c_str()) && ret; if (area.hydro.prepro) /* Hydro */ { // if changes are required, please update reloadXCastData() buffer.clear() << study.folderInput << SEP << "hydro" << SEP << "prepro"; ret = area.hydro.prepro->loadFromFolder(study, area.id, buffer.c_str()) && ret; + ret = area.hydro.prepro->validate(area.id) && ret; + } + + auto* hydroSeries = area.hydro.series; + if (!options.loadOnlyNeeded || !area.hydro.prepro) // Series + { + buffer.clear() << study.folderInput << SEP << "hydro" << SEP << "series"; + ret = hydroSeries->loadGenerationTS(area.id, buffer, studyVersion) && ret; + } + + if (studyVersion < StudyVersion(9, 1)) + { + buffer.clear() << study.folderInput << SEP << "hydro"; + + HydroMaxTimeSeriesReader reader(area.hydro, + area.id.to(), + area.name.to()); + ret = reader.read(buffer, study.usedByTheSolver) && ret; } - if (area.hydro.series && (!options.loadOnlyNeeded || !area.hydro.prepro)) // Series + else { buffer.clear() << study.folderInput << SEP << "hydro" << SEP << "series"; - ret = area.hydro.series->loadFromFolder(study, area.id, buffer) && ret; + ret = hydroSeries->LoadMaxPower(area.id, buffer) && ret; } - ++options.progressTicks; - options.pushProgressLogs(); + hydroSeries->resizeTSinDeratedMode(study.parameters.derated, + studyVersion, + study.usedByTheSolver); } // Wind @@ -920,45 +982,45 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, << area.id; ret = area.wind.prepro->loadFromFolder(buffer) && ret; } - if (area.wind.series && (!options.loadOnlyNeeded || !area.wind.prepro)) // Series + if (!options.loadOnlyNeeded || !area.wind.prepro) // Series { - buffer.clear() << study.folderInput << SEP << "wind" << SEP << "series"; - ret = DataSeriesWindLoadFromFolder(study, area.wind.series, area.id, buffer.c_str()) - && ret; + buffer.clear() << study.folderInput << SEP << "wind" << SEP << "series" << SEP + << "wind_" << area.id << ".txt"; + ret = area.wind.series.loadFromFile(buffer.c_str(), averageTs) && ret; } - - ++options.progressTicks; - options.pushProgressLogs(); } // Thermal cluster list { buffer.clear() << study.folderInput << SEP << "thermal" << SEP << "prepro"; - ret = area.thermal.list.loadPreproFromFolder(study, options, buffer) && ret; + ret = area.thermal.list.loadPreproFromFolder(study, buffer) && ret; + ret = area.thermal.list.validatePrepro(study) && ret; buffer.clear() << study.folderInput << SEP << "thermal" << SEP << "series"; - ret = area.thermal.list.loadDataSeriesFromFolder(study, options, buffer) && ret; + ret = area.thermal.list.loadDataSeriesFromFolder(study, buffer) && ret; ret = area.thermal.list.loadEconomicCosts(study, buffer) && ret; // In adequacy mode, all thermal clusters must be in 'mustrun' mode - if (study.usedByTheSolver && study.parameters.mode == stdmAdequacy) + if (study.usedByTheSolver && study.parameters.mode == SimulationMode::Adequacy) + { area.thermal.list.enableMustrunForEveryone(); + } } // Short term storage - if (study.header.version >= 860) + if (studyVersion >= StudyVersion(8, 6)) { - buffer.clear() << study.folderInput << SEP << "st-storage" << SEP << "series" - << SEP << area.id; + buffer.clear() << study.folderInput << SEP << "st-storage" << SEP << "series" << SEP + << area.id; ret = area.shortTermStorage.loadSeriesFromFolder(buffer.c_str()) && ret; ret = area.shortTermStorage.validate() && ret; } // Renewable cluster list - if (study.header.version >= 810) + if (studyVersion >= StudyVersion(8, 1)) { buffer.clear() << study.folderInput << SEP << "renewables" << SEP << "series"; - ret = area.renewable.list.loadDataSeriesFromFolder(study, options, buffer) && ret; + ret = area.renewable.list.loadDataSeriesFromFolder(study, buffer) && ret; } // Adequacy patch @@ -969,94 +1031,105 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, << "optimization.ini"; IniFile ini; if (!ini.open(buffer)) + { return false; + } - ini.each([&](const IniFile::Section& section) { - for (auto* p = section.firstProperty; p; p = p->next) - { - bool value = p->value.to(); - CString<30, false> tmp; - tmp = p->key; - tmp.toLower(); - if (tmp == "non-dispatchable-power") - { - if (value) - area.nodalOptimization |= anoNonDispatchPower; - continue; - } - if (tmp == "dispatchable-hydro-power") - { - if (value) - area.nodalOptimization |= anoDispatchHydroPower; - continue; - } - if (tmp == "other-dispatchable-power") - { - if (value) - area.nodalOptimization |= anoOtherDispatchPower; - continue; - } - if (tmp == "filter-synthesis") - { - area.filterSynthesis = stringIntoDatePrecision(p->value); - continue; - } - if (tmp == "filter-year-by-year") - { - area.filterYearByYear = stringIntoDatePrecision(p->value); - continue; - } - if (tmp == "spread-unsupplied-energy-cost") - { - if (!p->value.to(area.spreadUnsuppliedEnergyCost)) - { - area.spreadUnsuppliedEnergyCost = 0.; - logs.warning() - << area.name << ": invalid spread for unsupplied energy cost"; - } - continue; - } - if (tmp == "spread-spilled-energy-cost") - { - if (!p->value.to(area.spreadSpilledEnergyCost)) - { - area.spreadSpilledEnergyCost = 0.; - logs.warning() - << area.name << ": invalid spread for spilled energy cost"; - } - continue; - } - - logs.warning() << buffer << ": Unknown property '" << p->key << "'"; - } - }); + ini.each( + [&area, &buffer](const IniFile::Section& section) + { + for (auto* p = section.firstProperty; p; p = p->next) + { + bool value = p->value.to(); + CString<30, false> tmp; + tmp = p->key; + tmp.toLower(); + if (tmp == "non-dispatchable-power") + { + if (value) + { + area.nodalOptimization |= anoNonDispatchPower; + } + continue; + } + if (tmp == "dispatchable-hydro-power") + { + if (value) + { + area.nodalOptimization |= anoDispatchHydroPower; + } + continue; + } + if (tmp == "other-dispatchable-power") + { + if (value) + { + area.nodalOptimization |= anoOtherDispatchPower; + } + continue; + } + if (tmp == "filter-synthesis") + { + area.filterSynthesis = stringIntoDatePrecision(p->value); + continue; + } + if (tmp == "filter-year-by-year") + { + area.filterYearByYear = stringIntoDatePrecision(p->value); + continue; + } + if (tmp == "spread-unsupplied-energy-cost") + { + if (!p->value.to(area.spreadUnsuppliedEnergyCost)) + { + area.spreadUnsuppliedEnergyCost = 0.; + logs.warning() << area.name << ": invalid spread for unsupplied energy cost"; + } + continue; + } + if (tmp == "spread-spilled-energy-cost") + { + if (!p->value.to(area.spreadSpilledEnergyCost)) + { + area.spreadSpilledEnergyCost = 0.; + logs.warning() << area.name << ": invalid spread for spilled energy cost"; + } + continue; + } + + logs.warning() << buffer << ": Unknown property '" << p->key << "'"; + } + }); return ret; } void AreaList::ensureDataIsInitialized(Parameters& params, bool loadOnlyNeeded) { - AreaListEnsureDataLoadTimeSeries(this); - AreaListEnsureDataSolarTimeSeries(this); - AreaListEnsureDataWindTimeSeries(this); AreaListEnsureDataHydroTimeSeries(this); - AreaListEnsureDataThermalTimeSeries(this); - AreaListEnsureDataRenewableTimeSeries(this); if (loadOnlyNeeded) { // Load if (params.isTSGeneratedByPrepro(timeSeriesLoad)) + { AreaListEnsureDataLoadPrepro(this); + } // Solar if (params.isTSGeneratedByPrepro(timeSeriesSolar)) + { AreaListEnsureDataSolarPrepro(this); + } // Hydro if (params.isTSGeneratedByPrepro(timeSeriesHydro)) + { AreaListEnsureDataHydroPrepro(this); + } // Wind if (params.isTSGeneratedByPrepro(timeSeriesWind)) + { AreaListEnsureDataWindPrepro(this); + } } else { @@ -1074,6 +1147,7 @@ bool AreaList::loadFromFolder(const StudyLoadOptions& options) { bool ret = true; Clob buffer; + auto studyVersion = pStudy.header.version; // Load the list of all available areas { @@ -1088,6 +1162,7 @@ bool AreaList::loadFromFolder(const StudyLoadOptions& options) logs.info() << "Loading global hydro data..."; buffer.clear() << pStudy.folderInput << SEP << "hydro"; ret = PartHydro::LoadFromFolder(pStudy, buffer) && ret; + ret = PartHydro::validate(pStudy) && ret; } // Thermal data, specific to areas @@ -1108,23 +1183,23 @@ bool AreaList::loadFromFolder(const StudyLoadOptions& options) Area& area = *(i->second); buffer.clear() << pStudy.folderInput << thermalPlant << area.id; ret = area.thermal.list.loadFromFolder(pStudy, buffer.c_str(), &area) && ret; - area.thermal.prepareAreaWideIndexes(); + ret = area.thermal.list.validateClusters(pStudy.parameters) && ret; } } // Short term storage data, specific to areas - if (pStudy.header.version >= 860) + if (studyVersion >= StudyVersion(8, 6)) { logs.info() << "Loading short term storage clusters..."; - buffer.clear() << pStudy.folderInput << SEP << "st-storage"; + fs::path stsFolder = fs::path(pStudy.folderInput.c_str()) / "st-storage"; - if (IO::Directory::Exists(buffer)) + if (fs::exists(stsFolder)) { - for (const auto& [id, area] : areas) + for (const auto& [id, area]: areas) { - buffer.clear() << pStudy.folderInput << SEP << "st-storage" << SEP << "clusters" << SEP << area->id; - ret = area->shortTermStorage.createSTStorageClustersFromIniFile(buffer.c_str()) - && ret; + fs::path folder = stsFolder / "clusters" / area->id.c_str(); + + ret = area->shortTermStorage.createSTStorageClustersFromIniFile(folder) && ret; } } else @@ -1134,7 +1209,7 @@ bool AreaList::loadFromFolder(const StudyLoadOptions& options) } // Renewable data, specific to areas - if (pStudy.header.version >= 810) + if (studyVersion >= StudyVersion(8, 1)) { // The cluster list must be loaded before the method // ensureDataIsInitialized is called @@ -1148,7 +1223,7 @@ bool AreaList::loadFromFolder(const StudyLoadOptions& options) Area& area = *(i->second); buffer.clear() << pStudy.folderInput << renewablePlant << area.id; ret = area.renewable.list.loadFromFolder(buffer.c_str(), &area) && ret; - area.renewable.prepareAreaWideIndexes(); + ret = area.renewable.list.validateClusters() && ret; } } @@ -1157,15 +1232,17 @@ bool AreaList::loadFromFolder(const StudyLoadOptions& options) // Load all nodes uint indx = 0; - each([&](Data::Area& area) { - // Progression - options.logMessage.clear() - << "Loading the area " << (++indx) << '/' << areas.size() << ": " << area.name; - logs.info() << options.logMessage; - - // Load a single area - ret = AreaListLoadFromFolderSingleArea(pStudy, this, area, buffer, options) && ret; - }); + each( + [&options, &ret, &buffer, &indx, this](Data::Area& area) + { + // Progression + options.logMessage.clear() + << "Loading the area " << (++indx) << '/' << areas.size() << ": " << area.name; + logs.info() << options.logMessage; + + // Load a single area + ret = AreaListLoadFromFolderSingleArea(pStudy, this, area, buffer, options) && ret; + }); // update nameid set updateNameIDSet(); @@ -1186,8 +1263,7 @@ const Area* AreaList::find(const AreaName& id) const Area* AreaList::findFromName(const AreaName& name) { - AreaName id; - TransformNameIntoID(name, id); + AreaName id = transformNameIntoID(name); auto i = this->areas.find(id); return (i != this->areas.end()) ? i->second : nullptr; } @@ -1202,12 +1278,11 @@ Area* AreaList::findFromPosition(const int x, const int y) const for (auto i = this->areas.rbegin(); i != end; ++i) { auto lastArea = i->second; - if (lastArea->ui) - if (Math::Abs(lastArea->ui->x - x) < nearestDistance - && Math::Abs(lastArea->ui->y - y) < nearestDistance) - { - nearestItem = lastArea; - } + if (lastArea->ui && std::abs(lastArea->ui->x - x) < nearestDistance + && std::abs(lastArea->ui->y - y) < nearestDistance) + { + nearestItem = lastArea; + } } return nearestItem; } @@ -1216,8 +1291,7 @@ Area* AreaList::findFromPosition(const int x, const int y) const const Area* AreaList::findFromName(const AreaName& name) const { - AreaName id; - TransformNameIntoID(name, id); + AreaName id = transformNameIntoID(name); auto i = this->areas.find(id); return (i != this->areas.end()) ? i->second : nullptr; } @@ -1240,43 +1314,27 @@ Area* AreaListFindPtr(AreaList* l, const Area* ptr) for (auto i = l->areas.begin(); i != end; ++i) { if (ptr == i->second) + { return i->second; + } } } return nullptr; } -void AreaListEnsureDataLoadTimeSeries(AreaList* l) -{ - /* Asserts */ - assert(l); - - l->each([&](Data::Area& area) { - if (!area.load.series) - area.load.series = new DataSeriesLoad(); - }); -} - void AreaListEnsureDataLoadPrepro(AreaList* l) { /* Asserts */ assert(l); - l->each([&](Data::Area& area) { - if (!area.load.prepro) - area.load.prepro = new Antares::Data::Load::Prepro(); - }); -} - -void AreaListEnsureDataSolarTimeSeries(AreaList* l) -{ - /* Asserts */ - assert(l); - - l->each([&](Data::Area& area) { - if (!area.solar.series) - area.solar.series = new DataSeriesSolar(); - }); + l->each( + [](Data::Area& area) + { + if (!area.load.prepro) + { + area.load.prepro = new Antares::Data::Load::Prepro(); + } + }); } void AreaListEnsureDataSolarPrepro(AreaList* l) @@ -1284,21 +1342,14 @@ void AreaListEnsureDataSolarPrepro(AreaList* l) /* Asserts */ assert(l); - l->each([&](Data::Area& area) { - if (!area.solar.prepro) - area.solar.prepro = new Antares::Data::Solar::Prepro(); - }); -} - -void AreaListEnsureDataWindTimeSeries(AreaList* l) -{ - /* Asserts */ - assert(l); - - l->each([&](Data::Area& area) { - if (!area.wind.series) - area.wind.series = new DataSeriesWind(); - }); + l->each( + [](Data::Area& area) + { + if (!area.solar.prepro) + { + area.solar.prepro = new Antares::Data::Solar::Prepro(); + } + }); } void AreaListEnsureDataWindPrepro(AreaList* l) @@ -1306,10 +1357,14 @@ void AreaListEnsureDataWindPrepro(AreaList* l) /* Asserts */ assert(l); - l->each([&](Data::Area& area) { - if (!area.wind.prepro) - area.wind.prepro = new Antares::Data::Wind::Prepro(); - }); + l->each( + [](Data::Area& area) + { + if (!area.wind.prepro) + { + area.wind.prepro = new Antares::Data::Wind::Prepro(); + } + }); } void AreaListEnsureDataHydroTimeSeries(AreaList* l) @@ -1317,10 +1372,14 @@ void AreaListEnsureDataHydroTimeSeries(AreaList* l) /* Asserts */ assert(l); - l->each([&](Data::Area& area) { - if (!area.hydro.series) - area.hydro.series = new DataSeriesHydro(); - }); + l->each( + [](Data::Area& area) + { + if (!area.hydro.series) + { + area.hydro.series = new DataSeriesHydro(); + } + }); } void AreaListEnsureDataHydroPrepro(AreaList* l) @@ -1328,41 +1387,32 @@ void AreaListEnsureDataHydroPrepro(AreaList* l) /* Asserts */ assert(l); - l->each([&](Data::Area& area) { - if (!area.hydro.prepro) - area.hydro.prepro = new PreproHydro(); - }); -} - -void AreaListEnsureDataThermalTimeSeries(AreaList* l) -{ - assert(l); - l->each([&](Data::Area& area) { area.thermal.list.ensureDataTimeSeries(); }); -} - -void AreaListEnsureDataRenewableTimeSeries(AreaList* l) -{ - assert(l); - l->each([&](Data::Area& area) { area.renewable.list.ensureDataTimeSeries(); }); + l->each( + [](Data::Area& area) + { + if (!area.hydro.prepro) + { + area.hydro.prepro = new PreproHydro(); + } + }); } void AreaListEnsureDataThermalPrepro(AreaList* l) { - assert(l && "The area list must not be nullptr"); - l->each([&](Data::Area& area) { area.thermal.list.ensureDataPrepro(); }); + l->each([](Data::Area& area) { area.thermal.list.ensureDataPrepro(); }); } uint64_t AreaList::memoryUsage() const { uint64_t ret = sizeof(AreaList) + sizeof(Area**) * areas.size(); - each([&](const Data::Area& area) { ret += area.memoryUsage(); }); + each([&ret](const Data::Area& area) { ret += area.memoryUsage(); }); return ret; } uint AreaList::areaLinkCount() const { uint ret = 0; - each([&](const Data::Area& area) { ret += (uint)area.links.size(); }); + each([&ret](const Data::Area& area) { ret += (uint)area.links.size(); }); return ret; } @@ -1381,15 +1431,16 @@ void Area::detachLinkFromItsPointer(const AreaLink* lnk) bool AreaList::renameArea(const AreaName& oldid, const AreaName& newName) { - AreaName newid; - TransformNameIntoID(newName, newid); + AreaName newid = transformNameIntoID(newName); return renameArea(oldid, newid, newName); } bool AreaList::renameArea(const AreaName& oldid, const AreaName& newid, const AreaName& newName) { if (!oldid || !newName || !newid || areas.empty()) + { return false; + } if (CheckForbiddenCharacterInAreaName(newName)) { @@ -1401,7 +1452,9 @@ bool AreaList::renameArea(const AreaName& oldid, const AreaName& newid, const Ar { auto i = areas.find(oldid); if (i == areas.end()) + { return false; + } area = i->second; areas.erase(i); } @@ -1422,26 +1475,30 @@ bool AreaList::renameArea(const AreaName& oldid, const AreaName& newid, const Ar areas[area->id] = area; // We have to update all links connected to this area - each([&](Data::Area& a) { - auto* link = a.findLinkByID(oldid); - if (!link) - return; + each( + [&oldid](Data::Area& a) + { + auto* link = a.findLinkByID(oldid); + if (!link) + { + return; + } #ifndef NDEBUG - uint oldCount = (uint)a.links.size(); + uint oldCount = (uint)a.links.size(); #endif - // Renaming the entry + // Renaming the entry - link->forceReload(true); - link->markAsModified(); + link->forceReload(true); + link->markAsModified(); - link->detach(); - a.links[link->with->id] = link; + link->detach(); + a.links[link->with->id] = link; #ifndef NDEBUG - assert(oldCount == a.links.size() && "We must have the same number of items in the list"); + assert(oldCount == a.links.size() && "We must have the same number of items in the list"); #endif - }); + }); area->buildLinksIndexes(); @@ -1451,33 +1508,39 @@ bool AreaList::renameArea(const AreaName& oldid, const AreaName& newid, const Ar void AreaListDeleteLinkFromAreaPtr(AreaList* list, const Area* a) { if (!list || !a) + { return; + } - list->each([&](Data::Area& area) { - if (!area.links.empty()) - return; - bool mustLoop = false; - do - { - mustLoop = false; - // Foreach link from this area - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - { - AreaLink* lnk = i->second; - - // The link must be destroyed if attached to the given area - if ((lnk->from == a) || (lnk->with == a)) - { - // The reference to this link will be removed and the link will be freed - AreaLinkRemove(lnk); - // Let's start again - mustLoop = true; - break; - } - } - } while (mustLoop); - }); + list->each( + [&a](Data::Area& area) + { + if (!area.links.empty()) + { + return; + } + bool mustLoop = false; + do + { + mustLoop = false; + // Foreach link from this area + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + AreaLink* lnk = i->second; + + // The link must be destroyed if attached to the given area + if ((lnk->from == a) || (lnk->with == a)) + { + // The reference to this link will be removed and the link will be freed + AreaLinkRemove(lnk); + // Let's start again + mustLoop = true; + break; + } + } + } while (mustLoop); + }); } bool AreaList::forceReload(bool reload) const @@ -1491,54 +1554,57 @@ void AreaList::resizeAllTimeseriesNumbers(uint n) { // Ask to resize the matrices dedicated to the sampled timeseries numbers // for each area - each([&](Data::Area& area) { area.resizeAllTimeseriesNumbers(n); }); + each([n](Data::Area& area) { area.resizeAllTimeseriesNumbers(n); }); } -void AreaList::fixOrientationForAllInterconnections(BindingConstraintsRepository& bindingconstraints) -{ - each([&](Data::Area& area) { - bool mustLoop; - // for each link from this area - do - { - // Nothing to do if the area does not have any links - if (area.links.empty()) - break; - - // By default, we don't have to loop forever - mustLoop = false; - - // Foreach link... - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - { - // Reference to the link - auto& link = *(i->second); - // Asserts - assert(&link); - assert(link.from); - assert(link.with); - - if ((link.from)->id > (link.with)->id) - { - // Reversing the link - link.reverse(); - // Updating the binding constraints - bindingconstraints.reverseWeightSign(&link); - // Since the iterators have been compromised, we have to restart the iteration - // through the links - mustLoop = true; - break; - } - } - } while (mustLoop); - }); +void AreaList::fixOrientationForAllInterconnections( + BindingConstraintsRepository& bindingconstraints) +{ + each( + [&bindingconstraints](Data::Area& area) + { + bool mustLoop; + // for each link from this area + do + { + // Nothing to do if the area does not have any links + if (area.links.empty()) + { + break; + } + + // By default, we don't have to loop forever + mustLoop = false; + + // Foreach link... + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + // Reference to the link + auto& link = *(i->second); + // Asserts + assert(link.from); + assert(link.with); + + if ((link.from)->id > (link.with)->id) + { + // Reversing the link + link.reverse(); + // Updating the binding constraints + bindingconstraints.reverseWeightSign(&link); + // Since the iterators have been compromised, we have to restart the iteration + // through the links + mustLoop = true; + break; + } + } + } while (mustLoop); + }); } bool AreaList::remove(const AnyString& id) { - AreaName lname; - TransformNameIntoID(id, lname); + AreaName lname = transformNameIntoID(id); auto i = areas.find(lname); if (i != areas.end()) @@ -1565,10 +1631,14 @@ bool AreaList::remove(const AnyString& id) AreaLink* AreaList::findLinkFromINIKey(const AnyString& key) { if (key.empty()) + { return nullptr; + } auto offset = key.find('%'); if (offset == AreaName::npos || (0 == offset) || (offset == key.size() - 1)) + { return nullptr; + } AreaName from(key.c_str(), offset); AreaName to(key.c_str() + offset + 1, key.size() - (offset + 1)); @@ -1578,17 +1648,22 @@ AreaLink* AreaList::findLinkFromINIKey(const AnyString& key) ThermalCluster* AreaList::findClusterFromINIKey(const AnyString& key) { if (key.empty()) + { return nullptr; + } auto offset = key.find('.'); if (offset == AreaName::npos || (0 == offset) || (offset == key.size() - 1)) + { return nullptr; + } AreaName parentName(key.c_str(), offset); ClusterName id(key.c_str() + offset + 1, key.size() - (offset + 1)); Area* parentArea = findFromName(parentName); if (parentArea == nullptr) + { return nullptr; - ThermalCluster* i = parentArea->thermal.list.find(id); - return (i != nullptr) ? i : nullptr; + } + return parentArea->thermal.list.findInAll(id); } void AreaList::updateNameIDSet() const @@ -1604,36 +1679,41 @@ void AreaList::updateNameIDSet() const void AreaList::removeLoadTimeseries() { - each([&](Data::Area& area) { area.load.series->timeSeries.reset(1, HOURS_PER_YEAR); }); + each([](Data::Area& area) { area.load.series.reset(); }); } void AreaList::removeHydroTimeseries() { - each([&](Data::Area& area) { - area.hydro.series->ror.reset(1, HOURS_PER_YEAR); - area.hydro.series->storage.reset(1, DAYS_PER_YEAR); - area.hydro.series->mingen.reset(1, HOURS_PER_YEAR); - area.hydro.series->count = 1; - }); + each([](Data::Area& area) { area.hydro.series->reset(); }); } void AreaList::removeSolarTimeseries() { - each([&](Data::Area& area) { area.solar.series->timeSeries.reset(1, HOURS_PER_YEAR); }); + each([](Data::Area& area) { area.solar.series.reset(); }); } void AreaList::removeWindTimeseries() { - each([&](Data::Area& area) { area.wind.series->timeSeries.reset(1, HOURS_PER_YEAR); }); + each([](Data::Area& area) { area.wind.series.reset(); }); } void AreaList::removeThermalTimeseries() { - each([&](Data::Area& area) { - area.thermal.list.each( - [&](Data::ThermalCluster& cluster) { cluster.series->timeSeries.reset(1, HOURS_PER_YEAR); }); - }); + each( + [](const Data::Area& area) + { + for (const auto& c: area.thermal.list.all()) + { + c->series.reset(); + } + }); } -} // namespace Antares::Data +Area::ScratchMap AreaList::buildScratchMap(uint numspace) +{ + Area::ScratchMap scratchmap; + each([&scratchmap, &numspace](Area& a) { scratchmap.try_emplace(&a, a.scratchpad[numspace]); }); + return scratchmap; +} +} // namespace Antares::Data diff --git a/src/libs/antares/study/area/scratchpad.cpp b/src/libs/antares/study/area/scratchpad.cpp index 6c63ebf9ac..d0a1637a1d 100644 --- a/src/libs/antares/study/area/scratchpad.cpp +++ b/src/libs/antares/study/area/scratchpad.cpp @@ -1,50 +1,76 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "scratchpad.h" -#include "constants.h" -#include "../study.h" +#include "antares/study/area/scratchpad.h" + #include +#include "antares/antares/antares.h" +#include "antares/study/study.h" + using namespace Yuni; -namespace Antares +namespace Antares::Data { -namespace Data + +bool doWeHaveOnePositiveMaxDailyEnergy(const Matrix& dailyPower, + const Matrix::ColumnType& nbHoursAtPmaxPerDay) +{ + for (uint tsNumber = 0; tsNumber < dailyPower.width; ++tsNumber) + { + for (uint day = 0; day < DAYS_PER_YEAR; ++day) + { + if (dailyPower[tsNumber][day] * nbHoursAtPmaxPerDay[day] > 0.) + { + return true; + } + } + } + + return false; +} + +void CalculateDailyMeanPower(const Matrix::ColumnType& hourlyColumn, + Matrix::ColumnType& dailyColumn) { + for (uint day = 0; day < DAYS_PER_YEAR; ++day) + { + dailyColumn[day] = std::accumulate(hourlyColumn + day * HOURS_PER_DAY, + hourlyColumn + day * HOURS_PER_DAY + HOURS_PER_DAY, + 0) + / 24.; + } +} -AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) +AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area): + meanMaxDailyGenPower(area.hydro.series->timeseriesNumbers), + meanMaxDailyPumpPower(area.hydro.series->timeseriesNumbers) { // alias to the simulation mode auto mode = rinfos.mode; - uint nbMonthsPerYear = 12; for (uint i = 0; i != 168; ++i) + { dispatchableGenerationMargin[i] = 0; + } for (uint h = 0; h != HOURS_PER_YEAR; ++h) { @@ -52,12 +78,6 @@ AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) originalMustrunSum[h] = std::numeric_limits::quiet_NaN(); } - for (uint d = 0; d != DAYS_PER_YEAR; ++d) - { - optimalMaxPower[d] = std::numeric_limits::quiet_NaN(); - pumpingMaxPower[d] = std::numeric_limits::quiet_NaN(); - } - // Fatal hors hydro { double sum; @@ -69,16 +89,51 @@ AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) { sum = 0.; for (w = 0; w != area.miscGen.width; ++w) + { sum += area.miscGen[w][h]; + } miscGenSum[h] = sum; } - if (mode == Data::stdmAdequacy) + if (mode == Data::SimulationMode::Adequacy) { for (uint h = 0; h != area.miscGen.height; ++h) + { miscGenSum[h] -= area.reserves[Data::fhrPrimaryReserve][h]; + } } } + //******************************************************************************* + // TODO : about computing hydro max power daily mean from hourly max power TS. + //******************************************************************************* + // - This computation is done here, but we don't want it here. + // We want Scratchpad to shrink and even disappear. + // So a possible solution to move this computation to some place else is to host + // these means TS in the hydro part of areas, and compute them right after + // their the hourly TS (max power). + // Note that scratchpad instances are duplicated for multi-threading purpose, + // and that moving these TS elsewhere could create concurrency issues. + // But these daily TS, once computed, are then only read (in daily.cpp + // and when building the weekly optimization problem). + // Thus we don't have to fear such issues. + // - Besides, there is a performance problem here : for a given area, we compute + // the max power daily means for each call to scratchpad constructor, that is + // the same computation for each thread. + // This is another reason to move the computation from here. + //******************************************************************************* + + // Hourly maximum generation/pumping power matrices and their number of TS's (width of + // matrices) + const auto& maxHourlyGenPower = area.hydro.series->maxHourlyGenPower.timeSeries; + const auto& maxHourlyPumpPower = area.hydro.series->maxHourlyPumpPower.timeSeries; + + // Setting width and height of daily mean maximum generation/pumping power matrices + meanMaxDailyGenPower.timeSeries.reset(maxHourlyGenPower.width, DAYS_PER_YEAR); + meanMaxDailyPumpPower.timeSeries.reset(maxHourlyPumpPower.width, DAYS_PER_YEAR); + + // Instantiate daily mean maximum generation/pumping power matrices + CalculateMeanDailyMaxPowerMatrices(maxHourlyGenPower, maxHourlyPumpPower); + // =============== // hydroHasMod // =============== @@ -89,20 +144,11 @@ AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) // Useful whether we use a heuristic target or not bool hydroGenerationPermission = false; - // ... Getting hydro max power - auto const& maxPower = area.hydro.maxPower; + // ... Getting hydro max energy + const auto& dailyNbHoursAtGenPmax = area.hydro.dailyNbHoursAtGenPmax[0]; - // ... Hydro max generating power and energy - auto const& maxGenP = maxPower[Data::PartHydro::genMaxP]; - auto const& maxGenE = maxPower[Data::PartHydro::genMaxE]; - - double value = 0.; - for (uint d = 0; d < DAYS_PER_YEAR; ++d) - value += maxGenP[d] * maxGenE[d]; - - // If generating energy is nil over the whole year, hydroGenerationPermission is false, true - // otherwise. - hydroGenerationPermission = (value > 0.); + hydroGenerationPermission = doWeHaveOnePositiveMaxDailyEnergy(meanMaxDailyGenPower.timeSeries, + dailyNbHoursAtGenPmax); // --------------------- // Hydro has inflows @@ -111,7 +157,8 @@ AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) if (!area.hydro.prepro) // not in prepro mode { assert(area.hydro.series); - hydroHasInflows = MatrixTestForAtLeastOnePositiveValue(area.hydro.series->storage); + hydroHasInflows = MatrixTestForAtLeastOnePositiveValue( + area.hydro.series->storage.timeSeries); } else { @@ -120,8 +167,10 @@ AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) auto& colPowerOverWater = m[PreproHydro::powerOverWater]; auto& colMaxEnergy = m[PreproHydro::maximumEnergy]; - for (uint month = 0; month < nbMonthsPerYear; ++month) + for (uint month = 0; month < MONTHS_PER_YEAR; ++month) + { valueCol += colMaxEnergy[month] * (1. - colPowerOverWater[month]); + } hydroHasInflows = (valueCol > 0.); } @@ -131,30 +180,33 @@ AreaScratchpad::AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area) // -------------------------- hydroHasMod = hydroHasInflows || hydroGenerationPermission; - // =============== // Pumping // =============== - // ... Hydro max power - - // ... Hydro max pumping power and energy - auto const& maxPumpingP = maxPower[Data::PartHydro::pumpMaxP]; - auto const& maxPumpingE = maxPower[Data::PartHydro::pumpMaxE]; - - // ... Pumping max power - for (uint d = 0; d != DAYS_PER_YEAR; ++d) - pumpingMaxPower[d] = maxPumpingP[d]; - double valuePumping = 0.; - // ... Computing 'pumpHasMod' parameter - for (uint d = 0; d < DAYS_PER_YEAR; ++d) - valuePumping += maxPumpingP[d] * maxPumpingE[d]; + // Hydro max pumping energy + const auto& dailyNbHoursAtPumpPmax = area.hydro.dailyNbHoursAtPumpPmax[0]; - // If pumping energy is nil over the whole year, pumpHasMod is false, true otherwise. - pumpHasMod = (valuePumping > 0.); + // If pumping energy is nil over the whole year, pumpHasMod is false, true otherwise. + pumpHasMod = doWeHaveOnePositiveMaxDailyEnergy(meanMaxDailyPumpPower.timeSeries, + dailyNbHoursAtPumpPmax); } -AreaScratchpad::~AreaScratchpad() = default; +void AreaScratchpad::CalculateMeanDailyMaxPowerMatrices(const Matrix& hourlyMaxGenMatrix, + const Matrix& hourlyMaxPumpMatrix) +{ + for (uint nbOfTimeSeries = 0; nbOfTimeSeries < hourlyMaxGenMatrix.width; ++nbOfTimeSeries) + { + auto& hourlyMaxGenColumn = hourlyMaxGenMatrix[nbOfTimeSeries]; + auto& MeanMaxDailyGenPowerColumn = meanMaxDailyGenPower.timeSeries[nbOfTimeSeries]; + CalculateDailyMeanPower(hourlyMaxGenColumn, MeanMaxDailyGenPowerColumn); + } -} // namespace Data -} // namespace Antares + for (uint nbOfTimeSeries = 0; nbOfTimeSeries < hourlyMaxPumpMatrix.width; ++nbOfTimeSeries) + { + auto& MeanMaxDailyPumpPowerColumn = meanMaxDailyPumpPower.timeSeries[nbOfTimeSeries]; + auto& hourlyMaxPumpColumn = hourlyMaxPumpMatrix[nbOfTimeSeries]; + CalculateDailyMeanPower(hourlyMaxPumpColumn, MeanMaxDailyPumpPowerColumn); + } +} +} // namespace Antares::Data diff --git a/src/libs/antares/study/area/scratchpad.h b/src/libs/antares/study/area/scratchpad.h deleted file mode 100644 index a41733ba8e..0000000000 --- a/src/libs/antares/study/area/scratchpad.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_AREA_SCRATCHPAD_H__ -#define __ANTARES_LIBS_STUDY_AREA_SCRATCHPAD_H__ - -#include -#include -#include -#include "../fwd.h" -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Scratchpad for temporary data performed by the solver -*/ -class AreaScratchpad final -{ -public: - //! Matrix used for time-series - using TSMatrix = Matrix; - - //! \name Constructor - //@{ - /*! - ** \brief Constructor - */ - AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area); - //! Destructor - ~AreaScratchpad(); - //@} - - //! Sum of all fatal hors hydro - double miscGenSum[HOURS_PER_YEAR]; - - bool hydroHasMod; - - //! if sum(365)[pumpMaxP * pumpMaxE] > 0. then pumpHasMod = true - // else pumpHasMod = false - bool pumpHasMod; - - //! Sum of all 'must-run' clusters - // This variable is initialized every MC-year - double mustrunSum[HOURS_PER_YEAR]; - - //! Sum of all original 'must-run' clusters (adequacy only) - // This variable is initialized every MC-year - double originalMustrunSum[HOURS_PER_YEAR]; - - //! Optimal max power (OPP) - Hydro management - double optimalMaxPower[DAYS_PER_YEAR]; - - //! - double pumpingMaxPower[DAYS_PER_YEAR]; - - /*! - ** \brief Dispatchable Generation Margin - ** - ** Those values, written by the output, must be calculated before - ** running the hydro remix. - */ - double dispatchableGenerationMargin[168]; -}; // class AreaScratchpad - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_AREA_SCRATCHPAD_H__ diff --git a/src/libs/antares/study/area/store-timeseries-numbers.cpp b/src/libs/antares/study/area/store-timeseries-numbers.cpp index ebecde7625..9619206239 100644 --- a/src/libs/antares/study/area/store-timeseries-numbers.cpp +++ b/src/libs/antares/study/area/store-timeseries-numbers.cpp @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include +#include "antares/study/area/store-timeseries-numbers.h" -#include "store-timeseries-numbers.h" +#include +#include +#include using namespace Yuni; @@ -37,60 +31,43 @@ using namespace Yuni; namespace Antares::Data { -namespace // anonymous -{ -struct TSNumbersPredicate +static void storeTSnumbers(Solver::IResultWriter& writer, + const TimeSeriesNumbers& timeseriesNumbers, + const String& id, + const String& directory) { - uint32_t operator()(uint32_t value) const - { - return value + 1; - } -}; -} // anonymous namespace - -static void genericStoreTimeseriesNumbers(Solver::IResultWriter& writer, - const Matrix& timeseriesNumbers, - const String& id, - const String& directory) -{ - TSNumbersPredicate predicate; Clob path; path << "ts-numbers" << SEP << directory << SEP << id << ".txt"; std::string buffer; - timeseriesNumbers.saveToBuffer(buffer, - 0, // precision - true, // print_dimensions - predicate, // predicate - true); // save even if all coeffs are zero + timeseriesNumbers.saveToBuffer(buffer); writer.addEntryFromBuffer(path.c_str(), buffer); } void storeTimeseriesNumbersForLoad(Solver::IResultWriter& writer, const Area& area) { - genericStoreTimeseriesNumbers(writer, area.load.series->timeseriesNumbers, area.id, "load"); + storeTSnumbers(writer, area.load.series.timeseriesNumbers, area.id, "load"); } void storeTimeseriesNumbersForSolar(Solver::IResultWriter& writer, const Area& area) { - genericStoreTimeseriesNumbers(writer, area.solar.series->timeseriesNumbers, area.id, "solar"); + storeTSnumbers(writer, area.solar.series.timeseriesNumbers, area.id, "solar"); } void storeTimeseriesNumbersForHydro(Solver::IResultWriter& writer, const Area& area) { - genericStoreTimeseriesNumbers(writer, area.hydro.series->timeseriesNumbers, area.id, "hydro"); + storeTSnumbers(writer, area.hydro.series->timeseriesNumbers, area.id, "hydro"); } void storeTimeseriesNumbersForWind(Solver::IResultWriter& writer, const Area& area) { - genericStoreTimeseriesNumbers(writer, area.wind.series->timeseriesNumbers, area.id, "wind"); + storeTSnumbers(writer, area.wind.series.timeseriesNumbers, area.id, "wind"); } void storeTimeseriesNumbersForThermal(Solver::IResultWriter& writer, const Area& area) { area.thermal.list.storeTimeseriesNumbers(writer); - area.thermal.mustrunList.storeTimeseriesNumbers(writer); } void storeTimeseriesNumbersForRenewable(Solver::IResultWriter& writer, const Area& area) @@ -98,14 +75,17 @@ void storeTimeseriesNumbersForRenewable(Solver::IResultWriter& writer, const Are area.renewable.list.storeTimeseriesNumbers(writer); } -void storeTimeseriesNumbersForTransmissionCapacities(Solver::IResultWriter& writer, const Area& area) +void storeTimeseriesNumbersForTransmissionCapacities(Solver::IResultWriter& writer, + const Area& area) { // No links originating from this area // do not create an empty directory if (area.links.empty()) + { return; + } - for (const auto& [key, value] : area.links) + for (const auto& [key, value]: area.links) { if (value == nullptr) { @@ -113,8 +93,9 @@ void storeTimeseriesNumbersForTransmissionCapacities(Solver::IResultWriter& writ return; } else + { value->storeTimeseriesNumbers(writer); + } } } } // namespace Antares::Data - diff --git a/src/libs/antares/study/area/store-timeseries-numbers.h b/src/libs/antares/study/area/store-timeseries-numbers.h deleted file mode 100644 index 784856840f..0000000000 --- a/src/libs/antares/study/area/store-timeseries-numbers.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include - -#include "area.h" - -namespace Antares::Data -{ - template - void singleAreaStoreTimeseriesNumbers(Solver::IResultWriter& writer, const Area& area); - - template - void storeTimeseriesNumbers(Solver::IResultWriter& writer, const AreaList& area); - - // Store time-series numbers - void storeTimeseriesNumbersForLoad(Solver::IResultWriter& writer, const Area& area); - void storeTimeseriesNumbersForSolar(Solver::IResultWriter& writer, const Area& area); - void storeTimeseriesNumbersForWind(Solver::IResultWriter& writer, const Area& area); - void storeTimeseriesNumbersForHydro(Solver::IResultWriter& writer, const Area& area); - void storeTimeseriesNumbersForThermal(Solver::IResultWriter& writer, const Area& area); - void storeTimeseriesNumbersForRenewable(Solver::IResultWriter& writer, const Area& area); - void storeTimeseriesNumbersForTransmissionCapacities(Solver::IResultWriter& writer, const Area& area); - -} //Antares::Data - -#include "store-timeseries-numbers.hxx" diff --git a/src/libs/antares/study/area/store-timeseries-numbers.hxx b/src/libs/antares/study/area/store-timeseries-numbers.hxx deleted file mode 100644 index 40cc164399..0000000000 --- a/src/libs/antares/study/area/store-timeseries-numbers.hxx +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_STORE_TIMESERIES_HXX__ -#define __ANTARES_LIBS_STUDY_STORE_TIMESERIES_HXX__ - -namespace Antares::Data -{ -template -void singleAreaStoreTimeseriesNumbers(Solver::IResultWriter& writer, const Area& area) -{ - switch (TimeSeriesT) - { - // Load - case timeSeriesLoad: - storeTimeseriesNumbersForLoad(writer, area); - break; - // Solar - case timeSeriesSolar: - storeTimeseriesNumbersForSolar(writer, area); - break; - // Hydro - case timeSeriesHydro: - storeTimeseriesNumbersForHydro(writer, area); - break; - // Wind - case timeSeriesWind: - storeTimeseriesNumbersForWind(writer, area); - break; - // Thermal - case timeSeriesThermal: - storeTimeseriesNumbersForThermal(writer, area); - break; - // Renewable - case timeSeriesRenewable: - storeTimeseriesNumbersForRenewable(writer, area); - break; - // Transmission capacities (NTC) - case timeSeriesTransmissionCapacities: - storeTimeseriesNumbersForTransmissionCapacities(writer, area); - break; - case timeSeriesCount: - default: - break; - } -} - -template -void storeTimeseriesNumbers(Solver::IResultWriter& writer, const AreaList& area) -{ - // Each area in the list - area.each([&writer](const Area& a) { singleAreaStoreTimeseriesNumbers(writer, a); }); -} -} //namespace Antares::Data - -#endif // __ANTARES_LIBS_STUDY_STORE_TIMESERIES_HXX__ diff --git a/src/libs/antares/study/area/ui.cpp b/src/libs/antares/study/area/ui.cpp index 7717ce1f42..cd3f0bb5fd 100644 --- a/src/libs/antares/study/area/ui.cpp +++ b/src/libs/antares/study/area/ui.cpp @@ -1,36 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "ui.h" -#include -#include -#include +#include "antares/study/area/ui.h" + #include +#include +#include + using namespace Yuni; using namespace Antares; @@ -121,9 +116,13 @@ static inline void AreaColorToHSVModel(const AreaUI& area, StringT& out) else { if (rgb_max == rgb.g) + { hsv.hue = 85 + 43 * (rgb.b - rgb.r) / (rgb_max - rgb_min); + } else // rgb_max == rgb.b */ + { hsv.hue = 171 + 43 * (rgb.r - rgb.g) / (rgb_max - rgb_min); + } } Convert(hsv, out); } @@ -135,19 +134,29 @@ static inline bool AreaUIInternalLoadProperty(AreaUI& ui, const StringT& key, co if (key.size() == 1) { if (key == "x") + { return value.template to(ui.x); + } if (key == "y") + { return value.template to(ui.y); + } } else { // Color if (key == "color_r") + { return value.template to(ui.color[0]); + } if (key == "color_g") + { return value.template to(ui.color[1]); + } if (key == "color_b") + { return value.template to(ui.color[2]); + } if (key == "layers") { std::stringstream stringStream(value.template to()); @@ -156,9 +165,13 @@ static inline bool AreaUIInternalLoadProperty(AreaUI& ui, const StringT& key, co size_t n; stringStream >> n; if (n != 0) + { ui.mapLayersVisibilityList.push_back(n); + } if (stringStream.eof()) + { break; + } } return true; } @@ -169,7 +182,10 @@ static inline bool AreaUIInternalLoadProperty(AreaUI& ui, const StringT& key, co } // anonymous namespace -AreaUI::AreaUI() : x(0), y(0), pModified(true) +AreaUI::AreaUI(): + x(0), + y(0), + pModified(true) { color[0] = defaultRed; color[1] = defaultGreen; @@ -218,12 +234,16 @@ bool AreaUI::loadFromFile(const AnyString& filename) // Property if (!AreaUIInternalLoadProperty(*this, key, value)) + { logs.warning() << ": `" << key << "`: Unknown property"; + } } // Bound checking - limits 0..255 for (uint i = 0; i < 3; ++i) - color[i] = Math::MinMax(color[i], 0, 255); + { + color[i] = std::clamp(color[i], 0, 255); + } pModified = false; } @@ -301,7 +321,9 @@ bool AreaUI::saveToFile(const AnyString& filename, bool force) const data << "[ui]\nx = " << x << "\ny = " << y << "\ncolor_r = " << color[0] << "\ncolor_g = " << color[1] << "\ncolor_b = " << color[2] << "\nlayers ="; for (size_t i = 0, size = mapLayersVisibilityList.size(); i < size; i++) + { data << " " << mapLayersVisibilityList[i]; + } data << '\n'; data << "[layerX]\n"; for (std::map::const_iterator iterator = layerX.begin(); diff --git a/src/libs/antares/study/area/ui.h b/src/libs/antares/study/area/ui.h deleted file mode 100644 index b6f88da488..0000000000 --- a/src/libs/antares/study/area/ui.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_UI_H__ -#define __ANTARES_LIBS_STUDY_UI_H__ - -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Information about the Area for the UI -*/ -class AreaUI final -{ -public: - //! Default constructor - AreaUI(); - - //! Default constructor - ~AreaUI() - { - mapLayersVisibilityList.clear(); - } - - /*! - ** \brief (Re)Initialize all properties - */ - void reset(); - - /*! - ** \brief Load settings from an INI file - */ - bool loadFromFile(const AnyString& filename); - - /*! - ** \brief Save the settings into a file - ** - ** \param filename Filename - ** \param force True to not rely on the modifier flag - */ - bool saveToFile(const AnyString& filename, bool force = false) const; - - /*! - ** \brief Amount of memory consummed by the instance - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Get if the structure has been modified - */ - bool modified() const; - - /*! - ** \brief Mark the structure as modified - */ - void markAsModified(); - - void rebuildCache(); - -public: - //! The X-Coordinate - int x; - std::map layerX; - //! The Y-Coordinate - int y; - std::map layerY; - - //! Color of the area (RGB) - int color[3]; - std::map layerColor; - - //! HSV color model (only computed from the interface) - // \see UIRuntimeInfo::reload() - Yuni::CString<12, false> cacheColorHSV; - - //! The list of layers this Node will appear on - std::vector mapLayersVisibilityList; - -private: - //! Modifier flag - mutable bool pModified; - -}; // class AreaUI - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_UI_H__ diff --git a/src/libs/antares/study/binding_constraint/BindingConstraint.cpp b/src/libs/antares/study/binding_constraint/BindingConstraint.cpp index 8cf038d78f..36acdb1a59 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraint.cpp +++ b/src/libs/antares/study/binding_constraint/BindingConstraint.cpp @@ -1,37 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include +#include "antares/study/binding_constraint/BindingConstraint.h" + #include +#include +#include #include -#include "BindingConstraint.h" -#include "../study.h" -#include "BindingConstraintLoader.h" -#include "BindingConstraintSaver.h" + +#include + +#include "antares/study/binding_constraint/BindingConstraintLoader.h" +#include "antares/study/binding_constraint/BindingConstraintSaver.h" +#include "antares/study/study.h" +#include "antares/utils/utils.h" using namespace Yuni; using namespace Antares; @@ -44,7 +43,8 @@ using namespace Antares; #define SNPRINTF snprintf #endif -namespace Antares::Data { +namespace Antares::Data +{ BindingConstraint::Operator BindingConstraint::StringToOperator(const AnyString& text) { @@ -52,19 +52,27 @@ BindingConstraint::Operator BindingConstraint::StringToOperator(const AnyString& l.toLower(); if (l == "both" || l == "<>" || l == "><" || l == "< and >") + { return opBoth; + } if (l == "less" || l == "<" || l == "<=") + { return opLess; + } if (l == "greater" || l == ">" || l == ">=") + { return opGreater; + } if (l == "equal" || l == "=" || l == "==") + { return opEquality; + } return opUnknown; } BindingConstraint::Type BindingConstraint::StringToType(const AnyString& text) { - if (! text.empty()) + if (!text.empty()) { ShortString16 l(text); l.toLower(); @@ -72,22 +80,28 @@ BindingConstraint::Type BindingConstraint::StringToType(const AnyString& text) { case 'h': { - if (l == "hourly" || l == "hour" || l == "h") - return typeHourly; - break; + if (l == "hourly" || l == "hour" || l == "h") + { + return typeHourly; } + break; + } case 'd': { - if (l == "daily" || l == "day" || l == "d") - return typeDaily; - break; + if (l == "daily" || l == "day" || l == "d") + { + return typeDaily; } + break; + } case 'w': { - if (l == "weekly" || l == "week" || l == "w") - return typeWeekly; - break; + if (l == "weekly" || l == "week" || l == "w") + { + return typeWeekly; } + break; + } } } return typeUnknown; @@ -95,30 +109,34 @@ BindingConstraint::Type BindingConstraint::StringToType(const AnyString& text) const char* BindingConstraint::TypeToCString(const BindingConstraint::Type type) { - static const char *const names[typeMax + 1] = {"", "hourly", "daily", "weekly", ""}; - assert((uint) type < (uint) (typeMax + 1)); + static const char* const names[typeMax + 1] = {"", "hourly", "daily", "weekly", ""}; + assert((uint)type < (uint)(typeMax + 1)); return names[type]; } const char* BindingConstraint::OperatorToCString(BindingConstraint::Operator o) { - static const char *const names[opMax + 1] = {"", "equal", "less", "greater", "both", ""}; - assert((uint) o < (uint) (opMax + 1)); + static const char* const names[opMax + 1] = {"", "equal", "less", "greater", "both", ""}; + assert((uint)o < (uint)(opMax + 1)); return names[o]; } const char* BindingConstraint::OperatorToShortCString(BindingConstraint::Operator o) { - static const char *const names[opMax + 1] - = {"", "equality", "bounded above", "bounded below", "bounded on both sides", ""}; - assert((uint) o < (uint) (opMax + 1)); + static const char* const names[opMax + 1] = {"", + "equality", + "bounded above", + "bounded below", + "bounded on both sides", + ""}; + assert((uint)o < (uint)(opMax + 1)); return names[o]; } const char* BindingConstraint::MathOperatorToCString(BindingConstraint::Operator o) { - static const char *const names[opMax + 1] = {"", "=", "<", ">", "< and >", ""}; - assert((uint) o < (uint) (opMax + 1)); + static const char* const names[opMax + 1] = {"", "=", "<", ">", "< and >", ""}; + assert((uint)o < (uint)(opMax + 1)); return names[o]; } @@ -133,21 +151,28 @@ BindingConstraint::~BindingConstraint() void BindingConstraint::name(const AnyString& newname) { pName = newname; +} + +void BindingConstraint::pId(const AnyString& name) +{ pID.clear(); - Antares::TransformNameIntoID(pName, pID); + pID = transformNameIntoID(name); } void BindingConstraint::weight(const AreaLink* lnk, double w) { if (lnk) { - if (Math::Zero(w)) + if (Utils::isZero(w)) { auto i = pLinkWeights.find(lnk); if (i != pLinkWeights.end()) + { pLinkWeights.erase(i); + } } - else { + else + { pLinkWeights[lnk] = w; } } @@ -157,12 +182,16 @@ void BindingConstraint::weight(const ThermalCluster* cluster, double w) { if (cluster && cluster->isActive()) { - if (Math::Zero(w)) + if (Utils::isZero(w)) { auto i = pClusterWeights.find(cluster); if (i != pClusterWeights.end()) + { pClusterWeights.erase(i); - } else { + } + } + else + { pClusterWeights[cluster] = w; } } @@ -178,14 +207,18 @@ void BindingConstraint::offset(const AreaLink* lnk, int o) { if (lnk) { - if (Math::Zero(o)) + if (Utils::isZero(o)) { auto i = pLinkOffsets.find(lnk); if (i != pLinkOffsets.end()) + { pLinkOffsets.erase(i); + } } else + { pLinkOffsets[lnk] = o; + } } } @@ -193,14 +226,18 @@ void BindingConstraint::offset(const ThermalCluster* cluster, int o) { if (cluster && cluster->isActive()) { - if (Math::Zero(o)) + if (Utils::isZero(o)) { auto i = pClusterOffsets.find(cluster); if (i != pClusterOffsets.end()) + { pClusterOffsets.erase(i); + } } else + { pClusterOffsets[cluster] = o; + } } } @@ -212,10 +249,11 @@ void BindingConstraint::resetToDefaultValues() markAsModified(); } -void BindingConstraint::copyWeights(const Study &study, - const BindingConstraint &rhs, - bool emptyBefore, - Yuni::Bind& translate) +void BindingConstraint::copyWeights( + const Study& study, + const BindingConstraint& rhs, + bool emptyBefore, + const std::function& translate) { if (emptyBefore) { @@ -224,7 +262,9 @@ void BindingConstraint::copyWeights(const Study &study, } if (rhs.pLinkWeights.empty()) + { return; + } AreaName fromID; AreaName withID; @@ -233,7 +273,7 @@ void BindingConstraint::copyWeights(const Study &study, for (auto i = rhs.pLinkWeights.begin(); i != end; ++i) { // Alias to the current link - const AreaLink *sourceLink = i->first; + const AreaLink* sourceLink = i->first; // weight const double weight = i->second; @@ -245,9 +285,11 @@ void BindingConstraint::copyWeights(const Study &study, translate(fromID, sourceLink->from->id); translate(withID, sourceLink->with->id); - const AreaLink *localLink = study.areas.findLink(fromID, withID); + const AreaLink* localLink = study.areas.findLink(fromID, withID); if (localLink) + { pLinkWeights[localLink] = weight; + } } if (!rhs.pClusterWeights.empty()) @@ -256,7 +298,7 @@ void BindingConstraint::copyWeights(const Study &study, for (auto i = rhs.pClusterWeights.begin(); i != end; ++i) { // Alias to the current thermalCluster - const ThermalCluster *thermalCluster = i->first; + const ThermalCluster* thermalCluster = i->first; // weight const double weight = i->second; @@ -265,27 +307,34 @@ void BindingConstraint::copyWeights(const Study &study, AreaName parentID; translate(parentID, thermalCluster->parentArea->id); - const Area *localParent = study.areas.find(parentID); + const Area* localParent = study.areas.find(parentID); if (localParent) { - const ThermalCluster *localTC - = localParent->thermal.list.find(thermalCluster->id()); + const ThermalCluster* localTC = localParent->thermal.list.findInAll( + thermalCluster->id()); if (localTC) + { pClusterWeights[localTC] = weight; + } } } } } -void BindingConstraint::copyOffsets(const Study &study, - const BindingConstraint &rhs, - bool emptyBefore, - Yuni::Bind& translate) +void BindingConstraint::copyOffsets( + const Study& study, + const BindingConstraint& rhs, + bool emptyBefore, + const std::function& translate) { if (emptyBefore) + { pLinkOffsets.clear(); + } if (rhs.pLinkOffsets.empty()) + { return; + } AreaName fromID; AreaName withID; @@ -294,7 +343,7 @@ void BindingConstraint::copyOffsets(const Study &study, for (auto i = rhs.pLinkOffsets.begin(); i != end; ++i) { // Alias to the current link - const AreaLink *sourceLink = i->first; + const AreaLink* sourceLink = i->first; // offset const int offset = i->second; @@ -306,9 +355,11 @@ void BindingConstraint::copyOffsets(const Study &study, translate(fromID, sourceLink->from->id); translate(withID, sourceLink->with->id); - const AreaLink *localLink = study.areas.findLink(fromID, withID); + const AreaLink* localLink = study.areas.findLink(fromID, withID); if (localLink) + { pLinkOffsets[localLink] = offset; + } } if (!rhs.pClusterOffsets.empty()) @@ -317,7 +368,7 @@ void BindingConstraint::copyOffsets(const Study &study, for (auto i = rhs.pClusterOffsets.begin(); i != end; ++i) { // Alias to the current thermalCluster - const ThermalCluster *thermalCluster = i->first; + const ThermalCluster* thermalCluster = i->first; // weight const int offset = i->second; @@ -326,19 +377,22 @@ void BindingConstraint::copyOffsets(const Study &study, AreaName parentID; translate(parentID, thermalCluster->parentArea->id); - const Area *localParent = study.areas.find(parentID); + const Area* localParent = study.areas.find(parentID); if (localParent) { - const ThermalCluster *localTC - = localParent->thermal.list.find(thermalCluster->id()); + const ThermalCluster* localTC = localParent->thermal.list.findInAll( + thermalCluster->id()); if (localTC) + { pClusterOffsets[localTC] = offset; + } } } } } -void BindingConstraint::clear() { +void BindingConstraint::clear() +{ // Name / ID this->pName.clear(); this->pID.clear(); @@ -354,7 +408,6 @@ void BindingConstraint::clear() { this->pEnabled = true; } - void BindingConstraint::reverseWeightSign(const AreaLink* lnk) { auto i = pLinkWeights.find(lnk); @@ -371,14 +424,18 @@ bool BindingConstraint::contains(const Area* area) const for (auto i = pLinkWeights.begin(); i != end; ++i) { if ((i->first)->from == area || (i->first)->with == area) + { return true; + } } const auto tEnd = pClusterWeights.end(); for (auto i = pClusterWeights.begin(); i != tEnd; ++i) { if ((i->first)->parentArea == area) + { return true; + } } return false; @@ -392,18 +449,24 @@ void BindingConstraint::buildFormula(String& s) const for (auto i = pLinkWeights.begin(); i != end; ++i) { if (!first) + { s << " + "; + } SNPRINTF(tmp, sizeof(tmp), "%.2f", i->second); - s << '(' << (const char *) tmp << " x " << (i->first)->getName(); + s << '(' << (const char*)tmp << " x " << (i->first)->getName(); if (auto at = pLinkOffsets.find(i->first); at != pLinkOffsets.end()) { int o = at->second; if (o > 0) + { s << " x (t + " << pLinkOffsets.find(i->first)->second << ')'; + } if (o < 0) - s << " x (t - " << Math::Abs(pLinkOffsets.find(i->first)->second) << ')'; + { + s << " x (t - " << std::abs(pLinkOffsets.find(i->first)->second) << ')'; + } } s << ')'; @@ -414,22 +477,30 @@ void BindingConstraint::buildFormula(String& s) const for (auto i = pClusterWeights.begin(); i != tEnd; ++i) { if (!first) + { s << " + "; + } SNPRINTF(tmp, sizeof(tmp), "%.2f", i->second); - s << '(' << (const char *) tmp << " x " << (i->first)->getFullName(); + s << '(' << (const char*)tmp << " x " << (i->first)->getFullName(); if (auto at = pClusterOffsets.find(i->first); at != pClusterOffsets.end()) { int o = at->second; if (o > 0) + { s << " x (t + " << pClusterOffsets.find(i->first)->second << ')'; + } if (o < 0) - s << " x (t - " << Math::Abs(pClusterOffsets.find(i->first)->second) << ')'; + { + s << " x (t - " << std::abs(pClusterOffsets.find(i->first)->second) << ')'; + } } if (!i->first->isActive()) + { s << " x N/A"; + } s << ')'; first = false; @@ -444,13 +515,13 @@ uint64_t BindingConstraint::memoryUsage() const // Values + RHSTimeSeries().memoryUsage() // Estimation - + pLinkWeights.size() * (sizeof(double) + 3 * sizeof(void *)) + + pLinkWeights.size() * (sizeof(double) + 3 * sizeof(void*)) // Estimation - + pLinkOffsets.size() * (sizeof(int) + 3 * sizeof(void *)) + + pLinkOffsets.size() * (sizeof(int) + 3 * sizeof(void*)) // Estimation - + pClusterWeights.size() * (sizeof(double) + 3 * sizeof(void *)) + + pClusterWeights.size() * (sizeof(double) + 3 * sizeof(void*)) // Estimation - + pClusterOffsets.size() * (sizeof(int) + 3 * sizeof(void *)); + + pClusterOffsets.size() * (sizeof(int) + 3 * sizeof(void*)); } bool BindingConstraint::contains(const BindingConstraint* bc) const @@ -493,15 +564,19 @@ uint BindingConstraint::synthesisFilter() const bool BindingConstraint::hasAllWeightedLinksOnLayer(size_t layerID) { if (layerID == 0 || (linkCount() == 0 && clusterCount() == 0)) + { return true; + } auto endWeights = this->end(); for (auto j = this->begin(); j != endWeights; ++j) { - auto *areaLink = j->first; + auto* areaLink = j->first; if (!areaLink) + { continue; + } if (!areaLink->isVisibleOnLayer(layerID) || j->second == 0) { @@ -514,15 +589,19 @@ bool BindingConstraint::hasAllWeightedLinksOnLayer(size_t layerID) bool BindingConstraint::hasAllWeightedClustersOnLayer(size_t layerID) { if (layerID == 0 || (linkCount() == 0 && clusterCount() == 0)) + { return true; + } auto endWeights = pClusterWeights.end(); for (auto j = pClusterWeights.begin(); j != endWeights; ++j) { - auto *cluster = j->first; + auto* cluster = j->first; if (!cluster) + { continue; + } if (!cluster->isVisibleOnLayer(layerID) || j->second == 0) { @@ -558,13 +637,13 @@ int BindingConstraint::offset(const ThermalCluster* lnk) const BindingConstraintStructures BindingConstraint::initLinkArrays() const { - std::vector linkIndex; + std::vector linkIndex; std::vector linkWeight; std::vector clusterWeight; - std::vector linkOffset; - std::vector clusterOffset; - std::vector clusterIndex; - std::vector clustersAreaIndex; + std::vector linkOffset; + std::vector clusterOffset; + std::vector clusterIndex; + std::vector clustersAreaIndex; linkWeight.resize(linkCount()); linkOffset.resize(linkCount()); @@ -584,35 +663,47 @@ BindingConstraintStructures BindingConstraint::initLinkArrays() const auto offsetIt = pLinkOffsets.find(i->first); if (offsetIt != pLinkOffsets.end()) + { linkOffset[off] = offsetIt->second; + } else + { linkOffset[off] = 0; + } } off = 0; auto cEnd = pClusterWeights.end(); - for (auto i = pClusterWeights.begin(); i != cEnd; ++i) { - if (i->first->isActive()) { + for (auto i = pClusterWeights.begin(); i != cEnd; ++i) + { + if (i->first->isActive()) + { clusterIndex[off] = (i->first)->index; clustersAreaIndex[off] = (i->first)->parentArea->index; clusterWeight[off] = i->second; if (auto offsetIt = pClusterOffsets.find(i->first); offsetIt != pClusterOffsets.end()) + { clusterOffset[off] = offsetIt->second; + } else + { clusterOffset[off] = 0; + } ++off; } } - return {linkIndex, - linkWeight, - clusterWeight, - linkOffset, - clusterOffset, - clusterIndex, - clustersAreaIndex,}; + return { + linkIndex, + linkWeight, + clusterWeight, + linkOffset, + clusterOffset, + clusterIndex, + clustersAreaIndex, + }; } bool BindingConstraint::forceReload(bool reload) const @@ -625,7 +716,7 @@ void BindingConstraint::markAsModified() const RHSTimeSeries().markAsModified(); } -void BindingConstraint::clearAndReset(const AnyString &name, +void BindingConstraint::clearAndReset(const AnyString& name, BindingConstraint::Type newType, BindingConstraint::Operator op) { @@ -650,54 +741,59 @@ void BindingConstraint::clearAndReset(const AnyString &name, { case typeUnknown: { - RHSTimeSeries_.reset(); - logs.error() << "invalid type for " << name << " (got 'unknown')"; - assert(false); - break; - } + RHSTimeSeries_.reset(); + logs.error() << "invalid type for " << name << " (got 'unknown')"; + assert(false); + break; + } case typeHourly: { - RHSTimeSeries_.reset(columnMax, 8784, true); - break; - } + RHSTimeSeries_.reset(columnMax, 8784, true); + break; + } case typeDaily: { - RHSTimeSeries_.reset(columnMax, 366, true); - break; - } + RHSTimeSeries_.reset(columnMax, 366, true); + break; + } case typeWeekly: { - RHSTimeSeries_.reset(columnMax, 366); - break; - } + RHSTimeSeries_.reset(columnMax, 366); + break; + } case typeMax: { - RHSTimeSeries_.reset(0, 0); - logs.error() << "invalid type for " << name; - break; - } + RHSTimeSeries_.reset(0, 0); + logs.error() << "invalid type for " << name; + break; + } } RHSTimeSeries_.markAsModified(); } -std::string BindingConstraint::group() const { +std::string BindingConstraint::group() const +{ return group_; } -void BindingConstraint::group(std::string group_name) { +void BindingConstraint::group(std::string group_name) +{ group_ = std::move(group_name); markAsModified(); } -const Matrix<>& BindingConstraint::RHSTimeSeries() const { +const Matrix<>& BindingConstraint::RHSTimeSeries() const +{ return RHSTimeSeries_; } -Matrix<>& BindingConstraint::RHSTimeSeries() { +Matrix<>& BindingConstraint::RHSTimeSeries() +{ return RHSTimeSeries_; } -void BindingConstraint::copyFrom(BindingConstraint const* original) { +void BindingConstraint::copyFrom(const BindingConstraint* original) +{ clearAndReset(original->name(), original->type(), original->operatorType()); pLinkWeights = original->pLinkWeights; pClusterWeights = original->pClusterWeights; @@ -711,4 +807,4 @@ void BindingConstraint::copyFrom(BindingConstraint const* original) { RHSTimeSeries_.copyFrom(original->RHSTimeSeries_); } -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraint.hxx b/src/libs/antares/study/binding_constraint/BindingConstraint.hxx deleted file mode 100644 index ebf8f9473f..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraint.hxx +++ /dev/null @@ -1,124 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include - -namespace Antares::Data -{ -inline const ConstraintName& BindingConstraint::name() const -{ - return pName; -} - -inline const ConstraintName& BindingConstraint::id() const -{ - return pID; -} - -inline const YString& BindingConstraint::comments() const -{ - return pComments; -} - -inline void BindingConstraint::comments(const AnyString& newcomments) -{ - pComments = newcomments; -} - -inline uint BindingConstraint::linkCount() const -{ - return (uint)pLinkWeights.size(); -} - -inline uint BindingConstraint::clusterCount() const -{ - return (uint)pClusterWeights.size(); -} - -inline bool BindingConstraint::enabled() const -{ - return pEnabled; -} - -inline BindingConstraint::Operator BindingConstraint::operatorType() const -{ - return pOperator; -} - -inline BindingConstraint::Type BindingConstraint::type() const -{ - return pType; -} - -inline void BindingConstraint::setTimeGranularity(Type t) -{ - if (t != typeUnknown and t != typeMax) - pType = t; -} - -inline bool BindingConstraint::skipped() const -{ - return linkCount() == 0 && clusterCount() == 0; -} - -inline bool BindingConstraint::isActive() const { - return enabled() && !skipped(); -} - -inline BindingConstraint::iterator BindingConstraint::begin() { - return pLinkWeights.begin(); -} - -inline BindingConstraint::iterator BindingConstraint::end() { - return pLinkWeights.end(); -} - -inline BindingConstraint::const_iterator BindingConstraint::begin() const { - return pLinkWeights.begin(); -} - -inline BindingConstraint::const_iterator BindingConstraint::end() const { - return pLinkWeights.end(); -} - -template -inline std::string BindingConstraint::timeSeriesFileName(const Env &env) const { - switch (operatorType()) { - case BindingConstraint::opLess: - return std::string() + env.folder.c_str() + Yuni::IO::Separator + id().c_str() + "_lt" + ".txt"; - case BindingConstraint::opGreater: - return std::string() + env.folder.c_str() + Yuni::IO::Separator + id().c_str() + "_gt" + ".txt"; - case BindingConstraint::opEquality: - return std::string() + env.folder.c_str() + Yuni::IO::Separator + id().c_str() + "_eq" + ".txt"; - default: - logs.error("Cannot load/save time series of type other that eq/gt/lt"); - return ""; - } -} - -} // namespace Antares diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintGroup.cpp b/src/libs/antares/study/binding_constraint/BindingConstraintGroup.cpp index 5d955236ff..a6f04530a5 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraintGroup.cpp +++ b/src/libs/antares/study/binding_constraint/BindingConstraintGroup.cpp @@ -1,39 +1,58 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 28/06/23. // -#include "BindingConstraintGroup.h" +#include "antares/study/binding_constraint/BindingConstraintGroup.h" #include #include -namespace Antares::Data { - - void BindingConstraintGroup::add(const std::shared_ptr &constraint) { - constraints_.insert(constraint); - } - - BindingConstraintGroup::BindingConstraintGroup(std::string name) : - name_(std::move(name)) { - - } - - std::set> BindingConstraintGroup::constraints() const { - return constraints_; - } - - void BindingConstraintGroup::fixTSNumbersWhenWidthIsOne() { - if (std::all_of(constraints_.begin(), constraints_.end(), [](auto constraint){ - return constraint->RHSTimeSeries().width == 1; - })) { - timeseriesNumbers.fillColumn(0, 0); - } - } - - unsigned BindingConstraintGroup::numberOfTimeseries() const { - //Assume all BC in a group have the same width - if (constraints_.empty()) return 0; - return (*constraints_.begin())->RHSTimeSeries().width; +namespace Antares::Data +{ + +void BindingConstraintGroup::add(const std::shared_ptr& constraint) +{ + constraints_.insert(constraint); +} + +BindingConstraintGroup::BindingConstraintGroup(std::string name): + name_(std::move(name)) +{ +} + +std::set> BindingConstraintGroup::constraints() const +{ + return constraints_; +} + +unsigned BindingConstraintGroup::numberOfTimeseries() const +{ + // Assume all BC in a group have the same width + if (constraints_.empty()) + { + return 0; } + return (*constraints_.begin())->RHSTimeSeries().width; +} -} // Data \ No newline at end of file +} // namespace Antares::Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintGroup.h b/src/libs/antares/study/binding_constraint/BindingConstraintGroup.h deleted file mode 100644 index 0103fda27d..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintGroup.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// Created by marechaljas on 28/06/23. -// - -#pragma once - -#include -#include "BindingConstraint.h" -namespace Antares::Data { - -class BindingConstraintGroup { -public: - explicit BindingConstraintGroup(std::string name); - - [[nodiscard]] std::string name() { return name_; } - void add(const std::shared_ptr& constraint); - [[nodiscard]] std::set> constraints() const; - void fixTSNumbersWhenWidthIsOne(); - [[nodiscard]] unsigned numberOfTimeseries() const; - -public: - // Public data members - Matrix timeseriesNumbers; - -private: - std::set> constraints_; - std::string name_; -}; - -} // Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.cpp b/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.cpp index 9758b3f35a..b29ad4fba2 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.cpp +++ b/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.cpp @@ -1,102 +1,140 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 28/06/23. // -#include "BindingConstraintGroupRepository.h" +#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" + #include -#include #include -#include "BindingConstraintsRepository.h" -#include "BindingConstraintGroup.h" +#include -namespace Antares::Data { +#include "antares/study/binding_constraint/BindingConstraintGroup.h" +#include "antares/study/binding_constraint/BindingConstraintsRepository.h" - unsigned BindingConstraintGroupRepository::size() const { - return groups_.size(); - } +namespace Antares::Data +{ - bool BindingConstraintGroupRepository::buildFrom(const BindingConstraintsRepository &repository) { - for (const auto& constraint: repository) { - const auto group_found = operator[](constraint->group()); - BindingConstraintGroup* group; - if (group_found) { - group = group_found; - } else { - group = add(constraint->group()); - } - group->add(constraint); - } - return timeSeriesWidthConsistentInGroups(); - } +unsigned BindingConstraintGroupRepository::size() const +{ + return groups_.size(); +} - bool BindingConstraintGroupRepository::timeSeriesWidthConsistentInGroups() const { - bool allConsistent = !std::any_of(groups_.begin(), groups_.end(), [](const auto &group) { - const auto& constraints = group->constraints(); - if (constraints.empty()) - return false; - auto width = (*constraints.begin())->RHSTimeSeries().width; - bool isConsistent = std::all_of(constraints.begin(), constraints.end(), [&width](const std::shared_ptr& bc){ - bool sameWidth = bc->RHSTimeSeries().width == width; - if (!sameWidth) { - logs.error() << "Inconsistent time series width for constraint of the same group. Group at fault: " - << bc->group() - << " .Previous width was " << width - << " new constraint " << bc->name() - << " found with width of " << bc->RHSTimeSeries().width; - } - return sameWidth; - }); - return !isConsistent; - }); - return allConsistent; +bool BindingConstraintGroupRepository::buildFrom(const BindingConstraintsRepository& repository) +{ + for (const auto& constraint: repository) + { + const auto group_found = operator[](constraint->group()); + BindingConstraintGroup* group; + if (group_found) + { + group = group_found; + } + else + { + group = add(constraint->group()); + } + group->add(constraint); } + return timeSeriesWidthConsistentInGroups(); +} - void BindingConstraintGroupRepository::resizeAllTimeseriesNumbers(unsigned int nb_years) { - std::for_each(groups_.begin(), groups_.end(), [&](auto &group) { - group->timeseriesNumbers.clear(); - group->timeseriesNumbers.resize(1, nb_years); - }); - } +bool BindingConstraintGroupRepository::timeSeriesWidthConsistentInGroups() const +{ + bool allConsistent = !std::ranges::any_of( + groups_, + [](const auto& group) + { + const auto& constraints = group->constraints(); + if (constraints.empty()) + { + return false; + } + auto width = (*constraints.begin())->RHSTimeSeries().width; + bool isConsistent = std::ranges::all_of( + constraints, + [&width](const std::shared_ptr& bc) + { + bool sameWidth = bc->RHSTimeSeries().width == width; + if (!sameWidth) + { + logs.error() << "Inconsistent time series width for constraint of the same " + "group. Group at fault: " + << bc->group() << " .Previous width was " << width + << " new constraint " << bc->name() << " found with width of " + << bc->RHSTimeSeries().width; + } + return sameWidth; + }); + return !isConsistent; + }); + return allConsistent; +} - void BindingConstraintGroupRepository::fixTSNumbersWhenWidthIsOne() { - std::for_each(groups_.begin(), groups_.end(), [](auto& group) { - group->fixTSNumbersWhenWidthIsOne(); - }); - } +void BindingConstraintGroupRepository::resizeAllTimeseriesNumbers(unsigned int nb_years) +{ + std::ranges::for_each(groups_, + [&nb_years](auto& group) { group->timeseriesNumbers.reset(nb_years); }); +} - BindingConstraintGroup* BindingConstraintGroupRepository::operator[](const std::string& name) const { - if (auto group = std::find_if(groups_.begin(), groups_.end(), [&name](auto& group_of_constraint) { - return group_of_constraint->name() == name; - }); - group != groups_.end()) - { - return group->get(); - } - return nullptr; +BindingConstraintGroup* BindingConstraintGroupRepository::operator[](const std::string& name) const +{ + if (auto group = std::ranges::find_if(groups_, + [&name](auto& group_of_constraint) + { return group_of_constraint->name() == name; }); + group != groups_.end()) + { + return group->get(); } + return nullptr; +} - BindingConstraintGroupRepository::iterator BindingConstraintGroupRepository::begin() { - return groups_.begin(); - } +BindingConstraintGroupRepository::iterator BindingConstraintGroupRepository::begin() +{ + return groups_.begin(); +} - BindingConstraintGroupRepository::const_iterator - BindingConstraintGroupRepository::begin() const { - return groups_.begin(); - } +BindingConstraintGroupRepository::const_iterator BindingConstraintGroupRepository::begin() const +{ + return groups_.begin(); +} - BindingConstraintGroupRepository::iterator BindingConstraintGroupRepository::end() { - return groups_.end(); - } +BindingConstraintGroupRepository::iterator BindingConstraintGroupRepository::end() +{ + return groups_.end(); +} - BindingConstraintGroupRepository::const_iterator BindingConstraintGroupRepository::end() const { - return groups_.end(); - } +BindingConstraintGroupRepository::const_iterator BindingConstraintGroupRepository::end() const +{ + return groups_.end(); +} - BindingConstraintGroup* BindingConstraintGroupRepository::add(const std::string& name) { - return groups_.emplace_back(std::make_unique(name)).get(); - } +BindingConstraintGroup* BindingConstraintGroupRepository::add(const std::string& name) +{ + return groups_.emplace_back(std::make_unique(name)).get(); +} - void BindingConstraintGroupRepository::clear() { - groups_.clear(); - } -} // Data \ No newline at end of file +void BindingConstraintGroupRepository::clear() +{ + groups_.clear(); +} +} // namespace Antares::Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.h b/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.h deleted file mode 100644 index c39c62f211..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintGroupRepository.h +++ /dev/null @@ -1,47 +0,0 @@ -// -// Created by marechaljas on 28/06/23. -// - -#pragma once - -#include -#include -#include -#include "antares/study/binding_constraint/BindingConstraintGroup.h" -#include "antares/study/fwd.h" -#include "BindingConstraint.h" -#include "BindingConstraintSaver.h" - -namespace Antares::Data { - -class BindingConstraintGroupRepository { -public: - [[nodiscard]] unsigned size() const; - - [[nodiscard]] bool buildFrom(const BindingConstraintsRepository& repository); - - void resizeAllTimeseriesNumbers(unsigned nb_years); - - void fixTSNumbersWhenWidthIsOne(); - - BindingConstraintGroup* operator[](const std::string& name) const; - - using iterator = std::vector>::iterator; - using const_iterator = std::vector>::const_iterator; - - [[nodiscard]] iterator begin(); - [[nodiscard]] const_iterator begin() const; - - [[nodiscard]] iterator end(); - [[nodiscard]] const_iterator end() const; - - BindingConstraintGroup* add(const std::string& name); - void clear(); - -private: - [[nodiscard]] bool timeSeriesWidthConsistentInGroups() const; - - std::vector> groups_; -}; - -} // Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintLoader.cpp b/src/libs/antares/study/binding_constraint/BindingConstraintLoader.cpp index 6858d9c036..f4f157604e 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraintLoader.cpp +++ b/src/libs/antares/study/binding_constraint/BindingConstraintLoader.cpp @@ -1,12 +1,36 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 11/05/23. // -#include "BindingConstraintLoader.h" +#include "antares/study/binding_constraint/BindingConstraintLoader.h" + #include #include -#include "BindingConstraint.h" + #include "yuni/core/string/string.h" + +#include +#include "antares/study/binding_constraint/BindingConstraint.h" #include "antares/study/version.h" namespace Antares::Data @@ -22,7 +46,9 @@ std::vector> BindingConstraintLoader::load(En for (const IniFile::Property* p = env.section->firstProperty; p; p = p->next) { if (p->key.empty()) + { continue; + } if (p->key == "name") { @@ -79,7 +105,9 @@ std::vector> BindingConstraintLoader::load(En if (auto setKey = p->key.find('%'); setKey != 0 && setKey != String::npos) // It is a link { if (bool ret = SeparateValue(env, p, w, o); !ret) + { continue; + } const AreaLink* lnk = env.areaList.findLinkFromINIKey(p->key); if (!lnk) @@ -88,11 +116,15 @@ std::vector> BindingConstraintLoader::load(En << "`: link not found"; continue; } - if (!Math::Zero(w)) + if (!Utils::isZero(w)) + { bc->weight(lnk, w); + } - if (!Math::Zero(o)) + if (!Utils::isZero(o)) + { bc->offset(lnk, o); + } continue; } @@ -108,7 +140,9 @@ std::vector> BindingConstraintLoader::load(En } if (bool ret = SeparateValue(env, p, w, o); !ret) + { continue; + } const ThermalCluster* clstr = env.areaList.findClusterFromINIKey(p->key); if (!clstr) @@ -117,11 +151,15 @@ std::vector> BindingConstraintLoader::load(En << "`: cluster not found"; continue; } - if (!Math::Zero(w)) + if (!Utils::isZero(w)) + { bc->weight(clstr, w); + } - if (!Math::Zero(o)) + if (!Utils::isZero(o)) + { bc->offset(clstr, o); + } continue; } @@ -152,23 +190,12 @@ std::vector> BindingConstraintLoader::load(En << "]: Invalid operator [less,greater,equal,both]"; return {}; } - if (bc->group_.empty()) - { - if (env.version >= version870) - { - logs.error() << env.iniFilename << ": in [" << env.section->name - << "]: Missing mandatory binding constraint group"; - return {}; - } - else // In studies versions < 870, binding constraints have no group. From version 870, antares requires constraints to have a group. - { - bc->group_ = "default"; - } - } // The binding constraint can not be enabled if there is no weight in the table if (bc->pLinkWeights.empty() && bc->pClusterWeights.empty()) + { bc->pEnabled = false; + } switch (bc->operatorType()) { @@ -177,17 +204,19 @@ std::vector> BindingConstraintLoader::load(En case BindingConstraint::opGreater: { if (loadTimeSeries(env, bc.get())) + { return {bc}; + } break; } case BindingConstraint::opBoth: { auto greater_bc = std::make_shared(); greater_bc->copyFrom(bc.get()); - greater_bc->name(bc->name()); + greater_bc->name(bc->name() + "_sup"); greater_bc->pID = bc->pID; greater_bc->operatorType(BindingConstraint::opGreater); - + bc->name(bc->name() + "_inf"); bc->operatorType(BindingConstraint::opLess); if (loadTimeSeries(env, bc.get()) && loadTimeSeries(env, greater_bc.get())) @@ -214,47 +243,51 @@ bool BindingConstraintLoader::SeparateValue(const EnvForLoading& env, CString<64> stringWO = p->value; String::Size setVal = p->value.find('%'); uint occurrence = 0; - stringWO.words("%", [&occurrence, &setVal, &env, &ret, &p, &w, &o](const CString<64>& part) { - if (occurrence == 0) - { - if (setVal == 0) // weight is null - { - if (!part.to(o)) - { - logs.error() << env.iniFilename << ": in [" << env.section->name << "]: `" - << p->key << "`: invalid offset"; - ret = false; - } - } - else // weight is not null - { - if (!part.to(w)) - { - logs.error() << env.iniFilename << ": in [" << env.section->name << "]: `" - << p->key << "`: invalid weight"; - ret = false; - } - } - } + stringWO.words("%", + [&occurrence, &setVal, &env, &ret, &p, &w, &o](const CString<64>& part) + { + if (occurrence == 0) + { + if (setVal == 0) // weight is null + { + if (!part.to(o)) + { + logs.error() << env.iniFilename << ": in [" << env.section->name + << "]: `" << p->key << "`: invalid offset"; + ret = false; + } + } + else // weight is not null + { + if (!part.to(w)) + { + logs.error() << env.iniFilename << ": in [" << env.section->name + << "]: `" << p->key << "`: invalid weight"; + ret = false; + } + } + } - if (occurrence == 1 && setVal != 0 && !part.to(o)) - { - logs.error() << env.iniFilename << ": in [" << env.section->name << "]: `" << p->key - << "`: invalid offset"; - ret = false; - } + if (occurrence == 1 && setVal != 0 && !part.to(o)) + { + logs.error() << env.iniFilename << ": in [" << env.section->name + << "]: `" << p->key << "`: invalid offset"; + ret = false; + } - ++occurrence; - return ret; // continue to iterate - }); + ++occurrence; + return ret; // continue to iterate + }); return ret; } bool BindingConstraintLoader::loadTimeSeries(EnvForLoading& env, BindingConstraint* bindingConstraint) { - if (env.version >= version870) + if (env.version >= StudyVersion(8, 7)) + { return loadTimeSeries(env, bindingConstraint->operatorType(), bindingConstraint); + } return loadTimeSeriesLegacyStudies(env, bindingConstraint); } @@ -300,26 +333,39 @@ bool BindingConstraintLoader::loadTimeSeriesLegacyStudies( &env.matrixBuffer)) { if (bindingConstraint->pComments.empty()) + { logs.info() << " added `" << bindingConstraint->pName << "` (" << BindingConstraint::TypeToCString(bindingConstraint->pType) << ", " << BindingConstraint::OperatorToShortCString(bindingConstraint->pOperator) << ')'; + } else + { logs.info() << " added `" << bindingConstraint->pName << "` (" << BindingConstraint::TypeToCString(bindingConstraint->pType) << ", " << BindingConstraint::OperatorToShortCString(bindingConstraint->pOperator) << ") " << bindingConstraint->pComments; + } // 0 is BindingConstraint::opLess int columnNumber; if (bindingConstraint->operatorType() == BindingConstraint::opLess) + { columnNumber = BindingConstraint::Column::columnInferior; + } else if (bindingConstraint->operatorType() == BindingConstraint::opGreater) + { columnNumber = BindingConstraint::Column::columnSuperior; + } else if (bindingConstraint->operatorType() == BindingConstraint::opEquality) + { columnNumber = BindingConstraint::Column::columnEquality; + } else + { logs.error("Cannot load time series of type other that eq/gt/lt"); + return false; + } bindingConstraint->RHSTimeSeries_.resize(1, height); bindingConstraint->RHSTimeSeries_.pasteToColumn(0, intermediate[columnNumber]); diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintLoader.h b/src/libs/antares/study/binding_constraint/BindingConstraintLoader.h deleted file mode 100644 index 32ca6859f3..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintLoader.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// Created by marechaljas on 11/05/23. -// - -#pragma once - -#include -#include "antares/study/area/area.h" -#include "EnvForLoading.h" -#include "BindingConstraint.h" - -namespace Antares::Data { - -class BindingConstraint; -class BindingConstraintLoader { -public: - std::vector> load(EnvForLoading env); - -private: - static bool SeparateValue(const EnvForLoading &env, const IniFile::Property *p, double &w, int &o); - - bool loadTimeSeries(EnvForLoading &env, BindingConstraint *bindingConstraint); - bool loadTimeSeriesLegacyStudies(EnvForLoading &env, BindingConstraint *bindingConstraint) const; - bool loadTimeSeries(EnvForLoading &env, BindingConstraint::Operator operatorType, BindingConstraint *bindingConstraint) const; -}; - -} // Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintSaver.cpp b/src/libs/antares/study/binding_constraint/BindingConstraintSaver.cpp index bdc9efb741..390f17c8bd 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraintSaver.cpp +++ b/src/libs/antares/study/binding_constraint/BindingConstraintSaver.cpp @@ -1,31 +1,60 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 16/05/23. // -#include "BindingConstraintSaver.h" -#include "BindingConstraint.h" -#include +#include "antares/study/binding_constraint/BindingConstraintSaver.h" + #include + +#include + #include "antares/study/area/area.h" +#include "antares/study/binding_constraint/BindingConstraint.h" #include "antares/study/fwd.h" -namespace Antares::Data { +namespace Antares::Data +{ using namespace Yuni; -bool BindingConstraintSaver::saveToEnv(EnvForSaving& env, const BindingConstraint * bindingConstraint) + +bool BindingConstraintSaver::saveToEnv(EnvForSaving& env, + const BindingConstraint* bindingConstraint) { env.section->add("name", bindingConstraint->pName); env.section->add("id", bindingConstraint->pID); env.section->add("enabled", bindingConstraint->pEnabled); env.section->add("type", BindingConstraint::TypeToCString(bindingConstraint->pType)); - env.section->add("operator", BindingConstraint::OperatorToCString(bindingConstraint->pOperator)); - env.section->add("filter-year-by-year", datePrecisionIntoString(bindingConstraint->pFilterYearByYear)); - env.section->add("filter-synthesis", datePrecisionIntoString(bindingConstraint->pFilterSynthesis)); - - if (!bindingConstraint->group().empty()) - env.section->add("group", bindingConstraint->group()); + env.section->add("operator", + BindingConstraint::OperatorToCString(bindingConstraint->pOperator)); + env.section->add("filter-year-by-year", + datePrecisionIntoString(bindingConstraint->pFilterYearByYear)); + env.section->add("filter-synthesis", + datePrecisionIntoString(bindingConstraint->pFilterSynthesis)); + env.section->add("group", bindingConstraint->group()); if (!bindingConstraint->pComments.empty()) + { env.section->add("comments", bindingConstraint->pComments); + } if (!bindingConstraint->pLinkWeights.empty()) { @@ -37,12 +66,15 @@ bool BindingConstraintSaver::saveToEnv(EnvForSaving& env, const BindingConstrain assert(i->first->from and "Invalid area name"); assert(i->first->with and "Invalid area name"); - const AreaLink &lnk = *(i->first); + const AreaLink& lnk = *(i->first); env.key.clear() << lnk.from->id << '%' << lnk.with->id; String value; value << i->second; - if (bindingConstraint->pLinkOffsets.find(i->first) != bindingConstraint->pLinkOffsets.end()) + if (bindingConstraint->pLinkOffsets.find(i->first) + != bindingConstraint->pLinkOffsets.end()) + { value << '%' << bindingConstraint->pLinkOffsets.at(i->first); + } env.section->add(env.key, value); } } @@ -55,12 +87,15 @@ bool BindingConstraintSaver::saveToEnv(EnvForSaving& env, const BindingConstrain // asserts assert(i->first and "Invalid thermal cluster"); - const ThermalCluster &clstr = *(i->first); + const ThermalCluster& clstr = *(i->first); env.key.clear() << clstr.getFullName(); String value; value << i->second; - if (bindingConstraint->pClusterOffsets.find(i->first) != bindingConstraint->pClusterOffsets.end()) + if (bindingConstraint->pClusterOffsets.find(i->first) + != bindingConstraint->pClusterOffsets.end()) + { value << '%' << bindingConstraint->pClusterOffsets.at(i->first); + } env.section->add(env.key, value); } } @@ -69,4 +104,4 @@ bool BindingConstraintSaver::saveToEnv(EnvForSaving& env, const BindingConstrain env.matrixFilename.clear() << bindingConstraint->timeSeriesFileName(env); return bindingConstraint->RHSTimeSeries_.saveToCSVFile(env.matrixFilename.c_str()); } -} \ No newline at end of file +} // namespace Antares::Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintSaver.h b/src/libs/antares/study/binding_constraint/BindingConstraintSaver.h deleted file mode 100644 index 85ddc2e764..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintSaver.h +++ /dev/null @@ -1,34 +0,0 @@ -// -// Created by marechaljas on 16/05/23. -// - -#pragma once - -#include -#include "antares/study/fwd.h" - -namespace Antares::Data { -class BindingConstraintSaver { -public: - class EnvForSaving final - { - public: - EnvForSaving() = default; - - //! Current section - IniFile::Section* section = nullptr; - - Yuni::Clob folder; - Yuni::Clob matrixFilename; - Yuni::CString<2 * (ant_k_area_name_max_length + 8), false> key; - }; - - /*! - ** \brief Save the binding constraint into a folder and an INI file - ** - ** \param env All information needed to perform the task - ** \return True if the operation succeeded, false otherwise - */ - static bool saveToEnv(EnvForSaving& env, const BindingConstraint *bindingConstraint) ; -}; -} \ No newline at end of file diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintStructures.h b/src/libs/antares/study/binding_constraint/BindingConstraintStructures.h deleted file mode 100644 index 8f3d4466c8..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintStructures.h +++ /dev/null @@ -1,23 +0,0 @@ -// -// Created by marechaljas on 27/06/23. -// - -#pragma once - -#include - -namespace Antares { - namespace Data { - - struct BindingConstraintStructures { - mutable std::vector linkIndex; - mutable std::vector linkWeight; - mutable std::vector clusterWeight; - mutable std::vector linkOffset; - mutable std::vector clusterOffset; - mutable std::vector clusterIndex; - mutable std::vector clustersAreaIndex; - }; - - } // Antares -} // Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.cpp b/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.cpp index 1f1cad3bd4..e68c97d15c 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.cpp +++ b/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.cpp @@ -1,59 +1,102 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 11/05/23. // -#include "BindingConstraintsRepository.h" +#include "antares/study/binding_constraint/BindingConstraintsRepository.h" + #include #include #include #include -#include "BindingConstraint.h" + #include -#include "BindingConstraintLoader.h" -#include "BindingConstraintSaver.h" +#include "antares/study/binding_constraint/BindingConstraint.h" +#include "antares/study/binding_constraint/BindingConstraintLoader.h" +#include "antares/study/binding_constraint/BindingConstraintSaver.h" +#include "antares/utils/utils.h" void Data::BindingConstraintsRepository::clear() { constraints_.clear(); - activeConstraints_.reset(); + activeConstraints_.clear(); } -namespace Antares::Data { -std::shared_ptr BindingConstraintsRepository::find(const AnyString &id) { - for (auto const &i: constraints_) { +namespace Antares::Data +{ +std::shared_ptr BindingConstraintsRepository::find(const AnyString& id) +{ + for (const auto& i: constraints_) + { if (i->id() == id) + { return i; + } } return nullptr; } -std::shared_ptr BindingConstraintsRepository::find(const AnyString &id) const { - for (const auto & i : constraints_) { +std::shared_ptr BindingConstraintsRepository::find( + const AnyString& id) const +{ + for (const auto& i: constraints_) + { if (i->id() == id) + { return i; + } } return nullptr; } -BindingConstraint *BindingConstraintsRepository::findByName(const AnyString &name) { - for (auto const & i : constraints_) { +BindingConstraint* BindingConstraintsRepository::findByName(const AnyString& name) +{ + for (const auto& i: constraints_) + { if (i->name() == name) + { return i.get(); + } } return nullptr; } -const BindingConstraint *BindingConstraintsRepository::findByName(const AnyString &name) const { - for (const auto & i : constraints_) { +const BindingConstraint* BindingConstraintsRepository::findByName(const AnyString& name) const +{ + for (const auto& i: constraints_) + { if (i->name() == name) + { return i.get(); + } } return nullptr; } -void BindingConstraintsRepository::removeConstraintsWhoseNameConstains(const AnyString &filter) { +void BindingConstraintsRepository::removeConstraintsWhoseNameConstains(const AnyString& filter) +{ WhoseNameContains pred(filter); - constraints_.erase(std::remove_if(constraints_.begin(), constraints_.end(), pred), constraints_.end()); + constraints_.erase(std::remove_if(constraints_.begin(), constraints_.end(), pred), + constraints_.end()); } static int valueForSort(BindingConstraint::Operator op) @@ -86,49 +129,56 @@ bool compareConstraints(const std::shared_ptr& s1, } } -std::shared_ptr BindingConstraintsRepository::add(const AnyString &name) +std::shared_ptr BindingConstraintsRepository::add(const AnyString& name) { auto bc = std::make_shared(); bc->name(name); + bc->pId(name); constraints_.push_back(bc); std::sort(constraints_.begin(), constraints_.end(), compareConstraints); return bc; } -std::vector> -BindingConstraintsRepository::LoadBindingConstraint(EnvForLoading env) { +std::vector> BindingConstraintsRepository::LoadBindingConstraint( + EnvForLoading env) +{ BindingConstraintLoader loader; return loader.load(std::move(env)); } -bool BindingConstraintsRepository::saveToFolder(const AnyString &folder) const { +bool BindingConstraintsRepository::saveToFolder(const AnyString& folder) const +{ BindingConstraintSaver::EnvForSaving env; env.folder = folder; return internalSaveToFolder(env); } -bool BindingConstraintsRepository::rename(BindingConstraint *bc, const AnyString &newname) { +bool BindingConstraintsRepository::rename(BindingConstraint* bc, const AnyString& newname) +{ // Copy of the name ConstraintName name; name = newname; if (name == bc->name()) + { return true; - ConstraintName id; - Antares::TransformNameIntoID(name, id); - if (std::any_of(constraints_.begin(), constraints_.end(), [&id](auto constraint) { - return constraint->id() == id; - })) + } + ConstraintName id = Antares::transformNameIntoID(name); + if (std::any_of(constraints_.begin(), + constraints_.end(), + [&id](auto constraint) { return constraint->id() == id; })) { return false; } bc->name(name); + bc->pId(name); JIT::Invalidate(bc->RHSTimeSeries().jit); return true; } -bool BindingConstraintsRepository::loadFromFolder(Study &study, - const StudyLoadOptions &options, - const AnyString &folder) { +bool BindingConstraintsRepository::loadFromFolder(Study& study, + const StudyLoadOptions& options, + const AnyString& folder) +{ // Log entries logs.info(); // space for beauty logs.info() << "Loading constraints..."; @@ -136,12 +186,15 @@ bool BindingConstraintsRepository::loadFromFolder(Study &study, // Cleaning clear(); - if (study.usedByTheSolver) { - if (options.ignoreConstraints) { + if (study.usedByTheSolver) + { + if (options.ignoreConstraints) + { logs.info() << " The constraints have been disabled by the user"; return true; } - if (!study.parameters.include.constraints) { + if (!study.parameters.include.constraints) + { logs.info() << " The constraints shall be ignored due to the optimization preferences"; return true; } @@ -152,15 +205,19 @@ bool BindingConstraintsRepository::loadFromFolder(Study &study, env.iniFilename << env.folder << Yuni::IO::Separator << "bindingconstraints.ini"; IniFile ini; - if (!ini.open(env.iniFilename)) { + if (!ini.open(env.iniFilename)) + { return false; } // For each section - if (ini.firstSection) { - for (env.section = ini.firstSection; env.section; env.section = env.section->next) { - if (env.section->firstProperty) { - auto new_bc = LoadBindingConstraint(env); + if (ini.firstSection) + { + for (env.section = ini.firstSection; env.section; env.section = env.section->next) + { + if (env.section->firstProperty) + { + auto new_bc = LoadBindingConstraint(env); std::copy(new_bc.begin(), new_bc.end(), std::back_inserter(constraints_)); } } @@ -168,20 +225,27 @@ bool BindingConstraintsRepository::loadFromFolder(Study &study, // Logs if (constraints_.empty()) + { logs.info() << "No binding constraint found"; + } else { std::sort(constraints_.begin(), constraints_.end(), compareConstraints); if (constraints_.size() == 1) + { logs.info() << "1 binding constraint found"; + } else + { logs.info() << constraints_.size() << " binding constraints found"; + } } // When ran from the solver and if the simplex is in `weekly` mode, // all weekly constraints will become daily ones. - if (study.usedByTheSolver && sorDay == study.parameters.simplexOptimizationRange) { + if (study.usedByTheSolver && sorDay == study.parameters.simplexOptimizationRange) + { changeConstraintsWeeklyToDaily(); } @@ -190,46 +254,55 @@ bool BindingConstraintsRepository::loadFromFolder(Study &study, void BindingConstraintsRepository::changeConstraintsWeeklyToDaily() { - each([](BindingConstraint &constraint) { - if (constraint.type() == BindingConstraint::typeWeekly) - { - logs.info() << " The type of the constraint '" << constraint.name() - << "' is now 'daily'"; - constraint.setTimeGranularity(BindingConstraint::typeDaily); - } - }); + each( + [](BindingConstraint& constraint) + { + if (constraint.type() == BindingConstraint::typeWeekly) + { + logs.info() << " The type of the constraint '" << constraint.name() + << "' is now 'daily'"; + constraint.setTimeGranularity(BindingConstraint::typeDaily); + } + }); } -bool BindingConstraintsRepository::internalSaveToFolder(BindingConstraintSaver::EnvForSaving& env) const +bool BindingConstraintsRepository::internalSaveToFolder( + BindingConstraintSaver::EnvForSaving& env) const { if (constraints_.empty()) { logs.info() << "No binding constraint to export."; if (!Yuni::IO::Directory::Create(env.folder)) + { return false; + } // stripping the file env.folder << Yuni::IO::Separator << "bindingconstraints.ini"; return Yuni::IO::File::CreateEmptyFile(env.folder); } if (constraints_.size() == 1) + { logs.info() << "Exporting 1 binding constraint..."; + } else + { logs.info() << "Exporting " << constraints_.size() << " binding constraints..."; + } if (!Yuni::IO::Directory::Create(env.folder)) + { return false; + } IniFile ini; bool ret = true; uint index = 0; auto end = constraints_.end(); - Yuni::ShortString64 text; for (auto i = constraints_.begin(); i != end; ++i, ++index) { - text = index; - env.section = ini.addSection(text); + env.section = ini.addSection(std::to_string(index)); ret = Antares::Data::BindingConstraintSaver::saveToEnv(env, i->get()) && ret; } @@ -239,41 +312,44 @@ bool BindingConstraintsRepository::internalSaveToFolder(BindingConstraintSaver:: void BindingConstraintsRepository::reverseWeightSign(const AreaLink* lnk) { - each([&lnk](BindingConstraint &constraint) { constraint.reverseWeightSign(lnk); }); + each([&lnk](BindingConstraint& constraint) { constraint.reverseWeightSign(lnk); }); } uint64_t BindingConstraintsRepository::memoryUsage() const { uint64_t m = sizeof(BindingConstraintsRepository); - for (const auto & i : constraints_) + for (const auto& i: constraints_) + { m += i->memoryUsage(); + } return m; } namespace // anonymous { - template - class RemovePredicate final +template +class RemovePredicate final +{ +public: + explicit RemovePredicate(const T* u): + pItem(u) { - public: - explicit RemovePredicate(const T* u) : pItem(u) - { - } + } - bool operator()(const std::shared_ptr& bc) const + bool operator()(const std::shared_ptr& bc) const + { + assert(bc); + if (bc->contains(pItem)) { - assert(bc); - if (bc->contains(pItem)) - { - logs.info() << "destroying the binding constraint " << bc->name(); - return true; - } - return false; + logs.info() << "destroying the binding constraint " << bc->name(); + return true; } + return false; + } - private: - const T *pItem; - }; +private: + const T* pItem; +}; } // anonymous namespace @@ -282,7 +358,7 @@ void BindingConstraintsRepository::remove(const Area* area) RemovePredicate predicate(area); auto e = std::remove_if(constraints_.begin(), constraints_.end(), predicate); constraints_.erase(e, constraints_.end()); - activeConstraints_.reset(); + activeConstraints_.clear(); } void BindingConstraintsRepository::remove(const AreaLink* lnk) @@ -290,7 +366,7 @@ void BindingConstraintsRepository::remove(const AreaLink* lnk) RemovePredicate predicate(lnk); auto e = std::remove_if(constraints_.begin(), constraints_.end(), predicate); constraints_.erase(e, constraints_.end()); - activeConstraints_.reset(); + activeConstraints_.clear(); } void BindingConstraintsRepository::remove(const BindingConstraint* bc) @@ -298,10 +374,9 @@ void BindingConstraintsRepository::remove(const BindingConstraint* bc) RemovePredicate predicate(bc); auto e = std::remove_if(constraints_.begin(), constraints_.end(), predicate); constraints_.erase(e, constraints_.end()); - activeConstraints_.reset(); + activeConstraints_.clear(); } - BindingConstraintsRepository::iterator BindingConstraintsRepository::begin() { return constraints_.begin(); @@ -324,54 +399,63 @@ BindingConstraintsRepository::const_iterator BindingConstraintsRepository::end() void BindingConstraintsRepository::markAsModified() const { - for (const auto & i : constraints_) + for (const auto& i: constraints_) + { i->markAsModified(); + } } -std::vector> BindingConstraintsRepository::activeContraints() const { - if (activeConstraints_) { - return activeConstraints_.value(); - } else { - std::vector> out; - std::copy_if(constraints_.begin(), constraints_.end(), std::back_inserter(out), - [](const auto &bc) { - return bc->isActive(); - }); - activeConstraints_ = std::move(out); - return activeConstraints_.value(); +std::vector> BindingConstraintsRepository::activeConstraints() + const +{ + if (!activeConstraints_.empty()) + { + return activeConstraints_; } + + for (auto& bc: constraints_) + { + if (bc->isActive()) + { + activeConstraints_.push_back(bc); + } + } + + return activeConstraints_; } static bool isBindingConstraintTypeInequality(const Data::BindingConstraint& bc) { - return bc.operatorType() == BindingConstraint::opLess || bc.operatorType() == BindingConstraint::opGreater; + return bc.operatorType() == BindingConstraint::opLess + || bc.operatorType() == BindingConstraint::opGreater; } -std::vector BindingConstraintsRepository::getIndicesForInequalityBindingConstraints() const +BindingConstraintsRepository::Vector +BindingConstraintsRepository::getPtrForInequalityBindingConstraints() const { - auto activeConstraints = activeContraints(); - const auto firstBC = activeConstraints.begin(); - const auto lastBC = activeConstraints.end(); + auto activeBC = activeConstraints(); + Vector ptr; - std::vector indices; - for (auto bc = firstBC; bc < lastBC; bc++) + for (auto& bc: activeBC) { - if (isBindingConstraintTypeInequality(*(*bc))) + if (isBindingConstraintTypeInequality(*bc)) { - auto index = static_cast(std::distance(firstBC, bc)); - indices.push_back(index); + ptr.push_back(bc); } } - return indices; + + return ptr; } void BindingConstraintsRepository::forceReload(bool reload) const { if (!constraints_.empty()) { - for (const auto & i : constraints_) + for (const auto& i: constraints_) + { i->forceReload(reload); + } } } -} +} // namespace Antares::Data diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.h b/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.h deleted file mode 100644 index 1ea09fa227..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.h +++ /dev/null @@ -1,182 +0,0 @@ -// -// Created by marechaljas on 11/05/23. -// - -#pragma once - -#include -#include -#include "BindingConstraint.h" -#include "BindingConstraintSaver.h" - -namespace Antares::Data { -class BindingConstraintsRepository final : public Yuni::NonCopyable -{ -public: - //! Vector of binding constraints - using Vector = std::vector>; - //! Ordered Set of binding constraints - using Set = std::set, CompareBindingConstraintName>; - - using iterator = Vector::iterator; - using const_iterator = Vector::const_iterator; - - //! \name Constructor && Destructor - //@{ - /*! - ** \brief Default constructor - */ - BindingConstraintsRepository() = default; - /*! - ** \brief Destructor - */ - ~BindingConstraintsRepository() = default; - //@} - - /*! - ** \brief Delete all constraints - */ - void clear(); - - //! \name Iterating through all constraints - //@{ - /*! - ** \brief Iterate through all constraints - */ - template - void each(const PredicateT& predicate); - /*! - ** \brief Iterate through all constraints (const) - */ - template - void each(const PredicateT& predicate) const; - - iterator begin(); - [[nodiscard]] const_iterator begin() const; - - iterator end(); - [[nodiscard]] const_iterator end() const; - - [[nodiscard]] bool empty() const; - //@} - - /*! - ** \brief Add a new binding constraint - */ - std::shared_ptr add(const AnyString& name); - - /*! - ** Try to find a constraint from its id - */ - std::shared_ptr find(const AnyString& id); - - /*! - ** \brief Try to find a constraint from its id (const) - */ - [[nodiscard]] std::shared_ptr find(const AnyString& id) const; - - /*! -** \brief Try to find a constraint from its name -*/ - [[nodiscard]] Data::BindingConstraint* findByName(const AnyString& name); - - /*! - ** \brief Try to find a constraint from its name (const) - */ - [[nodiscard]] const Data::BindingConstraint* findByName(const AnyString& name) const; - - /*! - ** \brief Load all binding constraints from a folder - */ - [[nodiscard]] bool loadFromFolder(Data::Study& s, const Data::StudyLoadOptions& options, const AnyString& folder); - - /*! - ** \brief Save all binding constraints into a folder - */ - [[nodiscard]] bool saveToFolder(const AnyString& folder) const; - - /*! - ** \brief Reverse the sign of the weight for a given interconnection or thermal cluster - ** - ** This method is used when reverting an interconnection or thermal cluster - */ - void reverseWeightSign(const Data::AreaLink* lnk); - - //! Get the number of binding constraints - [[nodiscard]] uint size() const; - - /*! - ** \brief Remove a binding constraint - */ - void remove(const Data::BindingConstraint* bc); - /*! - ** \brief Remove any binding constraint linked with a given area - */ - void remove(const Data::Area* area); - /*! - ** \brief Remove any binding constraint linked with a given interconnection - */ - void remove(const Data::AreaLink* area); - - /*! - ** \brief Remove any binding constraint whose name contains the string in argument - */ - void removeConstraintsWhoseNameConstains(const AnyString& filter); - - /*! - ** \brief Rename a binding constraint - */ - bool rename(Data::BindingConstraint* bc, const AnyString& newname); - - /*! - ** \brief Convert all weekly constraints into daily ones - */ - void changeConstraintsWeeklyToDaily(); - - /*! - ** \brief Get the memory usage - */ - [[nodiscard]] uint64_t memoryUsage() const; - - /*! - ** \brief Invalidate all matrices of all binding constraints - */ - void forceReload(bool reload = false) const; - - /*! - ** \brief Mark the constraint as modified - */ - void markAsModified() const; - - static std::vector> LoadBindingConstraint(EnvForLoading env); - - [[nodiscard]] std::vector> activeContraints() const; - - [[nodiscard]] std::vector getIndicesForInequalityBindingConstraints() const; - - -private: - bool internalSaveToFolder(Data::BindingConstraintSaver::EnvForSaving& env) const; - - //! All constraints - Data::BindingConstraintsRepository::Vector constraints_; - - mutable std::optional>> activeConstraints_; -}; - -struct WhoseNameContains final -{ -public: - explicit WhoseNameContains(AnyString filter) : pFilter(std::move(filter)) - { - } - bool operator()(const std::shared_ptr& s) const - { - return (s->name()).contains(pFilter); - } - -private: - AnyString pFilter; -}; -} -#include "BindingConstraintsRepository.hxx" \ No newline at end of file diff --git a/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.hxx b/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.hxx deleted file mode 100644 index e548f5fa7e..0000000000 --- a/src/libs/antares/study/binding_constraint/BindingConstraintsRepository.hxx +++ /dev/null @@ -1,33 +0,0 @@ -// -// Created by marechaljas on 11/05/23. -// - -#pragma once - -#include -#include - -namespace Antares::Data { - -inline uint BindingConstraintsRepository::size() const { - return (uint) constraints_.size(); -} - -inline bool BindingConstraintsRepository::empty() const { - return constraints_.empty(); -} - -template -inline void BindingConstraintsRepository::each(const PredicateT &predicate) { - uint count = (uint) constraints_.size(); - for (uint i = 0; i != count; ++i) - predicate(*(constraints_[i])); -} - -template -inline void BindingConstraintsRepository::each(const PredicateT &predicate) const { - uint count = (uint) constraints_.size(); - for (uint i = 0; i != count; ++i) - predicate(*(constraints_[i].get())); -} -} diff --git a/src/libs/antares/study/binding_constraint/EnvForLoading.h b/src/libs/antares/study/binding_constraint/EnvForLoading.h deleted file mode 100644 index 5d3409ae2b..0000000000 --- a/src/libs/antares/study/binding_constraint/EnvForLoading.h +++ /dev/null @@ -1,35 +0,0 @@ -// -// Created by marechaljas on 11/05/23. -// - -#pragma once - -#include "yuni/core/fwd.h" -#include -#include - -namespace Antares::Data { - -class AreaList; -class EnvForLoading final -{ -public: - explicit EnvForLoading(AreaList& l, unsigned v) : areaList(l), version(v) - { - } - //! INI file - Yuni::Clob iniFilename; - //! Current section - IniFile::Section* section; - - Yuni::Clob buffer; - Matrix<>::BufferType matrixBuffer; - Yuni::Clob folder; - - //! List of areas - AreaList& areaList; - - unsigned version; -}; - -} // Data diff --git a/src/libs/antares/study/cleaner.h b/src/libs/antares/study/cleaner.h deleted file mode 100644 index 4756ee8ef0..0000000000 --- a/src/libs/antares/study/cleaner.h +++ /dev/null @@ -1,106 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_CLEANER_H__ -#define __ANTARES_LIBS_STUDY_CLEANER_H__ - -#include -#include -#include -#include "version.h" -#include - -namespace Antares::Data -{ -class StudyCleaningInfos final -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - StudyCleaningInfos(); - /*! - ** \brief Constructor with a given path - */ - explicit StudyCleaningInfos(const AnyString& path); - /*! - ** \brief Destructor - */ - ~StudyCleaningInfos(); - //@} - - /*! - ** \brief Determine the complete list of all files/folder considered as intruders - */ - bool analyze(); - - /*! - ** \brief Perform a complete cleanup - */ - void performCleanup(); - - /*! - ** \brief Get the total size occupied by the intruders - */ - uint64_t totalSize() const; - - /*! - ** \brief Set an additional list of excluded files or directories. - */ - void setCustomExcludeList(const Yuni::String& c); - -public: - /*! A study folder */ - Yuni::String folder; - - /*! Version of the study */ - Version version; - /*! List of all intruders */ - ::PathList intruders; - /*! List of all files/folders to prevent from the destruction */ - ::PathList exclude; - /*! Colon-separated list of all files/folders to prevent from the destruction */ - Yuni::String customExclude; - - /*! List of all files/folders to exclude after analyzing the content of the folder */ - /* This list mainly ensures that a list of folders will not deleted enven if empty */ - ::PathList postExclude; - - /*! - ** \brief Event triggered when entering into a new folder - ** - ** Return false to stop the process - */ - Yuni::Bind onProgress; - -}; // class StudyCleaningInfos - -} // namespace Antares::Data - - -#endif /* __ANTARES_LIBS_STUDY_CLEANER_H__ */ diff --git a/src/libs/antares/study/cleaner/cleaner-v20.cpp b/src/libs/antares/study/cleaner/cleaner-v20.cpp index a0f4dea784..f2fa71b17d 100644 --- a/src/libs/antares/study/cleaner/cleaner-v20.cpp +++ b/src/libs/antares/study/cleaner/cleaner-v20.cpp @@ -1,49 +1,44 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "../study.h" -#include "../cleaner.h" + #include +#include "antares/study/cleaner.h" +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data { namespace // anonymous { template -static void listOfFilesAnDirectoriesToKeepForArea(PathList& e, PathList& p, const Area* area, - StringT& buffer) +static void listOfFilesAnDirectoriesToKeepForArea(PathList& e, + PathList& p, + const Area* area, + StringT& buffer) { // ID of the current area const AreaName& id = area->id; @@ -87,7 +82,9 @@ static void listOfFilesAnDirectoriesToKeepForArea(PathList& e, PathList& p, cons e.add(buffer); buffer.clear() << "input/hydro/common/capacity/inflowPattern_" << id << ".txt"; e.add(buffer); - buffer.clear() << "input/hydro/common/capacity/maxpower_" << id << ".txt"; + buffer.clear() << "input/hydro/common/capacity/maxDailyGenEnergy_" << id << ".txt"; + e.add(buffer); + buffer.clear() << "input/hydro/common/capacity/maxDailyPumpEnergy_" << id << ".txt"; e.add(buffer); buffer.clear() << "input/hydro/common/capacity/reservoir_" << id << ".txt"; e.add(buffer); @@ -98,7 +95,11 @@ static void listOfFilesAnDirectoriesToKeepForArea(PathList& e, PathList& p, cons buffer.clear() << "input/hydro/series/" << id << "/mod.txt"; e.add(buffer); buffer.clear() << "input/hydro/series/" << id << "/mingen.txt"; - e.add(buffer); + e.add(buffer); + buffer.clear() << "input/hydro/series/" << id << "/maxHourlyGenPower.txt"; + e.add(buffer); + buffer.clear() << "input/hydro/series/" << id << "/maxHourlyPumpPower.txt"; + e.add(buffer); buffer.clear() << "input/hydro/allocation/" << id << ".ini"; p.add(buffer); buffer.clear() << "input/hydro/prepro/" << id; @@ -135,23 +136,20 @@ static void listOfFilesAnDirectoriesToKeepForArea(PathList& e, PathList& p, cons buffer.clear() << "input/thermal/clusters/" << id << "/list.ini"; e.add(buffer); - auto end = area->thermal.list.end(); - for (auto i = area->thermal.list.begin(); i != end; ++i) + for (auto& cluster: area->thermal.list.all()) { - // Reference to the thermal cluster - auto& cluster = *(i->second); - - buffer.clear() << "input/thermal/prepro/" << id << '/' << cluster.id(); + buffer.clear() << "input/thermal/prepro/" << id << '/' << cluster->id(); p.add(buffer); - buffer.clear() << "input/thermal/series/" << id << '/' << cluster.id(); + buffer.clear() << "input/thermal/series/" << id << '/' << cluster->id(); p.add(buffer); - buffer.clear() << "input/thermal/series/" << id << '/' << cluster.id() << "/series.txt"; + buffer.clear() << "input/thermal/series/" << id << '/' << cluster->id() + << "/series.txt"; e.add(buffer); - buffer.clear() << "input/thermal/prepro/" << id << '/' << cluster.id() << "/data.txt"; + buffer.clear() << "input/thermal/prepro/" << id << '/' << cluster->id() << "/data.txt"; e.add(buffer); - buffer.clear() << "input/thermal/prepro/" << id << '/' << cluster.id() + buffer.clear() << "input/thermal/prepro/" << id << '/' << cluster->id() << "/modulation.txt"; e.add(buffer); } @@ -168,16 +166,12 @@ static void listOfFilesAnDirectoriesToKeepForArea(PathList& e, PathList& p, cons buffer.clear() << "input/renewables/clusters/" << id << "/list.ini"; e.add(buffer); - auto end = area->renewable.list.end(); - for (auto i = area->renewable.list.begin(); i != end; ++i) + for (const auto& cluster: area->renewable.list.all()) { - // Reference to the thermal cluster - auto& cluster = *(i->second); - - buffer.clear() << "input/renewables/series/" << id << '/' << cluster.id(); + buffer.clear() << "input/renewables/series/" << id << '/' << cluster->id(); p.add(buffer); - buffer.clear() << "input/renewables/series/" << id << '/' << cluster.id() + buffer.clear() << "input/renewables/series/" << id << '/' << cluster->id() << "/series.txt"; e.add(buffer); } @@ -219,19 +213,16 @@ void listOfFilesAnDirectoriesToKeepForLinks(PathList& p, const Area* area, Strin auto& link = *(i->second); // Parameters buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << link.with->id - << "_parameters" - << ".txt"; + << "_parameters" << ".txt"; p.add(buffer); // Indirect capacities buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << "capacities" - << SEP << link.with->id << "_direct" - << ".txt"; + << SEP << link.with->id << "_direct" << ".txt"; p.add(buffer); // Direct capacities buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << "capacities" - << SEP << link.with->id << "_indirect" - << ".txt"; + << SEP << link.with->id << "_indirect" << ".txt"; p.add(buffer); } } @@ -271,10 +262,12 @@ bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos) e.add("input/thermal/areas.ini"); // Also exclude custom files/folders provided by the user - infos->customExclude.words(":", [&e](const AnyString& word) { - e.add(word); - return true; - }); + infos->customExclude.words(":", + [&e](const AnyString& word) + { + e.add(word); + return true; + }); // Post p.add("logs"); @@ -361,7 +354,7 @@ bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos) // Exclude listOfFilesAnDirectoriesToKeepForArea(e, p, area, buffer); // Clear the memory used by the thermal clusters of the area - area->thermal.list.clear(); + area->thermal.list.clearAll(); // Interconnections { @@ -369,7 +362,7 @@ bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos) logs.verbosityLevel = Logs::Verbosity::Warning::level; // load all links buffer.clear() << infos->folder << "/input/links/" << area->id; - if (not AreaLinksLoadFromFolder(*study, arealist, area, buffer)) + if (not AreaLinksLoadFromFolder(*study, arealist, area, buffer.c_str())) { delete arealist; delete study; @@ -398,23 +391,24 @@ bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos) buffer.clear() << infos->folder << "/input/bindingconstraints/bindingconstraints.ini"; if (ini.open(buffer)) { - String v; - - ini.each([&](const IniFile::Section& section) { - auto* property = section.firstProperty; - for (; property; property = property->next) - { - if (property->key == "id") - { - v = property->value; - v.toLower(); - buffer.clear() << "input/bindingconstraints/" << v << ".txt"; - e.add(buffer); - // Go to the next binding constraint - break; - } - } - }); + ini.each( + [&e](const IniFile::Section& section) + { + auto* property = section.firstProperty; + for (; property; property = property->next) + { + if (property->key == "id") + { + String v = property->value; + v.toLower(); + String tmp; + tmp << "input/bindingconstraints/" << v << ".txt"; + e.add(tmp); + // Go to the next binding constraint + break; + } + } + }); } else { @@ -426,5 +420,4 @@ bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos) return true; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/cleaner/cleaner.cpp b/src/libs/antares/study/cleaner/cleaner.cpp index 191f4814c7..88e4acbe05 100644 --- a/src/libs/antares/study/cleaner/cleaner.cpp +++ b/src/libs/antares/study/cleaner/cleaner.cpp @@ -1,35 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/cleaner.h" + #include #include -#include "../cleaner.h" -#include "versions.h" + #include +#include +#include "antares/study/cleaner/versions.h" +#include "antares/study/version.h" using namespace Yuni; @@ -39,12 +37,11 @@ namespace Antares::Data { StudyCleaningInfos::StudyCleaningInfos() { - version = versionUnknown; } -StudyCleaningInfos::StudyCleaningInfos(const AnyString& path) : folder(path) +StudyCleaningInfos::StudyCleaningInfos(const AnyString& path): + folder(path) { - version = versionUnknown; } StudyCleaningInfos::~StudyCleaningInfos() = default; @@ -58,34 +55,23 @@ bool StudyCleaningInfos::analyze() intruders.clear(); postExclude.clear(); // Getting the version - version = StudyTryToFindTheVersion(folder); + version = StudyHeader::tryToFindTheVersion(folder); - switch (version) - { - case versionFutur: + if (version > StudyVersion::latest()) { logs.error() << "A more recent version of Antares is required for " << folder; - break; + return false; } - case versionUnknown: + if (version == StudyVersion::unknown()) { logs.error() << "Unknown study version: " << folder; - break; + return false; } - default: + + if (not listOfFilesAnDirectoriesToKeep(this)) { - if ((int)version <= (int)versionLatest) - { - if (not listOfFilesAnDirectoriesToKeep(this)) - { - logs.error() << "Aborting: an error has been encountered: " << folder; - return false; - } - } - else - logs.error() << "Invalid study version: " << folder; - break; - } + logs.error() << "Aborting: an error has been encountered: " << folder; + return false; } // Grab all intruders at once @@ -98,9 +84,13 @@ bool StudyCleaningInfos::analyze() if (not intruders.empty()) { if (intruders.size() == 1) + { logs.info() << " :: 1 file/folder will be removed"; + } else + { logs.info() << " :: " << intruders.size() << " files/folders will be removed"; + } return true; } else @@ -113,7 +103,7 @@ bool StudyCleaningInfos::analyze() void StudyCleaningInfos::performCleanup() { - if (version != versionUnknown && not intruders.empty()) + if (version != StudyVersion::unknown() && not intruders.empty()) { // Remove all files first intruders.deleteAllFiles(folder); @@ -132,4 +122,3 @@ void StudyCleaningInfos::setCustomExcludeList(const Yuni::String& c) customExclude = c; } } // namespace Antares::Data - diff --git a/src/libs/antares/study/cleaner/versions.h b/src/libs/antares/study/cleaner/versions.h deleted file mode 100644 index b273f2b640..0000000000 --- a/src/libs/antares/study/cleaner/versions.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_CLEANER_VERSION_H__ -#define __ANTARES_LIBS_STUDY_CLEANER_VERSION_H__ - -namespace Antares -{ -namespace Data -{ -bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos); - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_CLEANER_VERSION_H__ diff --git a/src/libs/antares/study/constraint.h b/src/libs/antares/study/constraint.h deleted file mode 100644 index 177d96e4e2..0000000000 --- a/src/libs/antares/study/constraint.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_CONSTRAINT_H__ -#define __ANTARES_LIBS_STUDY_CONSTRAINT_H__ - -#include "binding_constraint/BindingConstraint.h" - -#endif // __ANTARES_LIBS_STUDY_CONSTRAINT_H__ diff --git a/src/libs/antares/study/correlation-updater.hxx b/src/libs/antares/study/correlation-updater.hxx deleted file mode 100644 index 01151f1437..0000000000 --- a/src/libs/antares/study/correlation-updater.hxx +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_CORRELATION_UPDATER_HXX__ -#define __ANTARES_LIBS_STUDY_CORRELATION_UPDATER_HXX__ - -#include - -#define SEP IO::Separator - -namespace Antares -{ -namespace // anonymous -{ -class CorrelationUpdater final -{ -public: - CorrelationUpdater(Data::Study& study) : pStudy(study) - { - using namespace Yuni; - // We can store the INI files in disk because it may not fit in memory - pTempFile << memory.cacheFolder() << SEP << "antares-corr-save-" << memory.processID() - << '-' << (void*)(this) << '-'; - - pS.clear() << pTempFile << "load.tmp"; - study.preproLoadCorrelation.saveToFile(study, pS); - pS.clear() << pTempFile << "solar.tmp"; - study.preproSolarCorrelation.saveToFile(study, pS); - pS.clear() << pTempFile << "wind.tmp"; - study.preproWindCorrelation.saveToFile(study, pS); - pS.clear() << pTempFile << "hydro.tmp"; - study.preproHydroCorrelation.saveToFile(study, pS); - } - - ~CorrelationUpdater() - { - using namespace Yuni; - pS.clear() << pTempFile << "load.tmp"; - pStudy.preproLoadCorrelation.loadFromFile(pStudy, pS, false); - IO::File::Delete(pS); - - pS.clear() << pTempFile << "solar.tmp"; - pStudy.preproSolarCorrelation.loadFromFile(pStudy, pS, false); - IO::File::Delete(pS); - - pS.clear() << pTempFile << "wind.tmp"; - pStudy.preproWindCorrelation.loadFromFile(pStudy, pS, false); - IO::File::Delete(pS); - - pS.clear() << pTempFile << "hydro.tmp"; - pStudy.preproHydroCorrelation.loadFromFile(pStudy, pS, false); - IO::File::Delete(pS); - } - -private: - Data::Study& pStudy; - Yuni::Clob pTempFile; - Yuni::Clob pS; - -}; // class CorrelationUpdater - -} // anonymous namespace - -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_CORRELATION_UPDATER_HXX__ diff --git a/src/libs/antares/study/filter.cpp b/src/libs/antares/study/filter.cpp index 192f3fd97e..cb94bf5d30 100644 --- a/src/libs/antares/study/filter.cpp +++ b/src/libs/antares/study/filter.cpp @@ -1,69 +1,71 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "filter.h" +#include "antares/study/filter.h" using namespace Yuni; -namespace Antares -{ -namespace Data +namespace Antares::Data { std::string datePrecisionIntoString(uint datePrecisionFilter) { std::string to_return; if (datePrecisionFilter & filterHourly) + { to_return += "hourly"; + } if (datePrecisionFilter & filterDaily) { if (!to_return.empty()) + { to_return += ", "; + } to_return += "daily"; } if (datePrecisionFilter & filterWeekly) { if (!to_return.empty()) + { to_return += ", "; + } to_return += "weekly"; } if (datePrecisionFilter & filterMonthly) { if (!to_return.empty()) + { to_return += ", "; + } to_return += "monthly"; } if (datePrecisionFilter & filterAnnual) { if (!to_return.empty()) + { to_return += ", "; + } to_return += "annual"; } @@ -73,40 +75,44 @@ std::string datePrecisionIntoString(uint datePrecisionFilter) uint stringIntoDatePrecision(const AnyString& string) { if (string.empty()) + { return filterNone; + } uint flag = 0; - string.words(",; \r\n\t", [&](const AnyString& word) -> bool { - ShortString16 s = word; - s.toLower(); - if (s == "hourly") - { - flag |= filterHourly; - return true; - } - if (s == "daily") - { - flag |= filterDaily; - return true; - } - if (s == "weekly") - { - flag |= filterWeekly; - return true; - } - if (s == "monthly") - { - flag |= filterMonthly; - return true; - } - if (s == "annual") - { - flag |= filterAnnual; - return true; - } - return true; - }); + string.words(",; \r\n\t", + [&flag](const AnyString& word) -> bool + { + ShortString16 s = word; + s.toLower(); + if (s == "hourly") + { + flag |= filterHourly; + return true; + } + if (s == "daily") + { + flag |= filterDaily; + return true; + } + if (s == "weekly") + { + flag |= filterWeekly; + return true; + } + if (s == "monthly") + { + flag |= filterMonthly; + return true; + } + if (s == "annual") + { + flag |= filterAnnual; + return true; + } + return true; + }); return flag; } @@ -132,5 +138,4 @@ uint addTimeIntervallToDatePrecisionFilter(const uint index) return flag; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/filter.h b/src/libs/antares/study/filter.h deleted file mode 100644 index ad9d8fdb3e..0000000000 --- a/src/libs/antares/study/filter.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_STUDY_FILTER_H__ -#define __ANTARES_LIB_STUDY_FILTER_H__ - -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -enum FilterFlag -{ - filterNone = 0, - filterHourly = 1, - filterDaily = 2, - filterWeekly = 4, - filterMonthly = 8, - filterAnnual = 16, - filterAll = (uint)-1, -}; - -// Convert a date precision filter into a string (obtained by concatenating filter components) -std::string datePrecisionIntoString(uint datePrecisionFilter); - -/*! -** \brief Convert a string into date precision filter flags -*/ -uint stringIntoDatePrecision(const AnyString& string); - -/*! -** \brief Convert a filter indices into filter flags -*/ -uint addTimeIntervallToDatePrecisionFilter(const uint index); - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIB_STUDY_FILTER_H__ diff --git a/src/libs/antares/study/finder.h b/src/libs/antares/study/finder.h deleted file mode 100644 index 0769819a4d..0000000000 --- a/src/libs/antares/study/finder.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_FINDER_H__ -#define __ANTARES_LIB_FINDER_H__ - -#include "finder/finder.h" - -#endif // __ANTARES_LIB_FINDER_H__ diff --git a/src/libs/antares/study/finder/finder.cpp b/src/libs/antares/study/finder/finder.cpp index fddd00e968..f4fe0e7419 100644 --- a/src/libs/antares/study/finder/finder.cpp +++ b/src/libs/antares/study/finder/finder.cpp @@ -1,54 +1,50 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/finder/finder.h" + #include #include #include -#include "../study.h" -#include "finder.h" + +#include "antares/study/study.h" using namespace Yuni; -namespace Antares -{ -namespace Data +namespace Antares::Data { namespace // anonymous namespace { -class MyIterator final : public IO::Directory::IIterator +class MyIterator final: public IO::Directory::IIterator { public: using IteratorType = IO::Directory::IIterator; using Flow = IO::Flow; public: - MyIterator(StudyFinder& finder) : pFinder(finder) + MyIterator(StudyFinder& finder): + pFinder(finder) { } + virtual ~MyIterator() { // For code robustness and to avoid corrupt vtable @@ -63,20 +59,18 @@ class MyIterator final : public IO::Directory::IIterator virtual Flow onBeginFolder(const String& filename, const String&, const String&) { - const Version versionFound = StudyTryToFindTheVersion(filename); - switch (versionFound) - { - case versionFutur: - return IO::flowSkip; - case versionUnknown: - return IO::flowContinue; - default: + const StudyVersion versionFound = StudyHeader::tryToFindTheVersion(filename); + if (versionFound > StudyVersion::latest()) { - // We have found a study ! - pFinder.onStudyFound(filename, versionFound); return IO::flowSkip; } + if (versionFound == StudyVersion::unknown()) + { + return IO::flowContinue; } + + // We have found a study ! + pFinder.onStudyFound(filename, versionFound); return IO::flowSkip; } @@ -96,11 +90,13 @@ class MyIterator final : public IO::Directory::IIterator } // anonymous namespace -StudyFinder::StudyFinder() : pLycos(nullptr) +StudyFinder::StudyFinder(): + pLycos(nullptr) { } -StudyFinder::StudyFinder(const StudyFinder&) : ThreadingPolicy(), pLycos(nullptr) +StudyFinder::StudyFinder(const StudyFinder&): + pLycos(nullptr) { } @@ -115,68 +111,89 @@ StudyFinder::~StudyFinder() void StudyFinder::stop(uint timeout) { - ThreadingPolicy::MutexLocker locker(*this); + std::lock_guard locker(mutex); if (pLycos) + { pLycos->stop(timeout); + } } void StudyFinder::wait() { - ThreadingPolicy::MutexLocker locker(*this); + std::lock_guard locker(mutex); if (pLycos) + { pLycos->wait(); + } } void StudyFinder::wait(uint timeout) { - ThreadingPolicy::MutexLocker locker(*this); + std::lock_guard locker(mutex); if (pLycos) + { pLycos->wait(timeout); + } } void StudyFinder::lookup(const Yuni::String::Vector& folder) { - ThreadingPolicy::MutexLocker locker(*this); + std::lock_guard locker(mutex); if (pLycos) + { pLycos->stop(10000); + } else + { pLycos = new MyIterator(*this); + } pLycos->clear(); const Yuni::String::Vector::const_iterator end = folder.end(); for (Yuni::String::Vector::const_iterator i = folder.begin(); i != end; ++i) + { pLycos->add(*i); + } pLycos->start(); } void StudyFinder::lookup(const Yuni::String::List& folder) { - ThreadingPolicy::MutexLocker locker(*this); + std::lock_guard locker(mutex); if (pLycos) + { pLycos->stop(10000); + } else + { pLycos = new MyIterator(*this); + } pLycos->clear(); const Yuni::String::List::const_iterator end = folder.end(); for (Yuni::String::List::const_iterator i = folder.begin(); i != end; ++i) + { pLycos->add(*i); + } pLycos->start(); } void StudyFinder::lookup(const String& folder) { - ThreadingPolicy::MutexLocker locker(*this); + std::lock_guard locker(mutex); if (pLycos) + { pLycos->stop(10000); + } else + { pLycos = new MyIterator(*this); + } pLycos->clear(); pLycos->add(folder); pLycos->start(); } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/finder/finder.h b/src/libs/antares/study/finder/finder.h deleted file mode 100644 index 26ea3cdcc6..0000000000 --- a/src/libs/antares/study/finder/finder.h +++ /dev/null @@ -1,141 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_FINDER_FINDER_H__ -#define __ANTARES_LIB_FINDER_FINDER_H__ - -#include -#include -#include "../study.h" -#include - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Look for study folders asynchronously -*/ -class StudyFinder : public Yuni::Policy::ObjectLevelLockable -{ -public: - //! The threading policy - using ThreadingPolicy = Yuni::Policy::ObjectLevelLockable; - enum - { - //! The default value for the timeout - defaultTimeout = 10000, // 10s - }; - - //! List of folders - using FolderVector = std::vector; - -public: - //! \name Constructor - //@{ - /*! - ** \brief Default Constructor - */ - StudyFinder(); - //! Copy constructor - StudyFinder(const StudyFinder&); - /*! - ** \brief Destructor - */ - virtual ~StudyFinder(); - //@} - - /*! - ** \brief Start a new lookup from a single folder - ** - ** If a lookup was already in progress, it will be stopped before. - ** \param folder The root folder where to start the lookup - */ - void lookup(const Yuni::String& folder); - - /*! - ** \brief Start a new lookup from a list of folder - ** - ** If a lookup was already in progress, it will be stopped before. - ** \param folders The list of folders where to start the lookup - */ - void lookup(const Yuni::String::Vector& folders); - /*! - ** \brief Start a new lookup from a list of folder - ** - ** If a lookup was already in progress, it will be stopped before. - ** \param folders The list of folders where to start the lookup - */ - void lookup(const Yuni::String::List& folders); - - /*! - ** \brief Stop a lookup currently in progress - */ - void stop(uint timeout = defaultTimeout); - - /*! - ** \brief Wait Indefinitely for the end of the lookup - */ - void wait(); - - /*! - ** \brief Wait for the end of the lookup (with timeout) - */ - void wait(uint timeout); - -public: // Events - /*! - ** \brief Event triggered when a lookup has been found - */ - virtual void onStudyFound(const Yuni::String& folder, Version version) = 0; - - /*! - ** \brief Event triggered when a lookup has finished gracefully - ** - ** This event might be called from any thread. - */ - virtual void onLookupFinished() - { - } - - /*! - ** \brief Event triggered when a lookup has been aborted - ** - ** This event might be called from any thread. - */ - virtual void onLookupAborted() - { - } - -private: - Yuni::IO::Directory::IIterator* pLycos; - -}; // class StudyFinder - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIB_FINDER_FINDER_H__ diff --git a/src/libs/antares/study/fwd.cpp b/src/libs/antares/study/fwd.cpp index 5988b26e7e..100a4b127e 100644 --- a/src/libs/antares/study/fwd.cpp +++ b/src/libs/antares/study/fwd.cpp @@ -1,38 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "fwd.h" +#include "antares/study/fwd.h" + #include using namespace Yuni; -namespace Antares -{ -namespace Data +namespace Antares::Data { const char* SeedToCString(SeedIndex seed) { @@ -98,50 +91,25 @@ const char* SeedToID(SeedIndex seed) return ""; } -// ... Initial reservoir levels ... -InitialReservoirLevels StringToInitialReservoirLevels(const AnyString& text) -{ - if (!text) - return irlUnknown; - - CString<24, false> s = text; - s.trim(); - s.toLower(); - if (s == "cold start") - return irlColdStart; - if (s == "hot start") - return irlHotStart; - - return irlUnknown; -} - -const char* InitialReservoirLevelsToCString(InitialReservoirLevels iniLevels) -{ - switch (iniLevels) - { - case irlColdStart: - return "cold start"; - case irlHotStart: - return "hot start"; - case irlUnknown: - return ""; - } - return ""; -} - // ... Hydro heuristic policy ... HydroHeuristicPolicy StringToHydroHeuristicPolicy(const AnyString& text) { if (!text) + { return hhpUnknown; + } CString<24, false> s = text; s.trim(); s.toLower(); if (s == "accommodate rule curves") + { return hhpAccommodateRuleCurves; + } if (s == "maximize generation") + { return hhpMaximizeGeneration; + } return hhpUnknown; } @@ -164,15 +132,21 @@ const char* HydroHeuristicPolicyToCString(HydroHeuristicPolicy hhPolicy) HydroPricingMode StringToHydroPricingMode(const AnyString& text) { if (!text) + { return hpUnknown; + } CString<24, false> s = text; s.trim(); s.toLower(); if (s == "fast") + { return hpHeuristic; + } if (s == "accurate") // mixed integer linear problem + { return hpMILP; + } return hpUnknown; } @@ -194,17 +168,25 @@ const char* HydroPricingModeToCString(HydroPricingMode hpm) PowerFluctuations StringToPowerFluctuations(const AnyString& text) { if (!text) + { return lssUnknown; + } CString<24, false> s = text; s.trim(); s.toLower(); if (s == "minimize ramping") + { return lssMinimizeRamping; + } if (s == "free modulations") + { return lssFreeModulations; + } if (s == "minimize excursions") + { return lssMinimizeExcursions; + } return lssUnknown; } @@ -228,15 +210,21 @@ const char* PowerFluctuationsToCString(PowerFluctuations fluctuations) SheddingPolicy StringToSheddingPolicy(const AnyString& text) { if (!text) + { return shpUnknown; + } CString<24, false> s = text; s.trim(); s.toLower(); if (s == "shave peaks") + { return shpShavePeaks; + } if (s == "minimize duration") + { return shpMinimizeDuration; + } return shpUnknown; } @@ -258,15 +246,25 @@ const char* SheddingPolicyToCString(SheddingPolicy strategy) UnitCommitmentMode StringToUnitCommitmentMode(const AnyString& text) { if (!text) + { return ucUnknown; + } CString<24, false> s = text; s.trim(); s.toLower(); if (s == "fast") - return ucHeuristic; - if (s == "accurate") // mixed integer linear problem + { + return ucHeuristicFast; + } + if (s == "accurate") + { + return ucHeuristicAccurate; + } + if (s == "milp") // mixed integer linear problem + { return ucMILP; + } return ucUnknown; } @@ -275,10 +273,12 @@ const char* UnitCommitmentModeToCString(UnitCommitmentMode ucommitment) { switch (ucommitment) { - case ucHeuristic: + case ucHeuristicFast: return "fast"; - case ucMILP: + case ucHeuristicAccurate: return "accurate"; // (slow) + case ucMILP: + return "milp"; // (possibly very slow) case ucUnknown: return ""; } @@ -288,21 +288,33 @@ const char* UnitCommitmentModeToCString(UnitCommitmentMode ucommitment) NumberOfCoresMode StringToNumberOfCoresMode(const AnyString& text) { if (!text) + { return ncUnknown; + } CString<24, false> s = text; s.trim(); s.toLower(); if (s == "minimum") + { return ncMin; + } if (s == "low") + { return ncLow; + } if (s == "medium") + { return ncAvg; + } if (s == "high") + { return ncHigh; + } if (s == "maximum") + { return ncMax; + } return ncUnknown; } @@ -370,13 +382,21 @@ mpsExportStatus stringToMPSexportStatus(const AnyString& value) v.toLower(); if (v == "both-optims" || v == "true") // Case "true" : for compatibily with older study versions + { return mpsExportStatus::EXPORT_BOTH_OPTIMS; + } if (v == "none" || v == "false") // Case "false" : for compatibily with older study versions + { return mpsExportStatus::NO_EXPORT; + } if (v == "optim-1") + { return mpsExportStatus::EXPORT_FIRST_OPTIM; + } if (v == "optim-2") + { return mpsExportStatus::EXPORT_SECOND_OPTIM; + } return mpsExportStatus::UNKNOWN_EXPORT; } @@ -489,5 +509,4 @@ std::string styleToString(const StyleType& style) } } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h deleted file mode 100644 index 6db7c2ee57..0000000000 --- a/src/libs/antares/study/fwd.h +++ /dev/null @@ -1,555 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_FWD_H__ -#define __ANTARES_LIBS_STUDY_FWD_H__ - -#include -#include -#include "../constants.h" -#include - -namespace Antares -{ -class IniFile; - -namespace Data -{ -// Forward declarations -class Study; -class StudyLoadOptions; -class Area; -class AreaLink; -class AreaList; -class AreaUI; -class ThermalCluster; -class RenewableCluster; - -class AreaScratchpad; - -class Parameters; - -class BindingConstraint; -class BindingConstraintsRepository; - -class StudyRuntimeInfos; - -class UIRuntimeInfo; - -class Correlation; - -//! Name of a single area -using AreaName = Yuni::CString; -//! Name of a single link -using AreaLinkName = Yuni::CString; -//! Name of a single thermal -using ClusterName = std::string; - -using ConstraintName = Yuni::CString; - -using RulesScenarioName = Yuni::CString<64, false>; - -//! Name mapping -using AreaNameMapping = std::map; - -/*! -** \brief Study's Consistency errors -*/ -enum StudyError -{ - stErrNone = 0, - //! startTime, finalHour = 0..8760 - stErrHourOutOfBounds = 1, - //! The final hour must be a multiple of 168 - stErrFinalHourMustBeAMultipleOf168, - //! A given day of the week is invalid - stErrInvalidDayOfWeek, - //! Too much areas (>300) - stErrTooMuchAreas, - //! Too much interconnections (>5000) - stErrTooMuchInterconnections, - //! Too much binding constaints - stErrTooMuchBindingConstraints, - /**/ -}; - -/*! -** \brief Types of Study -*/ -enum StudyMode -{ - stdmUnknown = -1, - //! Economic - stdmEconomy, - //! Adequacy (subset of the economy mode) - stdmAdequacy, - //! Expansion - stdmExpansion, - //! Max - stdmMax - -}; // enum StudyMode - -/* -** \brief Simplex optimizations -*/ -enum SimplexOptimization -{ - sorUnknown = 0, - sorDay, - sorWeek, - -}; // enum SimplexOptimization - -/*! -** \brief Transmission capacities mode (applies to all links) -*/ -enum class GlobalTransmissionCapacities -{ - //! Transmission capacities are enabled - localValuesForAllLinks = 0, - //! Transmission capacities are ignored (set to null) - nullForAllLinks, - //! Transmission capacities are infinite (aka Copper Plate) - infiniteForAllLinks, - //! Transmission capacities are ignored only for physical links - //! Global property only, cannot be used for individual links - nullForPhysicalLinks, - //! Transmission capacities are infinite only for physical links (not virtual) - //! Global property only, cannot be used for individual links - infiniteForPhysicalLinks -}; // enum TransmissionCapacities - -std::string GlobalTransmissionCapacitiesToString( - GlobalTransmissionCapacities transmissionCapacities); -std::string GlobalTransmissionCapacitiesToString_Display( - GlobalTransmissionCapacities transmissionCapacities); -bool stringToGlobalTransmissionCapacities(const AnyString& value, - GlobalTransmissionCapacities& out); - -/*! -** \brief Transmission capacities mode (applies to individual links) -*/ -enum class LocalTransmissionCapacities -{ - enabled, - null, - infinite -}; - -std::string transmissionCapacitiesToString(const LocalTransmissionCapacities& tc); - -/*! -** \brief Asset Type mode -*/ -enum AssetType -{ - //! Asset Type AC - atAC = 0, - //! Asset Type DC - atDC, - //! Asset Type gas - atGas, - //! Asset Type virtual - atVirt, - //! Asset Type Other (gas, etc) - atOther, - -}; // enum AssetType - -std::string assetTypeToString(const AssetType& assetType); - -/*! -** \brief Style Type mode -*/ -enum StyleType -{ - //! Style Type plain - stPlain = 0, - //! Style Type dot - stDot, - //! Style Type dash - stDash, - //! Style Type dot & dash - stDotDash, - -}; // enum StyleType - -std::string styleToString(const StyleType& style); - -/*! -** \brief Types of timeSeries -** -** These values are mainly used for mask bits -*/ -enum TimeSeriesType : unsigned int -{ - //! TimeSeries : Load - timeSeriesLoad = 1, - //! TimeSeries : Hydro - timeSeriesHydro = 2, - //! TimeSeries : Wind - timeSeriesWind = 4, - //! TimeSeries : Thermal - timeSeriesThermal = 8, - //! TimeSeries : Solar - timeSeriesSolar = 16, - //! TimeSeries : Renewable - timeSeriesRenewable = 32, - //! TimeSeries : Renewable - timeSeriesTransmissionCapacities = 64, - - //! The maximum number of time-series that we can encounter - timeSeriesCount = 7, - -}; // enum TimeSeries - -template -struct TimeSeriesBitPatternIntoIndex; - -template<> -struct TimeSeriesBitPatternIntoIndex<1> -{ - enum - { - value = 0 - }; -}; -template<> -struct TimeSeriesBitPatternIntoIndex<2> -{ - enum - { - value = 1 - }; -}; -template<> -struct TimeSeriesBitPatternIntoIndex<4> -{ - enum - { - value = 2 - }; -}; -template<> -struct TimeSeriesBitPatternIntoIndex<8> -{ - enum - { - value = 3 - }; -}; -template<> -struct TimeSeriesBitPatternIntoIndex<16> -{ - enum - { - value = 4 - }; -}; -template<> -struct TimeSeriesBitPatternIntoIndex<32> -{ - enum - { - value = 5 - }; -}; - -template -struct TimeSeriesToCStr; -template<> -struct TimeSeriesToCStr<1> -{ - static const char* Value() - { - return "load"; - } -}; -template<> -struct TimeSeriesToCStr<2> -{ - static const char* Value() - { - return "hydro"; - } -}; -template<> -struct TimeSeriesToCStr<4> -{ - static const char* Value() - { - return "wind"; - } -}; -template<> -struct TimeSeriesToCStr<8> -{ - static const char* Value() - { - return "thermal"; - } -}; -template<> -struct TimeSeriesToCStr<16> -{ - static const char* Value() - { - return "solar"; - } -}; -template<> -struct TimeSeriesToCStr<32> -{ - static const char* Value() - { - return "renewable"; - } -}; - -enum SeedIndex -{ - //! The seed for wind - seedTsGenWind = 0, - //! The seed for load - seedTsGenLoad, - //! The seed for hydro - seedTsGenHydro, - //! The seed for thermal - seedTsGenThermal, - //! The seed for solar - seedTsGenSolar, - //! The seed used for time-series numbers - seedTimeseriesNumbers, - //! Seed - unsupplied energy costs - seedUnsuppliedEnergyCosts, - //! Seed - Spilled energy costs - seedSpilledEnergyCosts, - //! Seed - thermal costs - seedThermalCosts, - //! Seed - Hydro costs - seedHydroCosts, - //! Seed - Hydro management - seedHydroManagement, - //! The number of seeds - seedMax, -}; - -enum -{ - //! A default seed for random number generators - antaresSeedDefaultValue = 5489, - //! Increment for RNG (generators) with a different seed - antaresSeedIncrement = 1000000, // arbitrary value -}; - -/*! -** \brief Convert a seed into a string -*/ -const char* SeedToCString(SeedIndex seed); - -/*! -** \brief Seed to CString ID -** -** Mainly used for saving / loading into generaldata.ini -*/ -const char* SeedToID(SeedIndex seed); - -// ... Initial reservoir levels ... -enum InitialReservoirLevels -{ - irlColdStart = 0, - irlHotStart, - irlUnknown, -}; - -/*! -** \brief Convert an Initial Reservoir Levels strategy into a text -*/ -const char* InitialReservoirLevelsToCString(InitialReservoirLevels iniLevels); - -/*! -** \brief Convert a text into an Initial Reservoir Levels strategy -*/ -InitialReservoirLevels StringToInitialReservoirLevels(const AnyString& text); - -// ... Hydro heuristic policy ... -enum HydroHeuristicPolicy -{ - hhpAccommodateRuleCurves = 0, - hhpMaximizeGeneration, - hhpUnknown, -}; - -HydroHeuristicPolicy StringToHydroHeuristicPolicy(const AnyString& text); - -const char* HydroHeuristicPolicyToCString(HydroHeuristicPolicy hhPolicy); - -// ... Hydro Pricing ... -enum HydroPricingMode -{ - hpHeuristic = 0, - hpMILP, // mixed integer linear problem - hpUnknown, -}; - -/*! -** \brief Convert a hyfro pricing mode into a text -*/ -const char* HydroPricingModeToCString(HydroPricingMode hpm); - -/*! -** \brief Convert a text into a hydro pricing mode -*/ -HydroPricingMode StringToHydroPricingMode(const AnyString& text); - -// ... Power fluctuations ... -enum PowerFluctuations -{ - lssFreeModulations = 0, - lssMinimizeRamping, - lssMinimizeExcursions, - lssUnknown, -}; - -/*! -** \brief Convert a local shedding strategy into a text -*/ -const char* PowerFluctuationsToCString(PowerFluctuations fluctuations); - -/*! -** \brief Convert a text into a local shedding strategy -*/ -PowerFluctuations StringToPowerFluctuations(const AnyString& text); - -enum SheddingPolicy -{ - shpShavePeaks = 0, - shpMinimizeDuration, - shpUnknown, -}; - -/*! -** \brief Convert a global shedding policy into a text -*/ -const char* SheddingPolicyToCString(SheddingPolicy strategy); - -/*! -** \brief Convert a text into a global shedding policy -*/ -SheddingPolicy StringToSheddingPolicy(const AnyString& text); - -enum UnitCommitmentMode -{ - ucHeuristic = 0, - ucMILP, // mixed integer linear problem - ucUnknown, -}; - -/*! -** \brief Convert a unit commitment mode into a text -*/ -const char* UnitCommitmentModeToCString(UnitCommitmentMode ucommitment); - -/*! -** \brief Convert a text into a unit commitment mode -*/ -UnitCommitmentMode StringToUnitCommitmentMode(const AnyString& text); - -enum NumberOfCoresMode -{ - ncMin = 0, - ncLow, - ncAvg, - ncHigh, - ncMax, - ncUnknown -}; - -/*! -** \brief Convert a numbers of cores mode into a text -*/ -const char* NumberOfCoresModeToCString(NumberOfCoresMode ncores); - -/*! -** \brief Convert a text into a nb of cores mode -*/ -NumberOfCoresMode StringToNumberOfCoresMode(const AnyString& text); - -/* - * Renewable generation modelling - */ -enum RenewableGenerationModelling -{ - rgAggregated = 0, // Default - rgClusters, // Using renewable clusters - rgUnknown, -}; - -/*! -** \brief Convert a renewable generation modelling into a text -*/ -const char* RenewableGenerationModellingToCString(RenewableGenerationModelling rgModelling); - -/*! -** \brief Convert a text into a renewable generation modelling -*/ -RenewableGenerationModelling StringToRenewableGenerationModelling(const AnyString& text); - -// ------------------------ -// MPS export status -// ------------------------ -enum class mpsExportStatus : int -{ - NO_EXPORT = 0, - EXPORT_FIRST_OPTIM = 1, - EXPORT_SECOND_OPTIM = 2, - EXPORT_BOTH_OPTIMS = 3, - UNKNOWN_EXPORT = 4 -}; - -std::string mpsExportStatusToString(const mpsExportStatus& mps_export_status); -mpsExportStatus stringToMPSexportStatus(const AnyString& value); - -} // namespace Data -} // namespace Antares - -namespace Antares::Data::ScenarioBuilder -{ -class Rules; -class TSNumberRules; -class Sets; - -} // namespace Antares::Data::ScenarioBuilder - - - -namespace Benchmarking -{ -class IDurationCollector; -} - -#endif // __ANTARES_LIBS_STUDY_FWD_H__ diff --git a/src/libs/antares/study/header.cpp b/src/libs/antares/study/header.cpp index b7507751fd..ae44e94ad5 100644 --- a/src/libs/antares/study/header.cpp +++ b/src/libs/antares/study/header.cpp @@ -1,39 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "header.h" +#include "antares/study/header.h" + +#include #include #include -#include + #include -#include "version.h" +#include "antares/study/version.h" using namespace Yuni; +namespace fs = std::filesystem; namespace Antares::Data { @@ -52,7 +49,7 @@ void StudyHeader::reset() // Caption caption = STUDYHEADER_DEFAULT_CAPTION; // Version - version = Data::versionLatest; + version = Data::StudyVersion::latest(); // Date dateCreated = ::time(nullptr); dateLastSave = dateCreated; @@ -68,10 +65,12 @@ void StudyHeader::CopySettingsToIni(IniFile& ini, bool upgradeVersion) // Version // For performance reasons, the version should be in written first to // be able to quickly check the version of the study when calling - // StudyHeader::ReadVersionFromFile(). + // StudyHeader::readVersionFromFile(). if (upgradeVersion) - version = Data::versionLatest; - sect->add("version", (uint)Data::versionLatest); + { + version = Data::StudyVersion::latest(); + } + sect->add("version", Data::StudyVersion::latest().toString()); // Caption sect->add("caption", caption); @@ -86,7 +85,7 @@ void StudyHeader::CopySettingsToIni(IniFile& ini, bool upgradeVersion) sect->add("author", author); } -uint StudyHeader::internalFindVersionFromFile(const IniFile& ini) +bool StudyHeader::internalFindVersionFromFile(const IniFile& ini, std::string& version) { const IniFile::Section* sect = ini.find("antares"); if (sect) @@ -96,19 +95,18 @@ uint StudyHeader::internalFindVersionFromFile(const IniFile& ini) // Version if (p->key == "version") { - uint ret; - if (p->value.to(ret)) - return ret; - break; + version = p->value; + return true; } } } - return (uint)versionUnknown; + + logs.error() << "Couldn't find a version number in study.antares"; + return false; } bool StudyHeader::internalLoadFromINIFile(const IniFile& ini, bool warnings) { - version = 0; const IniFile::Section* sect = ini.find("antares"); if (sect) { @@ -129,7 +127,7 @@ bool StudyHeader::internalLoadFromINIFile(const IniFile& ini, bool warnings) // Version if (p->key == "version") { - version = p->value.to(); + version.fromString(p->value); continue; } @@ -139,7 +137,9 @@ bool StudyHeader::internalLoadFromINIFile(const IniFile& ini, bool warnings) if (ConvertCStrToTimeT(p->value.c_str(), &dateCreated) && !dateCreated) { if (warnings) + { logs.error() << "Study header: The date of creation is invalid"; + } dateCreated = ::time(nullptr); } continue; @@ -149,7 +149,9 @@ bool StudyHeader::internalLoadFromINIFile(const IniFile& ini, bool warnings) if (ConvertCStrToTimeT(p->value.c_str(), &dateLastSave) && !dateLastSave) { if (warnings) + { logs.error() << "Study header: The date of the last save is invalid"; + } dateLastSave = ::time(nullptr); } continue; @@ -159,25 +161,21 @@ bool StudyHeader::internalLoadFromINIFile(const IniFile& ini, bool warnings) else { if (warnings) + { logs.error() << "The main section has not been found. The study seems invalid."; + } } - if (version >= 700) + if (version.isSupported(true)) { - if (version > static_cast(Data::versionLatest)) - { - if (warnings) - { - logs.error() << "Header: This version is not supported (version found:" << version - << ", expected: <=" << static_cast(Data::versionLatest) << ')'; - } - return false; - } return true; } if (warnings) + { logs.error() << "Study header: Invalid format"; + } + return false; } @@ -198,13 +196,47 @@ bool StudyHeader::saveToFile(const AnyString& filename, bool upgradeVersion) return ini.save(filename); } -uint StudyHeader::ReadVersionFromFile(const AnyString& filename) +StudyVersion StudyHeader::tryToFindTheVersion(const std::string& folder) +{ + if (folder.empty()) // trivial check + { + return StudyVersion::unknown(); + } + + // folder normalization + fs::path abspath = fs::absolute(folder); + abspath = abspath.lexically_normal(); + + if (fs::exists(abspath)) + { + abspath /= "study.antares"; + if (fs::exists(abspath)) + { + // The raw version number + std::string versionStr; + if (!readVersionFromFile(abspath, versionStr)) + { + return StudyVersion::unknown(); + } + + StudyVersion v; + v.fromString(versionStr); + return v; + } + } + return StudyVersion::unknown(); +} + +bool StudyHeader::readVersionFromFile(const fs::path& filename, std::string& version) { IniFile ini; if (ini.open(filename)) - return internalFindVersionFromFile(ini); - return (uint)versionUnknown; + { + return internalFindVersionFromFile(ini, version); + } + + logs.error() << "Couldn't open study.antares to find the version number"; + return false; } } // namespace Antares::Data - diff --git a/src/libs/antares/study/header.h b/src/libs/antares/study/header.h deleted file mode 100644 index 1dd472719f..0000000000 --- a/src/libs/antares/study/header.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_HEADER_H__ -#define __ANTARES_LIBS_STUDY_HEADER_H__ - -#include -#include -#include -#include - -//! Default author -#define STUDYHEADER_DEFAULT_AUTHOR "Unknown" -//! Default caption -#define STUDYHEADER_DEFAULT_CAPTION "No title" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Header of a study -** \ingroup study -*/ -class StudyHeader final -{ -public: - /*! - ** \brief Get the version of a header - ** - ** \param filename The filename to read - ** \return The version of the study, or 0 if unknown (invalid header) - */ - static uint ReadVersionFromFile(const AnyString& filename); - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - StudyHeader(); - /*! - ** \brief Destructor - */ - ~StudyHeader(); - //@} - - /*! - ** \brief Reset the values - */ - void reset(); - - /*! - ** \brief Load a study header from a file - ** - ** \param filename The target filename - ** \param warnings Enable warnings/errors - ** \return True if the operation succeeded, false otherwise - */ - bool loadFromFile(const AnyString& filename, bool warnings = true); - - /*! - ** \brief Save a study header into a file - ** - ** The property `version` will be upgraded to the last available - ** and `dateLastSave` as well. - ** - ** \param filename The target filename - ** \return True if the operation succeeded, false otherwise - */ - bool saveToFile(const AnyString& filename, bool upgradeVersion = true); - - //! Copy the internal settings into an INI structure - void CopySettingsToIni(IniFile& ini, bool upgradeVersion); - -public: - //! Caption of the study - Yuni::String caption; - - //! Format version - uint version; - - //! Date: Creation (timestamp) - time_t dateCreated; - //! Date: Last save (timestamp) - time_t dateLastSave; - - //! Author - Yuni::String author; - -private: - //! Load settings from an INI file - bool internalLoadFromINIFile(const IniFile& ini, bool warnings); - - //! Get the version written in an header file - static uint internalFindVersionFromFile(const IniFile& ini); - -}; // class StudyHeader; - -} // namespace Data -} // namespace Antares - -#include "header.hxx" - -#endif /* __ANTARES_LIBS_STUDY_HEADER_H__ */ diff --git a/src/libs/antares/study/header.hxx b/src/libs/antares/study/header.hxx deleted file mode 100644 index 4cbb3cf70b..0000000000 --- a/src/libs/antares/study/header.hxx +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_HEADER_HXX__ -#define __ANTARES_LIBS_STUDY_HEADER_HXX__ - -namespace Antares -{ -namespace Data -{ -inline StudyHeader::StudyHeader() -{ - reset(); -} - -inline StudyHeader::~StudyHeader() -{ -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_HEADER_HXX__ diff --git a/src/libs/antares/study/importlogs.cpp b/src/libs/antares/study/importlogs.cpp index 5b89107f26..080f38e174 100644 --- a/src/libs/antares/study/importlogs.cpp +++ b/src/libs/antares/study/importlogs.cpp @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include + #include -#include "study.h" -#include #include +#include +#include "antares/study/study.h" + using namespace Yuni; namespace Antares @@ -40,11 +36,12 @@ namespace Data void Study::importLogsToOutputFolder(Solver::IResultWriter& resultWriter) const { if (!logs.logfile()) + { return; + } - std::string logPath("simulation.log"); - String from; - IO::Normalize(from, logs.logfile()); + std::filesystem::path from = logs.logfile().c_str(); + from = from.lexically_normal(); if (System::windows) { @@ -53,12 +50,12 @@ void Study::importLogsToOutputFolder(Solver::IResultWriter& resultWriter) const logs.closeLogfile(); } - resultWriter.addEntryFromFile(logPath, from.c_str()); + resultWriter.addEntryFromFile("simulation.log", from.string()); if (System::windows) { // Reopen the log file - logs.logfile(from); + logs.logfile(from.string()); } } diff --git a/src/libs/antares/study/UnfeasibleProblemBehavior.hpp b/src/libs/antares/study/include/antares/study/UnfeasibleProblemBehavior.hpp similarity index 83% rename from src/libs/antares/study/UnfeasibleProblemBehavior.hpp rename to src/libs/antares/study/include/antares/study/UnfeasibleProblemBehavior.hpp index 4de5ac65ab..66c03305e9 100644 --- a/src/libs/antares/study/UnfeasibleProblemBehavior.hpp +++ b/src/libs/antares/study/include/antares/study/UnfeasibleProblemBehavior.hpp @@ -5,8 +5,8 @@ ** This file is part of Antares_Simulator. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** ** There are special exceptions to the terms and conditions of the @@ -17,12 +17,12 @@ ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** SPDX-License-Identifier: MPL-2.0 */ #ifndef ANTARES_DATA_UNFEASIBLEPROBLEMHAVIOR_HPP @@ -77,4 +77,4 @@ bool stopSimulation(const UnfeasibleProblemBehavior& unfeasibleProblemBehavior); } // namespace Antares -#endif // ANTARES_DATA_UNFEASIBLEPROBLEMHAVIOR_HPP \ No newline at end of file +#endif // ANTARES_DATA_UNFEASIBLEPROBLEMHAVIOR_HPP diff --git a/src/libs/antares/study/include/antares/study/area/area.h b/src/libs/antares/study/include/antares/study/area/area.h new file mode 100644 index 0000000000..6661ab8556 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/area.h @@ -0,0 +1,846 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_AREAS_H__ +#define __ANTARES_LIBS_STUDY_AREAS_H__ + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include "antares/study/filter.h" +#include "antares/study/parts/parts.h" + +#include "constants.h" +#include "links.h" +#include "ui.h" + +namespace Antares +{ +namespace Data +{ +struct CompareAreaName; + +/*! +** \brief Definition for a single area +*/ +class Area final: private Yuni::NonCopyable +{ +public: + using NameSet = std::set; + using Set = std::set; + using LinkMap = std::map; + using Map = std::map; + using Vector = std::vector; + using VectorConst = std::vector; + using List = std::list; + using ScratchMap = std::map; + //! Name mapping -> must be replaced by AreaNameMapping + using NameMapping = std::map; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Area(); + /*! + ** \brief Constructor with a given name + ** + ** \param name The name of the area + */ + explicit Area(const AnyString& name); + /*! + ** \brief Constructor + ** + ** \param name Name of the area + ** \param id id of the area + */ + Area(const AnyString& name, const AnyString& id); + /*! + ** \brief Destructor + */ + ~Area(); + + //@} + + // !\name isVisibleOnLayer + //@{ + /*! + ** \brief check visibility on layer + */ + bool isVisibleOnLayer(const size_t& layerID) const + { + if (ui == nullptr) + { + return false; + } + + std::vector& layerList = ui->mapLayersVisibilityList; + std::vector::iterator layerPosition = std::find(layerList.begin(), + layerList.end(), + layerID); + return layerPosition != layerList.end(); + } + + //! \name Links + //@{ + /*! + ** \brief Destroy all links + */ + void clearAllLinks(); + + /*! + ** \brief Properly detach all links attached to an area + ** + ** It is the safe way to add an area and it is mainly used by the GUI + */ + void detachAllLinks(); + + /*! + ** \brief Try to find the attached link from another area id + */ + AreaLink* findLinkByID(const AreaName& id); + const AreaLink* findLinkByID(const AreaName& id) const; + + /*! + ** \brief Detach any link connected from this area to the given area + */ + void detachLinkFromID(const AreaName& id); + + static void detachLink(const AreaLink* lnk); + + /*! + ** \brief Remove a link from its raw pointer + */ + void detachLinkFromItsPointer(const AreaLink* lnk); + //@} + + void buildLinksIndexes(); + /*! + ** \brief Ensure all data are created + */ + void createMissingData(); + + /*! + ** \brief Reset all values to their default one + */ + void resetToDefaultValues(); + + /*! + ** \brief Resize all matrices dedicated to the sampled timeseries numbers + ** + ** \param n A number of years + */ + void resizeAllTimeseriesNumbers(uint nbYears); + + /*! + ** \brief Check if a link with another area is already established + ** + ** \param with Any area + ** \return A pointer to an existing link if found, NULL otherwise + */ + AreaLink* findExistingLinkWith(Area& with); + const AreaLink* findExistingLinkWith(const Area& with) const; + + //! \name Memory management + //@{ + /*! + ** \brief Load all data not already loaded + ** + ** If the load-on-demand is enabled, some data might not be loaded (see `Matrix`) + ** However, we would like to be able to force the load of all data, especially + ** when saving a study. + ** The flag `invalidateJIT` will be reset to false. + ** + ** \param reload True to force the reload of data + ** \return True if the operation succeeded + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark all areas as modified + */ + void markAsModified() const; + + /*! + ** \brief Get the amount of memory currently used by the area + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Try to estimate the amount of memory required by the area for a simulation + */ + + //@} + + //! \name Thermal clusters min stable power validity checking + //@{ + /*! + ** \brief Check the validity of min stable power for all thermal clusters + ** + ** \return True if the value of min stable power is a good one + */ + bool thermalClustersMinStablePowerValidity(std::vector& output) const; + //@} + + /*! + ** \brief Get the XCast data according a given time-series type + */ + template + XCast* xcastData(); + template + const XCast* xcastData() const; + +public: + //! \name General + //@{ + //! Name of the area + AreaName name; + //! Name of the area in lowercase format + AreaName id; + //! Index of the area - only valid when already added to an area list + uint index = (uint)(-1); + //! Use adequacy patch for this area + AdequacyPatch::AdequacyPatchMode adequacyPatchMode = AdequacyPatch::physicalAreaOutsideAdqPatch; + /*@}*/ + + //! \name Associate data */ + //@{ + /*! + ** \brief Reserves + ** + ** Reserves, DSM, D-1... + ** \see enum ReservesIndex + */ + Matrix<> reserves; + /*! + ** \brief Misc Gen + ** + ** (previously called `Fatal hors hydro`) - fhhMax * HOURS_PER_YEAR + ** The sum is done in runtimeinfos.cpp + */ + Matrix<> miscGen; // [fhhMax][HOURS_PER_YEAR] + //@} + + //! \name Load + //@{ + Load::Container load; + //@} + + //! \name Solar + //@{ + Solar::Container solar; + //@} + + //! \name Hydro + //@{ + PartHydro hydro; + //@} + + //! \name Wind + //@{ + //! Wind time-series and Wind prepro data + Wind::Container wind; + //@} + + //! \name Thermal + //@{ + PartThermal thermal; + //@} + + //! \name Renewable + //@{ + PartRenewable renewable; + //@} + + ShortTermStorage::STStorageInput shortTermStorage; + + //! \name Interconnections + //@{ + //! All connections with this area + AreaLink::Map links; + //@} + + //! \name Nodal Optimization + //@{ + //! Nodal optimization (see AreaNodalOptimization) + uint nodalOptimization = anoAll; + //@} + + //! \name Spread + //@{ + //! Spread for the unsupplied energy cost + double spreadUnsuppliedEnergyCost = 0.; + //! Spread for the spilled energy cost + double spreadSpilledEnergyCost = 0.; + //@} + + //! \name Output filtering + //@{ + //! Print results for the area in the simulation synthesis + uint filterSynthesis = filterAll; + //! Print results for the area in the year-by-year mode + uint filterYearByYear = filterAll; + //@} + + //! \name UI + //@{ + //! Information for the UI + AreaUI* ui = nullptr; + //@} + + //! \name Dynamic + //@{ + /*! + ** \brief Scratchpad used temporary calculations (solver only) + */ + mutable std::vector scratchpad; + //@} + + //! \name Data + //@{ + /*! + ** \brief Invalidate (JIT) + ** + ** A non-zero value if the missing data must be loaded from HDD for the next + ** save (only valid if JIT enabled). + */ + mutable bool invalidateJIT = false; + //@} + +private: + void internalInitialize(); + void createMissingTimeSeries(); + void createMissingPrepros(); + +}; // class Area + +bool saveAreaOptimisationIniFile(const Area& area, const Yuni::Clob& buffer); + +bool saveAreaAdequacyPatchIniFile(const Area& area, const Yuni::Clob& buffer); + +/*! +** \brief A list of areas +** +** Here is one way to iterate through the list : +** \code +** AreaList* l; +** ... +** +** ... +** Area* c = l->first; +** while (NULL != c) +** { +** ... +** +** ... +** c = c->next; +** } +** \endcode +** +** It is possible to directly access to an area via its index : +** \code +** AreaList* l; +** ... +** +** ... +** printf("Area name : `%s`\n", (*(l->byIndex[2])).name); +** \endcode +*/ +class AreaList final: public Yuni::NonCopyable +{ +public: + //! An iterator + using iterator = Area::Map::iterator; + //! A const iterator + using const_iterator = Area::Map::const_iterator; + //! An iterator + using reverse_iterator = Area::Map::reverse_iterator; + //! A const iterator + using const_reverse_iterator = Area::Map::const_reverse_iterator; + //! Key-value type + using value_type = Area::Map::value_type; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + explicit AreaList(Study& study); + //! Destructor + ~AreaList(); + //@} + + //! \name Iterating through all areas + //@{ + /*! + ** \brief Iterate through all areas + */ + template + void each(const PredicateT& predicate); + /*! + ** \brief Iterate through all areas (const) + */ + template + void each(const PredicateT& predicate) const; + + iterator begin(); + const_iterator begin() const; + const_iterator cbegin() const; + + iterator end(); + const_iterator end() const; + const_iterator cend() const; + + reverse_iterator rbegin(); + const_reverse_iterator rbegin() const; + + reverse_iterator rend(); + const_reverse_iterator rend() const; + + //! \name Internal Data TS-Generators / Series + //@{ + /*! + ** \brief Ensure data for time series/prepro are initalized if they should be + ** + ** It initializes data for each area so it would be better to call this + ** routine when areas are already loaded. + */ + + void ensureDataIsInitialized(Parameters& params, bool loadOnlyNeeded); + //@} + + //! \name Import / Export + //@{ + /*! + ** \brief Load all informations about areas from a folder (-> input/generalData) + ** + ** \param l The list of areas + ** \param folder The target folder + */ + bool loadFromFolder(const StudyLoadOptions& options); + + /*! + ** \brief Fill the list of areas from an input file + ** + ** The file structure is merely composed by all names of areas, one line one area + ** + ** \param l The structure + ** \param filename The file to read + ** \return A non-zero value if the operation was successful, 0 otherwise + */ + bool loadListFromFile(const AnyString& filename); + + /*! + ** \brief Save all informations about areas into a folder (-> input/generalData) + ** + ** \param l The list of areas + ** \param folder The target folder + */ + bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Write the list of areas into a file + ** + ** The file structure is merely composed by all names of areas, one line one area + ** + ** \param filename The file to read + ** \return A non-zero value if the operation was successful, 0 otherwise + */ + bool saveListToFile(const AnyString& filename) const; + + /*! + ** \brief Write the list of all links into a file + ** + ** \code + ** + ** + ** + ** + ** + ** + ** \endcode + ** + ** \param filename The file to read + ** \return A non-zero value if the operation was successful, 0 otherwise + */ + void saveLinkListToBuffer(Yuni::Clob& buffer) const; + + /*! + ** \brief Preload all areas which have been invalidated + ** + ** \param [out] The number of areas which have been invalidated + */ + bool preloadAndMarkAsModifiedAllInvalidatedAreas(uint* invalidateCount = nullptr) const; + //@} + + //! \name Areas + //@{ + /*! + ** \brief Add an area in the container + */ + Area* add(Area* a); + + /*! + ** \brief Find an area from its unique string id + */ + Area* find(const AreaName& id); + /*! + ** \brief Find an area from its unique string id (const) + */ + const Area* find(const AreaName& id) const; + + /*! + ** \brief Find an area from its name + */ + Area* findFromName(const AreaName& name); + + Area* findFromPosition(const int x, const int y) const; + + /*! + ** \brief Find an area from its name (const) + */ + const Area* findFromName(const AreaName& name) const; + + /*! + ** \brief Resize all matrices dedicated to the sampled timeseries numbers + ** + ** \param n A number of years + */ + void resizeAllTimeseriesNumbers(uint n); + + /*! + ** \brief Remove all elements in the container + */ + void clear(); + + //! Get if the container is empty + bool empty() const; + + /*! + ** \brief Invalidate all areas + ** + ** \param reload True to reload data in the same time + ** \return True if the operation succeeded + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark all data as modified + */ + void markAsModified() const; + + /*! + ** \brief Rebuild the indexes for accessing areas + ** + ** It is sometimes quite usefull to use a mere index to access to + ** a given area. This is mandatory when used from the solver. + */ + void rebuildIndexes(); + + /*! + ** \brief Remove an area from its ID + ** + ** \warning When used by a study, do not forget to remove all binding + ** constraints which depends upon this area before any call to this + ** routine. + */ + bool remove(const AnyString& id); + + /*! + ** \brief Rename an area + ** + ** \param oldid ID of the area to rename + ** \param newName The new name for the area + ** \return True if the operation succeeded (the area has been renamed) + ** false otherwise (if another area has the same name) + ** + ** \warning This function invalidates the index of all areas. If you need + ** the indexes after a call to this routine, please use AreaListRebuildIndex() + */ + bool renameArea(const AreaName& oldid, const AreaName& newName); + + /*! + ** \brief Rename an area + ** + ** \param oldid ID of the area to rename + ** \param newID The new area ID + ** \param newName The new name for the area + ** \return True if the operation succeeded (the area has been renamed) + ** false otherwise (if another area has the same name) + ** + ** \warning This function invalidates the index of all areas. If you need + ** the indexes after a call to this routine, please use AreaListRebuildIndex() + */ + bool renameArea(const AreaName& oldid, const AreaName& newid, const AreaName& newName); + + /*! + ** \brief Get the total number of areas + */ + uint size() const; + //@} + + //! \name Links + //@{ + /*! + ** \brief Find an interconnection between two areas + ** + ** \param area The name of the first area (in lowercase) + ** \param with The name of the second area (in lowercase) + */ + AreaLink* findLink(const AreaName& area, const AreaName& with); + const AreaLink* findLink(const AreaName& area, const AreaName& with) const; + + /*! + ** \brief Try to find the link from a given INI key (%) + */ + AreaLink* findLinkFromINIKey(const AnyString& key); + + /*! + ** \brief Try to find the cluster from a given INI key (.) + */ + ThermalCluster* findClusterFromINIKey(const AnyString& key); + + /*! + ** \brief Get the total number of interconnections between all areas + */ + uint areaLinkCount() const; + //@} + + //! \name Tools + //@{ + /*! + ** \brief Fix all invalid orientations + */ + void fixOrientationForAllInterconnections(BindingConstraintsRepository& bindingconstraints); + + //! Remove all load timeseries + void removeLoadTimeseries(); + //! Remove all hydro timeseries + void removeHydroTimeseries(); + //! Remove all solar timeseries + void removeSolarTimeseries(); + //! Remove all wind timeseries + void removeWindTimeseries(); + //! Remove all thermal timeseries + void removeThermalTimeseries(); + //@} + + /// create a map with the corresponding scratchpad for each area link to this numspace + Area::ScratchMap buildScratchMap(uint numspace); + + //! \name Memory management + //@{ + /*! + ** \brief Try to estimate the amount of memory required by the class for a simulation + */ + + /*! + ** \brief Get the average amount of memory currently used by each area + */ + double memoryUsageAveragePerArea() const; + + /*! + ** \brief Get the amount of memory currently used by the class + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Update the name id set + */ + void updateNameIDSet() const; + //@} + + //! \name Operators + //@{ + /*! + ** \brief Get an area from its index + */ + Area* operator[](uint i); + const Area* operator[](uint i) const; + //@} + +public: + //! All areas by their index + Area** byIndex = nullptr; + //! All areas in the list + Area::Map areas; + + //! Name set (must be updated by updateNameSet) + // used by the copy/paste + mutable Area::NameSet nameidSet; + +private: + //! The parent study + Study& pStudy; + +}; // class AreaList + +void AreaListDeleteLinkFromAreaPtr(AreaList* l, const Area* a); + +/*! +** \brief Establish a link between two areas +** +** No check are made at this stade +** +** \param area The main area from where to establish the link +** \param with The second area +** \return A pointer to the structure used by the link between +** the two areas +*/ +AreaLink* AreaAddLinkBetweenAreas(Area* area, Area* with, bool warning = true); + +/*! +** \brief Load interconnections of a given area from a folder (`input/areas/[area]/ntc`) +** +** \param area The area +** \param folder The target folder +** \return A non-null value if the operation succeeded, 0 otherwise +*/ +bool AreaLinksLoadFromFolder(Study& s, + AreaList* l, + Area* area, + const std::filesystem::path& folder); + +/*! +** \brief Save interconnections of a given area into a folder (`input/areas/[area]/ntc`) +** +** \param area The area +** \param folder The target folder +** \return True if the operation succeeded, 0 otherwise +*/ +bool AreaLinksSaveToFolder(const Area* area, const char* const folder); + +// Save a given area's interconnexions configuration file into a folder +bool saveAreaLinksConfigurationFileToFolder(const Area* area, const char* const folder); + +/*! +** \brief Clear all interconnection from an area +*/ +int AreaLinkClear(AreaList* l, Area* area); + +/*! +** \brief Remove a connection +*/ +void AreaLinkRemove(AreaLink* lnk); + +/*! +** \brief Try to find an area by its name (in lowercase) +** +** \param l The area list +** \param lname The name of the area in lowercase +** \return A valid pointer to the area structure if found, NULL otherwise +*/ +Area* AreaListLFind(AreaList* l, const char lname[]); + +/*! +** \brief Try to find an area by its ptr +** +** \param l The area list +** \param ptr The ptr +** \return A valid pointer to the area structure if found, NULL otherwise +*/ +Area* AreaListFindPtr(AreaList* l, const Area* ptr); + +/*! +** \brief Add an area in the list from a given name +** +** \param l The list of areas +** \param name The name of the area +** \return A valid pointer to the area if successful, NULL otherwise +*/ +Area* addAreaToListOfAreas(AreaList& list, const AnyString& name); + +/*! +** \brief Add an area in the list from a given name +** +** \param l The list of areas +** \param name The name of the area +** \param lname The name of the area in lowercase +** \return A valid pointer to the area if successful, NULL otherwise +*/ +Area* AreaListAddFromNames(AreaList& list, const AnyString& name, const AnyString& lname); + +/*! +** \brief Try to establish a link between two areas +** +** \param l The list of areas +** \param area The area to make a link +** \param with The area to link with +*/ +AreaLink* AreaListAddLink(AreaList* l, const char area[], const char with[], bool warning = true); + +void AreaListClearAllLinks(AreaList* l); + +/*! +** \brief Ensure data for load prepro are initialized +*/ +void AreaListEnsureDataLoadPrepro(AreaList* l); + +/*! +** \brief Ensure data for solar prepro are initialized +*/ +void AreaListEnsureDataSolarPrepro(AreaList* l); + +/*! +** \brief Ensure data for wind prepro are initialized +*/ +void AreaListEnsureDataWindPrepro(AreaList* l); + +/*! +** \brief Ensure data for hydro time-series are initialized +*/ +void AreaListEnsureDataHydroTimeSeries(AreaList* l); + +/*! +** \brief Ensure data for hydro prepro are initialized +*/ +void AreaListEnsureDataHydroPrepro(AreaList* l); + +/*! +** \brief Ensure data for thermal prepro are initialized +*/ +void AreaListEnsureDataThermalPrepro(AreaList* l); + +/*! +** \brief to check that Area name does not contains character * +*/ +inline bool CheckForbiddenCharacterInAreaName(const AnyString& name) +{ + return name.contains('*'); +} + +} // namespace Data +} // namespace Antares + +#include "../load-options.h" +#include "area.hxx" + +#endif // __ANTARES_LIBS_STUDY_AREAS_H__ diff --git a/src/libs/antares/study/include/antares/study/area/area.hxx b/src/libs/antares/study/include/antares/study/area/area.hxx new file mode 100644 index 0000000000..cbbc7a1826 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/area.hxx @@ -0,0 +1,163 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/study/parts/load/prepro.h" +#include "antares/study/parts/parts.h" + +namespace Antares::Data +{ +struct CompareAreaName final +{ + inline bool operator()(const Area* s1, const Area* s2) const + { + return s1->name < s2->name; + } +}; + +inline Area* AreaList::operator[](uint i) +{ + assert(i < areas.size() and "Index out of bounds"); + return byIndex[i]; +} + +inline const Area* AreaList::operator[](uint i) const +{ + assert(i < areas.size() and "Index out of bounds"); + return byIndex[i]; +} + +template +inline XCast* Area::xcastData() +{ + switch (T) + { + case timeSeriesLoad: + return &(load.prepro->xcast); + case timeSeriesSolar: + return &(solar.prepro->xcast); + case timeSeriesWind: + return &(wind.prepro->xcast); + case timeSeriesHydro: + return nullptr; + case timeSeriesThermal: + return nullptr; + } + return nullptr; +} + +template +inline const XCast* Area::xcastData() const +{ + switch (T) + { + case timeSeriesLoad: + return &(load.prepro->xcast); + case timeSeriesSolar: + return &(solar.prepro->xcast); + case timeSeriesWind: + return &(wind.prepro->xcast); + case timeSeriesHydro: + return nullptr; + case timeSeriesThermal: + return nullptr; + } + return nullptr; +} + +template +inline void AreaList::each(const PredicateT& predicate) +{ + auto end = areas.end(); + for (auto i = areas.begin(); i != end; ++i) + { + auto& area = *(i->second); + predicate(area); + } +} + +template +inline void AreaList::each(const PredicateT& predicate) const +{ + auto end = areas.cend(); + for (auto i = areas.cbegin(); i != end; ++i) + { + auto& area = *(i->second); + predicate(area); + } +} + +inline uint AreaList::size() const +{ + return (uint)areas.size(); +} + +inline AreaList::iterator AreaList::begin() +{ + return areas.begin(); +} + +inline AreaList::const_iterator AreaList::begin() const +{ + return areas.begin(); +} + +inline AreaList::const_iterator AreaList::cbegin() const +{ + return areas.begin(); +} + +inline AreaList::iterator AreaList::end() +{ + return areas.end(); +} + +inline AreaList::const_iterator AreaList::end() const +{ + return areas.end(); +} + +inline AreaList::const_iterator AreaList::cend() const +{ + return areas.end(); +} + +inline AreaList::reverse_iterator AreaList::rbegin() +{ + return areas.rbegin(); +} + +inline AreaList::const_reverse_iterator AreaList::rbegin() const +{ + return areas.rbegin(); +} + +inline AreaList::reverse_iterator AreaList::rend() +{ + return areas.rend(); +} + +inline AreaList::const_reverse_iterator AreaList::rend() const +{ + return areas.rend(); +} + +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/area/constants.h b/src/libs/antares/study/include/antares/study/area/constants.h new file mode 100644 index 0000000000..01978a7eb5 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/constants.h @@ -0,0 +1,103 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_AREAS_CONSTANTS_H__ +#define __ANTARES_LIBS_STUDY_AREAS_CONSTANTS_H__ + +namespace Antares +{ +namespace Data +{ +struct CompareAreaName; + +enum LinkParameterIndex +{ + //! Hurdles cost, Direct + fhlHurdlesCostDirect = 0, + //! Hurdles cost, Indirect + fhlHurdlesCostIndirect, + //! Impedances, + fhlImpedances, + //! Loop flow, + fhlLoopFlow, + //! P.shift min, + fhlPShiftMinus, + //! P.shift max, + fhlPShiftPlus, + //! Maximum number of items + fhlMax, +}; + +/*! +** \brief Misc. Gen. +*/ +enum MiscGenIndex +{ + //! CHP + fhhCHP = 0, + //! Bio-Mass + fhhBioMass, + //! BioGaz + fhhBioGaz, + //! Waste + fhhWaste, + //! GeoThermal + fhhGeoThermal, + //! Other */ + fhhOther, + //! PSP - Pump + fhhPSP, + //! Row Balance + fhhRowBalance, + //! Maximum number of items + fhhMax +}; + +enum ReservesIndex +{ + //! Primary reserve + fhrPrimaryReserve = 0, + //! Strategic reserve + fhrStrategicReserve, + //! DSM + fhrDSM, + //! D-1 + fhrDayBefore, + //! Maximum number of items + fhrMax, +}; + +enum AreaNodalOptimization +{ + //! Non Dispatchable power + anoNonDispatchPower = 1, + //! Dispatchable Hydro power + anoDispatchHydroPower = 2, + //! Other dispatchable power + anoOtherDispatchPower = 4, + + //! All features + anoAll = anoNonDispatchPower | anoDispatchHydroPower | anoOtherDispatchPower, +}; + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_AREAS_CONSTANTS_H__ diff --git a/src/libs/antares/study/include/antares/study/area/links.h b/src/libs/antares/study/include/antares/study/area/links.h new file mode 100644 index 0000000000..fd4b8e69d8 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/links.h @@ -0,0 +1,222 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_LINKS_H__ +#define __ANTARES_LIBS_STUDY_LINKS_H__ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../fwd.h" + +namespace Antares +{ +namespace Data +{ +struct CompareLinkName; + +/*! +** \brief Definition of a link between two areas (Interconnection) +** +** \ingroup area +*/ +class AreaLink final: public Yuni::NonCopyable +{ +public: + //! Vector of links + using Vector = std::vector; + //! Set of links + using Set = std::set; + //! Map of links + using Map = std::map; + + using NamePair = std::pair; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + AreaLink(); + //! Destructor + ~AreaLink(); + //@} + + bool loadTimeSeries(const StudyVersion& version, const AnyString& folder); + + void storeTimeseriesNumbers(Solver::IResultWriter& writer) const; + + //! \name Area + //@{ + /*! + ** \brief Detach the link from the areas + */ + void detach(); + //@} + + //! \name Data management + //@{ + /*! + ** \brief Reverse the link + ** + ** Be careful, this method does not invert the sign of the weight + ** for binding constraints. + */ + void reverse(); + + void resetToDefaultValues(); + + /*! + ** \brief Invalidate all matrices + ** + ** \param reload True to load all missing data + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark the data associated to the link as modified + */ + void markAsModified() const; + //@} + + //! \name Memory management + //@{ + /*! + ** \brief Get the size (bytes) in memory occupied by a `AreaLink` structure + */ + uint64_t memoryUsage() const; + + bool isVisibleOnLayer(const size_t& layerID) const; + + Yuni::String getName() const; + + bool isLinkPhysical() const; + void overrideTransmissionCapacityAccordingToGlobalParameter(GlobalTransmissionCapacities tc); + +private: + bool linkLoadTimeSeries_for_version_below_810(const AnyString& folder); + bool linkLoadTimeSeries_for_version_820_and_later(const AnyString& folder); + NamePair getNamePair() const; + +public: + //! \name Graph + //@{ + //! The orginal Area + Area* from; + //! The other area | Hash ID: with->id + Area* with; + //@} + + //! Monte-Carlo + TimeSeriesNumbers timeseriesNumbers; + + //! \name Data + //@{ + /*! + ** \brief Data related to the link + ** + */ + Matrix<> parameters; + TimeSeries directCapacities; + TimeSeries indirectCapacities; + + //! Flag for using loop flow + bool useLoopFlow; + + //! Flag for using the phase shifter + bool usePST; + + //! Flag for using hurdles cost + bool useHurdlesCost; + + //! Flag for the transmission capacities (NTC +infinite) + // previously called copper plate + LocalTransmissionCapacities transmissionCapacities; + //@} + + //! Flag for the asset type (AC/DC/Other) + AssetType assetType; + + //! \name Indexes + //@{ + /*! + ** \brief Index of the link in the entire list if Interconnections + ** + ** \internal This variable must only be used when runtime data are + ** available + */ + uint index; + /*! + ** \brief Index of the link in the list of interconnection of the main area + ** + ** \internal This variable must only be used when runtime data are + ** available + */ + uint indexForArea; + //@} + + //! \name Comments + //@{ + //! Comments + Yuni::String comments; + //! Flag for displaying comments + bool displayComments; + //@} + + //! \name Output filtering + //@{ + //! Print results for the area in the simulation synthesis + uint filterSynthesis; + //! Print results for the area in the year-by-year mode + uint filterYearByYear; + //@} + + //! Colors + int color[3]; + //! Style + StyleType style; + //! link width + int linkWidth; + + friend struct CompareLinkName; +}; // class AreaLink + +struct CompareLinkName final +{ + inline bool operator()(const AreaLink* s1, const AreaLink* s2) const + { + return s1->getNamePair() < s2->getNamePair(); + } +}; + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_LINKS_H__ diff --git a/src/libs/antares/study/include/antares/study/area/scratchpad.h b/src/libs/antares/study/include/antares/study/area/scratchpad.h new file mode 100644 index 0000000000..864d50a155 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/scratchpad.h @@ -0,0 +1,106 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_AREA_SCRATCHPAD_H__ +#define __ANTARES_LIBS_STUDY_AREA_SCRATCHPAD_H__ + +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "../fwd.h" + +namespace Antares::Data +{ +/*! +** \brief Scratchpad for temporary data performed by the solver +*/ +class AreaScratchpad final +{ +public: + //! Matrix used for time-series + using TSMatrix = Matrix; + + //! \name Constructor + //@{ + /*! + ** \brief Constructor + */ + AreaScratchpad(const StudyRuntimeInfos& rinfos, Area& area); + //! Destructor + ~AreaScratchpad() = default; + //@} + + //! Sum of all fatal hors hydro + double miscGenSum[HOURS_PER_YEAR]; + + bool hydroHasMod; + + //! if sum(365)[pumpMaxP * pumpMaxE] > 0. then pumpHasMod = true + // else pumpHasMod = false + bool pumpHasMod; + + //! Sum of all 'must-run' clusters + // This variable is initialized every MC-year + std::array mustrunSum; + + //! Sum of all original 'must-run' clusters (adequacy only) + // This variable is initialized every MC-year + std::array originalMustrunSum; + + /*! + ** \brief Dispatchable Generation Margin + ** + ** Those values, written by the output, must be calculated before + ** running the hydro remix. + */ + double dispatchableGenerationMargin[168]; + + /*! + ** \brief Daily mean maximum power matrices + ** + ** These matrices will be calculated based on maximum + ** hourly generation/pumping matrices + */ + TimeSeries meanMaxDailyGenPower; + TimeSeries meanMaxDailyPumpPower; + +private: + /*! + ** \brief Caluclation of daily mean maximum power matrices + ** + ** Calculates daily mean maximum generation/pumping power + ** power matrices meanMaxDailyGenPower/meanMaxDailyPumpPower + */ + void CalculateMeanDailyMaxPowerMatrices(const Matrix& hourlyMaxGenMatrix, + const Matrix& hourlyMaxPumpMatrix); + +}; // class AreaScratchpad + +} // namespace Antares::Data + +#endif // __ANTARES_LIBS_STUDY_AREA_SCRATCHPAD_H__ diff --git a/src/libs/antares/study/include/antares/study/area/store-timeseries-numbers.h b/src/libs/antares/study/include/antares/study/area/store-timeseries-numbers.h new file mode 100644 index 0000000000..56b6d8969f --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/store-timeseries-numbers.h @@ -0,0 +1,48 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include + +#include "area.h" + +namespace Antares::Data +{ +template +void singleAreaStoreTimeseriesNumbers(Solver::IResultWriter& writer, const Area& area); + +template +void storeTimeseriesNumbers(Solver::IResultWriter& writer, const AreaList& area); + +// Store time-series numbers +void storeTimeseriesNumbersForLoad(Solver::IResultWriter& writer, const Area& area); +void storeTimeseriesNumbersForSolar(Solver::IResultWriter& writer, const Area& area); +void storeTimeseriesNumbersForWind(Solver::IResultWriter& writer, const Area& area); +void storeTimeseriesNumbersForHydro(Solver::IResultWriter& writer, const Area& area); +void storeTimeseriesNumbersForThermal(Solver::IResultWriter& writer, const Area& area); +void storeTimeseriesNumbersForRenewable(Solver::IResultWriter& writer, const Area& area); +void storeTimeseriesNumbersForTransmissionCapacities(Solver::IResultWriter& writer, + const Area& area); +void storeTimeseriesNumbersForHydroMaxPower(Solver::IResultWriter& writer, const Area& area); + +} // namespace Antares::Data + +#include "store-timeseries-numbers.hxx" diff --git a/src/libs/antares/study/include/antares/study/area/store-timeseries-numbers.hxx b/src/libs/antares/study/include/antares/study/area/store-timeseries-numbers.hxx new file mode 100644 index 0000000000..f811ef71be --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/store-timeseries-numbers.hxx @@ -0,0 +1,73 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_STORE_TIMESERIES_HXX__ +#define __ANTARES_LIBS_STUDY_STORE_TIMESERIES_HXX__ + +namespace Antares::Data +{ +template +void singleAreaStoreTimeseriesNumbers(Solver::IResultWriter& writer, const Area& area) +{ + switch (TimeSeriesT) + { + // Load + case timeSeriesLoad: + storeTimeseriesNumbersForLoad(writer, area); + break; + // Solar + case timeSeriesSolar: + storeTimeseriesNumbersForSolar(writer, area); + break; + // Hydro + case timeSeriesHydro: + storeTimeseriesNumbersForHydro(writer, area); + break; + // Wind + case timeSeriesWind: + storeTimeseriesNumbersForWind(writer, area); + break; + // Thermal + case timeSeriesThermal: + storeTimeseriesNumbersForThermal(writer, area); + break; + // Renewable + case timeSeriesRenewable: + storeTimeseriesNumbersForRenewable(writer, area); + break; + // Transmission capacities (NTC) + case timeSeriesTransmissionCapacities: + storeTimeseriesNumbersForTransmissionCapacities(writer, area); + break; + default: + break; + } +} + +template +void storeTimeseriesNumbers(Solver::IResultWriter& writer, const AreaList& area) +{ + // Each area in the list + area.each([&writer](const Area& a) + { singleAreaStoreTimeseriesNumbers(writer, a); }); +} +} // namespace Antares::Data + +#endif // __ANTARES_LIBS_STUDY_STORE_TIMESERIES_HXX__ diff --git a/src/libs/antares/study/include/antares/study/area/ui.h b/src/libs/antares/study/include/antares/study/area/ui.h new file mode 100644 index 0000000000..9ab5f39c8b --- /dev/null +++ b/src/libs/antares/study/include/antares/study/area/ui.h @@ -0,0 +1,111 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_UI_H__ +#define __ANTARES_LIBS_STUDY_UI_H__ + +#include + +#include +#include + +namespace Antares +{ +namespace Data +{ +/*! +** \brief Information about the Area for the UI +*/ +class AreaUI final +{ +public: + //! Default constructor + AreaUI(); + + //! Default constructor + ~AreaUI() + { + mapLayersVisibilityList.clear(); + } + + /*! + ** \brief (Re)Initialize all properties + */ + void reset(); + + /*! + ** \brief Load settings from an INI file + */ + bool loadFromFile(const AnyString& filename); + + /*! + ** \brief Save the settings into a file + ** + ** \param filename Filename + ** \param force True to not rely on the modifier flag + */ + bool saveToFile(const AnyString& filename, bool force = false) const; + + /*! + ** \brief Amount of memory consummed by the instance + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Get if the structure has been modified + */ + bool modified() const; + + /*! + ** \brief Mark the structure as modified + */ + void markAsModified(); + + void rebuildCache(); + +public: + //! The X-Coordinate + int x; + std::map layerX; + //! The Y-Coordinate + int y; + std::map layerY; + + //! Color of the area (RGB) + int color[3]; + std::map layerColor; + + //! HSV color model (only computed from the interface) + // \see UIRuntimeInfo::reload() + Yuni::CString<12, false> cacheColorHSV; + + //! The list of layers this Node will appear on + std::vector mapLayersVisibilityList; + +private: + //! Modifier flag + mutable bool pModified; + +}; // class AreaUI + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_UI_H__ diff --git a/src/libs/antares/study/binding_constraint/BindingConstraint.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraint.h similarity index 87% rename from src/libs/antares/study/binding_constraint/BindingConstraint.h rename to src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraint.h index 98f2b4dc1c..e88c7b1bb6 100644 --- a/src/libs/antares/study/binding_constraint/BindingConstraint.h +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraint.h @@ -1,57 +1,55 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once +#include +#include +#include +#include + #include -#include #include -#include "../fwd.h" -#include "../../constants.h" -#include "../area/links.h" -#include "../parts/thermal/cluster.h" +#include + #include #include -#include "EnvForLoading.h" +#include "antares/antares/antares.h" #include "antares/study/filter.h" + +#include "../area/links.h" +#include "../fwd.h" +#include "../parts/thermal/cluster.h" #include "BindingConstraintStructures.h" -#include -#include -#include -#include +#include "EnvForLoading.h" namespace Antares::Data { // Forward declaration struct CompareBindingConstraintName; -class BindingConstraint final : public Yuni::NonCopyable +class BindingConstraint final: public Yuni::NonCopyable { friend class BindingConstraintLoader; friend class BindingConstraintSaver; + public: enum Type { @@ -66,6 +64,7 @@ class BindingConstraint final : public Yuni::NonCopyable //! The maximum number of types typeMax }; + enum Operator { opUnknown = 0, @@ -75,6 +74,7 @@ class BindingConstraint final : public Yuni::NonCopyable opBoth, opMax }; + enum Column { columnInferior = 0, @@ -143,13 +143,17 @@ class BindingConstraint final : public Yuni::NonCopyable ** \brief Get the name of the binding constraint */ const ConstraintName& name() const; + /*! ** \brief Set the name of the binding constraint - ** - ** The ID will be changed in the same time */ void name(const AnyString& newname); + /*! + ** \brief Set the pId of the binding constraint + */ + void pId(const AnyString& name); + /*! ** \brief Get the ID of the binding constraint */ @@ -191,11 +195,10 @@ class BindingConstraint final : public Yuni::NonCopyable bool skipped() const; bool isActive() const; - //Ref to prevent copy. const ref to prevent modification. + // Ref to prevent copy. const ref to prevent modification. const Matrix<>& RHSTimeSeries() const; Matrix<>& RHSTimeSeries(); - bool hasAllWeightedLinksOnLayer(size_t layerID); bool hasAllWeightedClustersOnLayer(size_t layerID); @@ -239,7 +242,7 @@ class BindingConstraint final : public Yuni::NonCopyable void copyWeights(const Study& study, const BindingConstraint& rhs, bool emptyBefore, - Yuni::Bind& translate); + const std::function& translate); /*! ** \brief Get the offset of a given interconnection @@ -271,7 +274,7 @@ class BindingConstraint final : public Yuni::NonCopyable void copyOffsets(const Study& study, const BindingConstraint& rhs, bool emptyBefore, - Yuni::Bind& translate); + const std::function& translate); /*! ** \brief Get how many links the binding constraint contains @@ -374,14 +377,15 @@ class BindingConstraint final : public Yuni::NonCopyable BindingConstraintStructures initLinkArrays() const; template - std::string timeSeriesFileName(const Env &env) const; + std::string timeSeriesFileName(const Env& env) const; private: //! Raw name ConstraintName pName; //! Raw ID ConstraintName pID; - //! Time series of the binding constraint. Width = number of series. Height = nbTimeSteps. Only store series for operatorType + //! Time series of the binding constraint. Width = number of series. Height = nbTimeSteps. Only + //! store series for operatorType Matrix<> RHSTimeSeries_; //! Weights for links linkWeightMap pLinkWeights; @@ -406,11 +410,11 @@ class BindingConstraint final : public Yuni::NonCopyable //! Comments YString pComments; //! Group - std::string group_; + std::string group_ = "default"; void clear(); - void copyFrom(BindingConstraint const *original); + void copyFrom(const BindingConstraint* original); }; // class BindingConstraint @@ -418,7 +422,8 @@ class BindingConstraint final : public Yuni::NonCopyable struct CompareBindingConstraintName final { - bool operator()(const std::shared_ptr& s1, const std::shared_ptr& s2) const + bool operator()(const std::shared_ptr& s1, + const std::shared_ptr& s2) const { return s1->name() < s2->name(); } diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraint.hxx b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraint.hxx new file mode 100644 index 0000000000..7df3b79054 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraint.hxx @@ -0,0 +1,128 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +namespace Antares::Data +{ +inline const ConstraintName& BindingConstraint::name() const +{ + return pName; +} + +inline const ConstraintName& BindingConstraint::id() const +{ + return pID; +} + +inline const YString& BindingConstraint::comments() const +{ + return pComments; +} + +inline void BindingConstraint::comments(const AnyString& newcomments) +{ + pComments = newcomments; +} + +inline uint BindingConstraint::linkCount() const +{ + return (uint)pLinkWeights.size(); +} + +inline uint BindingConstraint::clusterCount() const +{ + return (uint)pClusterWeights.size(); +} + +inline bool BindingConstraint::enabled() const +{ + return pEnabled; +} + +inline BindingConstraint::Operator BindingConstraint::operatorType() const +{ + return pOperator; +} + +inline BindingConstraint::Type BindingConstraint::type() const +{ + return pType; +} + +inline void BindingConstraint::setTimeGranularity(Type t) +{ + if (t != typeUnknown and t != typeMax) + { + pType = t; + } +} + +inline bool BindingConstraint::skipped() const +{ + return linkCount() == 0 && clusterCount() == 0; +} + +inline bool BindingConstraint::isActive() const +{ + return enabled() && !skipped(); +} + +inline BindingConstraint::iterator BindingConstraint::begin() +{ + return pLinkWeights.begin(); +} + +inline BindingConstraint::iterator BindingConstraint::end() +{ + return pLinkWeights.end(); +} + +inline BindingConstraint::const_iterator BindingConstraint::begin() const +{ + return pLinkWeights.begin(); +} + +inline BindingConstraint::const_iterator BindingConstraint::end() const +{ + return pLinkWeights.end(); +} + +template +inline std::string BindingConstraint::timeSeriesFileName(const Env& env) const +{ + switch (operatorType()) + { + case BindingConstraint::opLess: + return std::string() + env.folder.c_str() + Yuni::IO::Separator + id().c_str() + "_lt" + + ".txt"; + case BindingConstraint::opGreater: + return std::string() + env.folder.c_str() + Yuni::IO::Separator + id().c_str() + "_gt" + + ".txt"; + case BindingConstraint::opEquality: + return std::string() + env.folder.c_str() + Yuni::IO::Separator + id().c_str() + "_eq" + + ".txt"; + default: + logs.error("Cannot load/save time series of type other that eq/gt/lt"); + return ""; + } +} + +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintGroup.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintGroup.h new file mode 100644 index 0000000000..64f5ae8bb0 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintGroup.h @@ -0,0 +1,58 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 28/06/23. +// + +#pragma once + +#include + +#include "BindingConstraint.h" + +namespace Antares::Data +{ + +class BindingConstraintGroup +{ +public: + explicit BindingConstraintGroup(std::string name); + + [[nodiscard]] std::string name() + { + return name_; + } + + void add(const std::shared_ptr& constraint); + [[nodiscard]] std::set> constraints() const; + [[nodiscard]] unsigned numberOfTimeseries() const; + +public: + // Public data members + TimeSeriesNumbers timeseriesNumbers; + +private: + std::set> constraints_; + std::string name_; +}; + +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintGroupRepository.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintGroupRepository.h new file mode 100644 index 0000000000..b8eb6ee803 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintGroupRepository.h @@ -0,0 +1,69 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 28/06/23. +// + +#pragma once + +#include +#include +#include + +#include "antares/study/binding_constraint/BindingConstraintGroup.h" +#include "antares/study/fwd.h" + +#include "BindingConstraint.h" +#include "BindingConstraintSaver.h" + +namespace Antares::Data +{ + +class BindingConstraintGroupRepository +{ +public: + [[nodiscard]] unsigned size() const; + + [[nodiscard]] bool buildFrom(const BindingConstraintsRepository& repository); + + void resizeAllTimeseriesNumbers(unsigned nb_years); + + BindingConstraintGroup* operator[](const std::string& name) const; + + using iterator = std::vector>::iterator; + using const_iterator = std::vector>::const_iterator; + + [[nodiscard]] iterator begin(); + [[nodiscard]] const_iterator begin() const; + + [[nodiscard]] iterator end(); + [[nodiscard]] const_iterator end() const; + + BindingConstraintGroup* add(const std::string& name); + void clear(); + +private: + [[nodiscard]] bool timeSeriesWidthConsistentInGroups() const; + + std::vector> groups_; +}; + +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintLoader.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintLoader.h new file mode 100644 index 0000000000..8e8003bcf9 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintLoader.h @@ -0,0 +1,59 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 11/05/23. +// + +#pragma once + +#include + +#include "antares/study/area/area.h" + +#include "BindingConstraint.h" +#include "EnvForLoading.h" + +namespace Antares::Data +{ + +class BindingConstraint; + +class BindingConstraintLoader +{ +public: + std::vector> load(EnvForLoading env); + +private: + static bool SeparateValue(const EnvForLoading& env, + const IniFile::Property* p, + double& w, + int& o); + + bool loadTimeSeries(EnvForLoading& env, BindingConstraint* bindingConstraint); + bool loadTimeSeriesLegacyStudies(EnvForLoading& env, + BindingConstraint* bindingConstraint) const; + bool loadTimeSeries(EnvForLoading& env, + BindingConstraint::Operator operatorType, + BindingConstraint* bindingConstraint) const; +}; + +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintSaver.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintSaver.h new file mode 100644 index 0000000000..105020baed --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintSaver.h @@ -0,0 +1,57 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 16/05/23. +// + +#pragma once + +#include +#include "antares/study/fwd.h" + +namespace Antares::Data +{ +class BindingConstraintSaver +{ +public: + class EnvForSaving final + { + public: + EnvForSaving() = default; + + //! Current section + IniFile::Section* section = nullptr; + + Yuni::Clob folder; + Yuni::Clob matrixFilename; + Yuni::CString<2 * (ant_k_area_name_max_length + 8), false> key; + }; + + /*! + ** \brief Save the binding constraint into a folder and an INI file + ** + ** \param env All information needed to perform the task + ** \return True if the operation succeeded, false otherwise + */ + static bool saveToEnv(EnvForSaving& env, const BindingConstraint* bindingConstraint); +}; +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintStructures.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintStructures.h new file mode 100644 index 0000000000..dceccbb2b8 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintStructures.h @@ -0,0 +1,47 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 27/06/23. +// + +#pragma once + +#include + +namespace Antares +{ +namespace Data +{ + +struct BindingConstraintStructures +{ + mutable std::vector linkIndex; + mutable std::vector linkWeight; + mutable std::vector clusterWeight; + mutable std::vector linkOffset; + mutable std::vector clusterOffset; + mutable std::vector clusterIndex; + mutable std::vector clustersAreaIndex; +}; + +} // namespace Data +} // namespace Antares diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintsRepository.h b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintsRepository.h new file mode 100644 index 0000000000..25809de754 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintsRepository.h @@ -0,0 +1,208 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 11/05/23. +// + +#pragma once + +#include +#include + +#include "BindingConstraint.h" +#include "BindingConstraintSaver.h" + +namespace Antares::Data +{ +class BindingConstraintsRepository final: public Yuni::NonCopyable +{ +public: + //! Vector of binding constraints + using Vector = std::vector>; + //! Ordered Set of binding constraints + using Set = std::set, CompareBindingConstraintName>; + + using iterator = Vector::iterator; + using const_iterator = Vector::const_iterator; + + //! \name Constructor && Destructor + //@{ + /*! + ** \brief Default constructor + */ + BindingConstraintsRepository() = default; + /*! + ** \brief Destructor + */ + ~BindingConstraintsRepository() = default; + //@} + + /*! + ** \brief Delete all constraints + */ + void clear(); + + //! \name Iterating through all constraints + //@{ + /*! + ** \brief Iterate through all constraints + */ + template + void each(const PredicateT& predicate); + /*! + ** \brief Iterate through all constraints (const) + */ + template + void each(const PredicateT& predicate) const; + + iterator begin(); + [[nodiscard]] const_iterator begin() const; + + iterator end(); + [[nodiscard]] const_iterator end() const; + + [[nodiscard]] bool empty() const; + //@} + + /*! + ** \brief Add a new binding constraint + */ + std::shared_ptr add(const AnyString& name); + + /*! + ** Try to find a constraint from its id + */ + std::shared_ptr find(const AnyString& id); + + /*! + ** \brief Try to find a constraint from its id (const) + */ + [[nodiscard]] std::shared_ptr find(const AnyString& id) const; + + /*! + ** \brief Try to find a constraint from its name + */ + [[nodiscard]] Data::BindingConstraint* findByName(const AnyString& name); + + /*! + ** \brief Try to find a constraint from its name (const) + */ + [[nodiscard]] const Data::BindingConstraint* findByName(const AnyString& name) const; + + /*! + ** \brief Load all binding constraints from a folder + */ + [[nodiscard]] bool loadFromFolder(Data::Study& s, + const Data::StudyLoadOptions& options, + const AnyString& folder); + + /*! + ** \brief Save all binding constraints into a folder + */ + [[nodiscard]] bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Reverse the sign of the weight for a given interconnection or thermal cluster + ** + ** This method is used when reverting an interconnection or thermal cluster + */ + void reverseWeightSign(const Data::AreaLink* lnk); + + //! Get the number of binding constraints + [[nodiscard]] uint size() const; + + /*! + ** \brief Remove a binding constraint + */ + void remove(const Data::BindingConstraint* bc); + /*! + ** \brief Remove any binding constraint linked with a given area + */ + void remove(const Data::Area* area); + /*! + ** \brief Remove any binding constraint linked with a given interconnection + */ + void remove(const Data::AreaLink* area); + + /*! + ** \brief Remove any binding constraint whose name contains the string in argument + */ + void removeConstraintsWhoseNameConstains(const AnyString& filter); + + /*! + ** \brief Rename a binding constraint + */ + bool rename(Data::BindingConstraint* bc, const AnyString& newname); + + /*! + ** \brief Convert all weekly constraints into daily ones + */ + void changeConstraintsWeeklyToDaily(); + + /*! + ** \brief Get the memory usage + */ + [[nodiscard]] uint64_t memoryUsage() const; + + /*! + ** \brief Invalidate all matrices of all binding constraints + */ + void forceReload(bool reload = false) const; + + /*! + ** \brief Mark the constraint as modified + */ + void markAsModified() const; + + static std::vector> LoadBindingConstraint(EnvForLoading env); + + [[nodiscard]] std::vector> activeConstraints() const; + + [[nodiscard]] Vector getPtrForInequalityBindingConstraints() const; + +private: + bool internalSaveToFolder(Data::BindingConstraintSaver::EnvForSaving& env) const; + + //! All constraints + Data::BindingConstraintsRepository::Vector constraints_; + + mutable std::vector> activeConstraints_; +}; + +struct WhoseNameContains final +{ +public: + explicit WhoseNameContains(AnyString filter): + pFilter(std::move(filter)) + { + } + + bool operator()(const std::shared_ptr& s) const + { + return (s->name()).contains(pFilter); + } + +private: + AnyString pFilter; +}; +} // namespace Antares::Data + +#include "BindingConstraintsRepository.hxx" diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintsRepository.hxx b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintsRepository.hxx new file mode 100644 index 0000000000..f8c1ad545e --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/BindingConstraintsRepository.hxx @@ -0,0 +1,60 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 11/05/23. +// + +#pragma once + +#include + +namespace Antares::Data +{ + +inline uint BindingConstraintsRepository::size() const +{ + return (uint)constraints_.size(); +} + +inline bool BindingConstraintsRepository::empty() const +{ + return constraints_.empty(); +} + +template +inline void BindingConstraintsRepository::each(const PredicateT& predicate) +{ + for (auto bc: constraints_) + { + predicate(*bc); + } +} + +template +inline void BindingConstraintsRepository::each(const PredicateT& predicate) const +{ + for (auto bc: constraints_) + { + predicate(*bc); + } +} +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/binding_constraint/EnvForLoading.h b/src/libs/antares/study/include/antares/study/binding_constraint/EnvForLoading.h new file mode 100644 index 0000000000..9220f0c1f3 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/binding_constraint/EnvForLoading.h @@ -0,0 +1,59 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "yuni/core/fwd.h" + +#include +#include +#include + +namespace Antares::Data +{ + +class AreaList; + +class EnvForLoading final +{ +public: + explicit EnvForLoading(AreaList& l, const StudyVersion& v): + areaList(l), + version(v) + { + } + + //! INI file + Yuni::Clob iniFilename; + //! Current section + IniFile::Section* section; + + Yuni::Clob buffer; + Matrix<>::BufferType matrixBuffer; + Yuni::Clob folder; + + //! List of areas + AreaList& areaList; + + StudyVersion version; +}; + +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/cleaner.h b/src/libs/antares/study/include/antares/study/cleaner.h new file mode 100644 index 0000000000..1ea5fcac72 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/cleaner.h @@ -0,0 +1,101 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_CLEANER_H__ +#define __ANTARES_LIBS_STUDY_CLEANER_H__ + +#include +#include +#include + +#include + +#include "version.h" + +namespace Antares::Data +{ +class StudyCleaningInfos final +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + StudyCleaningInfos(); + /*! + ** \brief Constructor with a given path + */ + explicit StudyCleaningInfos(const AnyString& path); + /*! + ** \brief Destructor + */ + ~StudyCleaningInfos(); + //@} + + /*! + ** \brief Determine the complete list of all files/folder considered as intruders + */ + bool analyze(); + + /*! + ** \brief Perform a complete cleanup + */ + void performCleanup(); + + /*! + ** \brief Get the total size occupied by the intruders + */ + uint64_t totalSize() const; + + /*! + ** \brief Set an additional list of excluded files or directories. + */ + void setCustomExcludeList(const Yuni::String& c); + +public: + /*! A study folder */ + Yuni::String folder; + + /*! Version of the study */ + StudyVersion version; + /*! List of all intruders */ + ::PathList intruders; + /*! List of all files/folders to prevent from the destruction */ + ::PathList exclude; + /*! Colon-separated list of all files/folders to prevent from the destruction */ + Yuni::String customExclude; + + /*! List of all files/folders to exclude after analyzing the content of the folder */ + /* This list mainly ensures that a list of folders will not deleted enven if empty */ + ::PathList postExclude; + + /*! + ** \brief Event triggered when entering into a new folder + ** + ** Return false to stop the process + */ + std::function onProgress; + +}; // class StudyCleaningInfos + +} // namespace Antares::Data + +#endif /* __ANTARES_LIBS_STUDY_CLEANER_H__ */ diff --git a/src/libs/antares/study/include/antares/study/cleaner/versions.h b/src/libs/antares/study/include/antares/study/cleaner/versions.h new file mode 100644 index 0000000000..d1f316c130 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/cleaner/versions.h @@ -0,0 +1,33 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_CLEANER_VERSION_H__ +#define __ANTARES_LIBS_STUDY_CLEANER_VERSION_H__ + +namespace Antares +{ +namespace Data +{ +bool listOfFilesAnDirectoriesToKeep(StudyCleaningInfos* infos); + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_CLEANER_VERSION_H__ diff --git a/src/libs/antares/study/include/antares/study/constraint.h b/src/libs/antares/study/include/antares/study/constraint.h new file mode 100644 index 0000000000..16656697a4 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/constraint.h @@ -0,0 +1,26 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_CONSTRAINT_H__ +#define __ANTARES_LIBS_STUDY_CONSTRAINT_H__ + +#include "binding_constraint/BindingConstraint.h" + +#endif // __ANTARES_LIBS_STUDY_CONSTRAINT_H__ diff --git a/src/libs/antares/study/include/antares/study/correlation-updater.hxx b/src/libs/antares/study/include/antares/study/correlation-updater.hxx new file mode 100644 index 0000000000..0a5e617d11 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/correlation-updater.hxx @@ -0,0 +1,84 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_CORRELATION_UPDATER_HXX__ +#define __ANTARES_LIBS_STUDY_CORRELATION_UPDATER_HXX__ + +#include + +#define SEP IO::Separator + +namespace Antares +{ +namespace // anonymous +{ +class CorrelationUpdater final +{ +public: + CorrelationUpdater(Data::Study& study): + pStudy(study) + { + using namespace Yuni; + // We can store the INI files in disk because it may not fit in memory + pTempFile << memory.cacheFolder() << SEP << "antares-corr-save-" << memory.processID() + << '-' << (void*)(this) << '-'; + + pS.clear() << pTempFile << "load.tmp"; + study.preproLoadCorrelation.saveToFile(study, pS); + pS.clear() << pTempFile << "solar.tmp"; + study.preproSolarCorrelation.saveToFile(study, pS); + pS.clear() << pTempFile << "wind.tmp"; + study.preproWindCorrelation.saveToFile(study, pS); + pS.clear() << pTempFile << "hydro.tmp"; + study.preproHydroCorrelation.saveToFile(study, pS); + } + + ~CorrelationUpdater() + { + using namespace Yuni; + pS.clear() << pTempFile << "load.tmp"; + pStudy.preproLoadCorrelation.loadFromFile(pStudy, pS, false); + IO::File::Delete(pS); + + pS.clear() << pTempFile << "solar.tmp"; + pStudy.preproSolarCorrelation.loadFromFile(pStudy, pS, false); + IO::File::Delete(pS); + + pS.clear() << pTempFile << "wind.tmp"; + pStudy.preproWindCorrelation.loadFromFile(pStudy, pS, false); + IO::File::Delete(pS); + + pS.clear() << pTempFile << "hydro.tmp"; + pStudy.preproHydroCorrelation.loadFromFile(pStudy, pS, false); + IO::File::Delete(pS); + } + +private: + Data::Study& pStudy; + Yuni::Clob pTempFile; + Yuni::Clob pS; + +}; // class CorrelationUpdater + +} // anonymous namespace + +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_CORRELATION_UPDATER_HXX__ diff --git a/src/libs/antares/study/include/antares/study/filter.h b/src/libs/antares/study/include/antares/study/filter.h new file mode 100644 index 0000000000..6b8cbd1c5f --- /dev/null +++ b/src/libs/antares/study/include/antares/study/filter.h @@ -0,0 +1,60 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIB_STUDY_FILTER_H__ +#define __ANTARES_LIB_STUDY_FILTER_H__ + +#include + +#include +#include + +namespace Antares +{ +namespace Data +{ +enum FilterFlag +{ + filterNone = 0, + filterHourly = 1, + filterDaily = 2, + filterWeekly = 4, + filterMonthly = 8, + filterAnnual = 16, + filterAll = (uint)-1, +}; + +// Convert a date precision filter into a string (obtained by concatenating filter components) +std::string datePrecisionIntoString(uint datePrecisionFilter); + +/*! +** \brief Convert a string into date precision filter flags +*/ +uint stringIntoDatePrecision(const AnyString& string); + +/*! +** \brief Convert a filter indices into filter flags +*/ +uint addTimeIntervallToDatePrecisionFilter(const uint index); + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIB_STUDY_FILTER_H__ diff --git a/src/libs/antares/study/include/antares/study/finder.h b/src/libs/antares/study/include/antares/study/finder.h new file mode 100644 index 0000000000..f1acd83259 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/finder.h @@ -0,0 +1,26 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIB_FINDER_H__ +#define __ANTARES_LIB_FINDER_H__ + +#include "finder/finder.h" + +#endif // __ANTARES_LIB_FINDER_H__ diff --git a/src/libs/antares/study/include/antares/study/finder/finder.h b/src/libs/antares/study/include/antares/study/finder/finder.h new file mode 100644 index 0000000000..660a2da28a --- /dev/null +++ b/src/libs/antares/study/include/antares/study/finder/finder.h @@ -0,0 +1,141 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIB_FINDER_FINDER_H__ +#define __ANTARES_LIB_FINDER_FINDER_H__ + +#include + +#include +#include +#include + +#include "antares/study/study.h" + +#include "../version.h" + +namespace Antares +{ +namespace Data +{ +/*! +** \brief Look for study folders asynchronously +*/ +class StudyFinder +{ +public: + enum + { + //! The default value for the timeout + defaultTimeout = 10000, // 10s + }; + + //! List of folders + using FolderVector = std::vector; + +public: + //! \name Constructor + //@{ + /*! + ** \brief Default Constructor + */ + StudyFinder(); + //! Copy constructor + StudyFinder(const StudyFinder&); + /*! + ** \brief Destructor + */ + virtual ~StudyFinder(); + //@} + + /*! + ** \brief Start a new lookup from a single folder + ** + ** If a lookup was already in progress, it will be stopped before. + ** \param folder The root folder where to start the lookup + */ + void lookup(const Yuni::String& folder); + + /*! + ** \brief Start a new lookup from a list of folder + ** + ** If a lookup was already in progress, it will be stopped before. + ** \param folders The list of folders where to start the lookup + */ + void lookup(const Yuni::String::Vector& folders); + /*! + ** \brief Start a new lookup from a list of folder + ** + ** If a lookup was already in progress, it will be stopped before. + ** \param folders The list of folders where to start the lookup + */ + void lookup(const Yuni::String::List& folders); + + /*! + ** \brief Stop a lookup currently in progress + */ + void stop(uint timeout = defaultTimeout); + + /*! + ** \brief Wait Indefinitely for the end of the lookup + */ + void wait(); + + /*! + ** \brief Wait for the end of the lookup (with timeout) + */ + void wait(uint timeout); + +public: // Events + /*! + ** \brief Event triggered when a lookup has been found + */ + virtual void onStudyFound(const Yuni::String& folder, const StudyVersion& version) = 0; + + /*! + ** \brief Event triggered when a lookup has finished gracefully + ** + ** This event might be called from any thread. + */ + virtual void onLookupFinished() + { + } + + /*! + ** \brief Event triggered when a lookup has been aborted + ** + ** This event might be called from any thread. + */ + virtual void onLookupAborted() + { + } + +protected: + std::mutex mutex; + +private: + Yuni::IO::Directory::IIterator* pLycos; + +}; // class StudyFinder + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIB_FINDER_FINDER_H__ diff --git a/src/libs/antares/study/include/antares/study/fwd.h b/src/libs/antares/study/include/antares/study/fwd.h new file mode 100644 index 0000000000..6fa2819aca --- /dev/null +++ b/src/libs/antares/study/include/antares/study/fwd.h @@ -0,0 +1,547 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_FWD_H__ +#define __ANTARES_LIBS_STUDY_FWD_H__ + +#include + +#include +#include + +#include "antares/antares/antares.h" +#include "antares/antares/constants.h" + +namespace Antares +{ +class IniFile; + +namespace Data +{ +// Forward declarations +class Study; +class StudyLoadOptions; +class Area; +class AreaLink; +class AreaList; +class AreaUI; +class ThermalCluster; +class RenewableCluster; + +class AreaScratchpad; + +class Parameters; + +class BindingConstraint; +class BindingConstraintsRepository; + +class StudyRuntimeInfos; + +class UIRuntimeInfo; + +class Correlation; + +//! Name of a single area +using AreaName = Yuni::CString; +//! Name of a single link +using AreaLinkName = Yuni::CString; +//! Name of a single thermal +using ClusterName = std::string; + +using ConstraintName = Yuni::CString; + +using RulesScenarioName = Yuni::CString<64, false>; + +//! Name mapping +using AreaNameMapping = std::map; + +/*! +** \brief Study's Consistency errors +*/ +enum StudyError +{ + stErrNone = 0, + //! startTime, finalHour = 0..8760 + stErrHourOutOfBounds = 1, + //! The final hour must be a multiple of 168 + stErrFinalHourMustBeAMultipleOf168, + //! A given day of the week is invalid + stErrInvalidDayOfWeek, + //! Too much areas (>300) + stErrTooMuchAreas, + //! Too much interconnections (>5000) + stErrTooMuchInterconnections, + //! Too much binding constaints + stErrTooMuchBindingConstraints, + /**/ +}; + +/*! +** \brief Types of Simulation +*/ +enum class SimulationMode +{ + //! Economic + Economy, + //! Adequacy (subset of the economy mode) + Adequacy, + //! Expansion + Expansion, + //! Unknown simulation mode + Unknown +}; + +/* +** \brief Simplex optimizations +*/ +enum SimplexOptimization +{ + sorUnknown = 0, + sorDay, + sorWeek, + +}; // enum SimplexOptimization + +/*! +** \brief Transmission capacities mode (applies to all links) +*/ +enum class GlobalTransmissionCapacities +{ + //! Transmission capacities are enabled + localValuesForAllLinks = 0, + //! Transmission capacities are ignored (set to null) + nullForAllLinks, + //! Transmission capacities are infinite (aka Copper Plate) + infiniteForAllLinks, + //! Transmission capacities are ignored only for physical links + //! Global property only, cannot be used for individual links + nullForPhysicalLinks, + //! Transmission capacities are infinite only for physical links (not virtual) + //! Global property only, cannot be used for individual links + infiniteForPhysicalLinks +}; // enum TransmissionCapacities + +std::string GlobalTransmissionCapacitiesToString( + GlobalTransmissionCapacities transmissionCapacities); +std::string GlobalTransmissionCapacitiesToString_Display( + GlobalTransmissionCapacities transmissionCapacities); +bool stringToGlobalTransmissionCapacities(const AnyString& value, + GlobalTransmissionCapacities& out); + +/*! +** \brief Transmission capacities mode (applies to individual links) +*/ +enum class LocalTransmissionCapacities +{ + enabled, + null, + infinite +}; + +std::string transmissionCapacitiesToString(const LocalTransmissionCapacities& tc); + +/*! +** \brief Asset Type mode +*/ +enum AssetType +{ + //! Asset Type AC + atAC = 0, + //! Asset Type DC + atDC, + //! Asset Type gas + atGas, + //! Asset Type virtual + atVirt, + //! Asset Type Other (gas, etc) + atOther, + +}; // enum AssetType + +std::string assetTypeToString(const AssetType& assetType); + +/*! +** \brief Style Type mode +*/ +enum StyleType +{ + //! Style Type plain + stPlain = 0, + //! Style Type dot + stDot, + //! Style Type dash + stDash, + //! Style Type dot & dash + stDotDash, + +}; // enum StyleType + +std::string styleToString(const StyleType& style); + +/*! +** \brief Types of timeSeries +** +** These values are mainly used for mask bits +*/ +static const unsigned int timeSeriesCount = 7; + +enum TimeSeriesType : unsigned int +{ + //! TimeSeries : Load + timeSeriesLoad = 1, + //! TimeSeries : Hydro + timeSeriesHydro = 2, + //! TimeSeries : Wind + timeSeriesWind = 4, + //! TimeSeries : Thermal + timeSeriesThermal = 8, + //! TimeSeries : Solar + timeSeriesSolar = 16, + //! TimeSeries : Renewable + timeSeriesRenewable = 32, + //! TimeSeries : Renewable + timeSeriesTransmissionCapacities = 64, + // *********************************************************************** + // Please update the constant timeSeriesCount if you add / remove an item + // *********************************************************************** +}; // enum TimeSeries + +template +struct TimeSeriesBitPatternIntoIndex; + +template<> +struct TimeSeriesBitPatternIntoIndex<1> +{ + enum + { + value = 0 + }; +}; + +template<> +struct TimeSeriesBitPatternIntoIndex<2> +{ + enum + { + value = 1 + }; +}; + +template<> +struct TimeSeriesBitPatternIntoIndex<4> +{ + enum + { + value = 2 + }; +}; + +template<> +struct TimeSeriesBitPatternIntoIndex<8> +{ + enum + { + value = 3 + }; +}; + +template<> +struct TimeSeriesBitPatternIntoIndex<16> +{ + enum + { + value = 4 + }; +}; + +template<> +struct TimeSeriesBitPatternIntoIndex<32> +{ + enum + { + value = 5 + }; +}; + +template +struct TimeSeriesToCStr; + +template<> +struct TimeSeriesToCStr<1> +{ + static const char* Value() + { + return "load"; + } +}; + +template<> +struct TimeSeriesToCStr<2> +{ + static const char* Value() + { + return "hydro"; + } +}; + +template<> +struct TimeSeriesToCStr<4> +{ + static const char* Value() + { + return "wind"; + } +}; + +template<> +struct TimeSeriesToCStr<8> +{ + static const char* Value() + { + return "thermal"; + } +}; + +template<> +struct TimeSeriesToCStr<16> +{ + static const char* Value() + { + return "solar"; + } +}; + +template<> +struct TimeSeriesToCStr<32> +{ + static const char* Value() + { + return "renewable"; + } +}; + +enum SeedIndex +{ + //! The seed for wind + seedTsGenWind = 0, + //! The seed for load + seedTsGenLoad, + //! The seed for hydro + seedTsGenHydro, + //! The seed for thermal + seedTsGenThermal, + //! The seed for solar + seedTsGenSolar, + //! The seed used for time-series numbers + seedTimeseriesNumbers, + //! Seed - unsupplied energy costs + seedUnsuppliedEnergyCosts, + //! Seed - Spilled energy costs + seedSpilledEnergyCosts, + //! Seed - thermal costs + seedThermalCosts, + //! Seed - Hydro costs + seedHydroCosts, + //! Seed - Hydro management + seedHydroManagement, + //! The number of seeds + seedMax, +}; + +//! A default seed for random number generators +constexpr unsigned antaresSeedDefaultValue = 5489; +//! Increment for RNG (generators) with a different seed +constexpr unsigned antaresSeedIncrement = 1000000; // arbitrary value + +/*! +** \brief Convert a seed into a string +*/ +const char* SeedToCString(SeedIndex seed); + +/*! +** \brief Seed to CString ID +** +** Mainly used for saving / loading into generaldata.ini +*/ +const char* SeedToID(SeedIndex seed); + +// ... Hydro heuristic policy ... +enum HydroHeuristicPolicy +{ + hhpAccommodateRuleCurves = 0, + hhpMaximizeGeneration, + hhpUnknown, +}; + +HydroHeuristicPolicy StringToHydroHeuristicPolicy(const AnyString& text); + +const char* HydroHeuristicPolicyToCString(HydroHeuristicPolicy hhPolicy); + +// ... Hydro Pricing ... +enum HydroPricingMode +{ + hpHeuristic = 0, + hpMILP, // mixed integer linear problem + hpUnknown, +}; + +/*! +** \brief Convert a hyfro pricing mode into a text +*/ +const char* HydroPricingModeToCString(HydroPricingMode hpm); + +/*! +** \brief Convert a text into a hydro pricing mode +*/ +HydroPricingMode StringToHydroPricingMode(const AnyString& text); + +// ... Power fluctuations ... +enum PowerFluctuations +{ + lssFreeModulations = 0, + lssMinimizeRamping, + lssMinimizeExcursions, + lssUnknown, +}; + +/*! +** \brief Convert a local shedding strategy into a text +*/ +const char* PowerFluctuationsToCString(PowerFluctuations fluctuations); + +/*! +** \brief Convert a text into a local shedding strategy +*/ +PowerFluctuations StringToPowerFluctuations(const AnyString& text); + +enum SheddingPolicy +{ + shpShavePeaks = 0, + shpMinimizeDuration, + shpUnknown, +}; + +/*! +** \brief Convert a global shedding policy into a text +*/ +const char* SheddingPolicyToCString(SheddingPolicy strategy); + +/*! +** \brief Convert a text into a global shedding policy +*/ +SheddingPolicy StringToSheddingPolicy(const AnyString& text); + +enum UnitCommitmentMode +{ + //! Heuristic in which 2 LP problems are solved + //! No explicit modelling for the number of ON/OFF units + ucHeuristicFast = 0, + //! Heuristic in which 2 LP problems are solved + //! Explicit modelling for the number of ON/OFF units + ucHeuristicAccurate, + //! A single MILP problem is solved, with explicit modelling + //! for the number of ON/OFF units + ucMILP, + //! Unknown mode, mainly used for error handling + ucUnknown, +}; + +/*! +** \brief Convert a unit commitment mode into a text +*/ +const char* UnitCommitmentModeToCString(UnitCommitmentMode ucommitment); + +/*! +** \brief Convert a text into a unit commitment mode +*/ +UnitCommitmentMode StringToUnitCommitmentMode(const AnyString& text); + +enum NumberOfCoresMode +{ + ncMin = 0, + ncLow, + ncAvg, + ncHigh, + ncMax, + ncUnknown +}; + +/*! +** \brief Convert a numbers of cores mode into a text +*/ +const char* NumberOfCoresModeToCString(NumberOfCoresMode ncores); + +/*! +** \brief Convert a text into a nb of cores mode +*/ +NumberOfCoresMode StringToNumberOfCoresMode(const AnyString& text); + +/* + * Renewable generation modelling + */ +enum RenewableGenerationModelling +{ + rgAggregated = 0, // Default + rgClusters, // Using renewable clusters + rgUnknown, +}; + +/*! +** \brief Convert a renewable generation modelling into a text +*/ +const char* RenewableGenerationModellingToCString(RenewableGenerationModelling rgModelling); + +/*! +** \brief Convert a text into a renewable generation modelling +*/ +RenewableGenerationModelling StringToRenewableGenerationModelling(const AnyString& text); + +// ------------------------ +// MPS export status +// ------------------------ +enum class mpsExportStatus : int +{ + NO_EXPORT = 0, + EXPORT_FIRST_OPTIM = 1, + EXPORT_SECOND_OPTIM = 2, + EXPORT_BOTH_OPTIMS = 3, + UNKNOWN_EXPORT = 4 +}; + +std::string mpsExportStatusToString(const mpsExportStatus& mps_export_status); +mpsExportStatus stringToMPSexportStatus(const AnyString& value); + +} // namespace Data +} // namespace Antares + +namespace Antares::Data::ScenarioBuilder +{ +class Rules; +class TSNumberRules; +class Sets; + +} // namespace Antares::Data::ScenarioBuilder + +namespace Benchmarking +{ +class DurationCollector; +} + +#endif // __ANTARES_LIBS_STUDY_FWD_H__ diff --git a/src/libs/antares/study/include/antares/study/header.h b/src/libs/antares/study/include/antares/study/header.h new file mode 100644 index 0000000000..aea7e0f35c --- /dev/null +++ b/src/libs/antares/study/include/antares/study/header.h @@ -0,0 +1,139 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_HEADER_H__ +#define __ANTARES_LIBS_STUDY_HEADER_H__ + +#include +#include + +#include +#include + +#include + +#include "version.h" + +//! Default author +#define STUDYHEADER_DEFAULT_AUTHOR "Unknown" +//! Default caption +#define STUDYHEADER_DEFAULT_CAPTION "No title" + +namespace Antares +{ +namespace Data +{ +/*! +** \brief Header of a study +** \ingroup study +*/ +class StudyHeader final +{ +public: + /*! + ** \brief Get the version of a header + ** + ** \param filename The filename to read + ** \return The version of the study, or 0 if unknown (invalid header) + */ + static bool readVersionFromFile(const std::filesystem::path& filename, std::string& version); + + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + StudyHeader() + { + reset(); + } + + /*! + ** \brief Destructor + */ + ~StudyHeader() = default; + //@} + + /*! + ** \brief Reset the values + */ + void reset(); + + /*! + ** \brief Load a study header from a file + ** + ** \param filename The target filename + ** \param warnings Enable warnings/errors + ** \return True if the operation succeeded, false otherwise + */ + bool loadFromFile(const AnyString& filename, bool warnings = true); + + /*! + ** \brief Save a study header into a file + ** + ** The property `version` will be upgraded to the last available + ** and `dateLastSave` as well. + ** + ** \param filename The target filename + ** \return True if the operation succeeded, false otherwise + */ + bool saveToFile(const AnyString& filename, bool upgradeVersion = true); + + //! Copy the internal settings into an INI structure + void CopySettingsToIni(IniFile& ini, bool upgradeVersion); + + /*! + ** \brief Try to determine the version of a study + ** \ingroup study + ** + ** \param folder The folder where data are located + ** \return The version of the study. `unknown` if not found + */ + static StudyVersion tryToFindTheVersion(const std::string& folder); + + bool validateVersion(); + + //! Caption of the study + Yuni::String caption; + + //! Format version + StudyVersion version; + + //! Date: Creation (timestamp) + time_t dateCreated; + //! Date: Last save (timestamp) + time_t dateLastSave; + + //! Author + Yuni::String author; + +private: + //! Load settings from an INI file + bool internalLoadFromINIFile(const IniFile& ini, bool warnings); + + //! Get the version written in an header file + static bool internalFindVersionFromFile(const IniFile& ini, std::string& version); + +}; // class StudyHeader; + +} // namespace Data +} // namespace Antares + +#endif /* __ANTARES_LIBS_STUDY_HEADER_H__ */ diff --git a/src/libs/antares/study/include/antares/study/layerdata.h b/src/libs/antares/study/include/antares/study/layerdata.h new file mode 100644 index 0000000000..f552dd00e7 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/layerdata.h @@ -0,0 +1,59 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_LAYERDATA_H__ +#define __ANTARES_LIBS_STUDY_LAYERDATA_H__ + +#include +#include + +#include + +namespace Antares::Data +{ +/*! +** \brief Antares Study +*/ + +class LayerData +{ +public: + LayerData(size_t activeLayer, bool showLayer): + activeLayerID(activeLayer), + showAllLayer(showLayer) + { + } + + //! \name Layers + //@{ + //! All available layers + std::map layers; + //@} + size_t activeLayerID; + bool showAllLayer; + +protected: + bool saveLayers(const AnyString& filename); + void loadLayers(const AnyString& filename); +}; + +} // namespace Antares::Data + +#endif /* __ANTARES_LIBS_STUDY_LAYERDATA_H__ */ diff --git a/src/libs/antares/study/include/antares/study/load-options.h b/src/libs/antares/study/include/antares/study/load-options.h new file mode 100644 index 0000000000..41eee86cbb --- /dev/null +++ b/src/libs/antares/study/include/antares/study/load-options.h @@ -0,0 +1,108 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_SOLVER_LOAD_OPTIONS_H__ +#define __ANTARES_LIBS_SOLVER_LOAD_OPTIONS_H__ + +#include +#include + +#include + +#include "parameters.h" + +namespace Antares +{ +namespace Data +{ +class StudyLoadOptions +{ +public: + //! \name Constructor + //@{ + //! Default constructor + StudyLoadOptions(); + //@} + + void checkForceSimulationMode(); + +public: + //! The number of MC years (non-zero to force the value) + uint nbYears; + //! True to prepare the output folder + bool prepareOutput; + //! True to load only the strictly required data + bool loadOnlyNeeded; + //! Force the year-by-year flag + bool forceYearByYear; + + //! Force the derated mode + bool forceDerated; + + //! No Timeseries import in the input + // This option might be useful for running old studies without upgrading + bool noTimeseriesImportIntoInput; + + //! Simplex optimization range + SimplexOptimization simplexOptimizationRange; + //! Mps files export asked + bool mpsToExport; + //! named problems + bool namedProblems = false; + //! Ignore all constraints + bool ignoreConstraints; + //! Simulation mode + SimulationMode forceMode; + + //! Enables the parallel computation of MC years + bool enableParallel; + + //! Force a maximum number of MC years computed simultaneously + bool forceParallel; + uint maxNbYearsInParallel; + + //! A non-zero value if the data will be used for a simulation + bool usedByTheSolver; + + //! All options related to optimization + Antares::Solver::Optimization::OptimizationOptions optOptions; + + //! Temporary string for passing log message + mutable Yuni::String logMessage; + + //! Display version number and exit + bool displayVersion = false; + + //! True => display the list of OR-Tools solvers and exit + bool listSolvers = false; + + //! Simulation mode + bool forceExpansion = false; + bool forceEconomy = false; + bool forceAdequacy = false; + + YString studyFolder; + YString simulationName; +}; // class StudyLoadOptions + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_SOLVER_LOAD_OPTIONS_H__ diff --git a/src/libs/antares/study/include/antares/study/output.h b/src/libs/antares/study/include/antares/study/output.h new file mode 100644 index 0000000000..38846330bd --- /dev/null +++ b/src/libs/antares/study/include/antares/study/output.h @@ -0,0 +1,108 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_OUTPUT_H__ +#define __ANTARES_LIBS_STUDY_OUTPUT_H__ + +#include +#include +#include + +#include +#include + +#include "antares/study/study.h" + +namespace Antares +{ +namespace Data +{ +class Output final +{ +public: + //! Smartptr + using Ptr = std::shared_ptr; + //! List + using List = std::list; + //! Title + using Title = Yuni::CString<128, false>; + //! Name + using Name = Yuni::CString<128, false>; + + //! Map of study output info, ordered by their timestamp + using MapByTimestamp = std::map; + //! Map of study output info, ordered by their timestamp (desc) + using MapByTimestampDesc = std::map>; + +public: + /*! + ** \brief Retrieve the list of all available outputs + */ + static void RetrieveListFromStudy(List& out, const Study& study); + +public: + //! \name Constructor + //@{ + /*! + ** \brief Constructor, with an output folder + */ + explicit Output(const AnyString& folder); + //@} + + /*! + ** \brief Load data from an output folder + */ + bool loadFromFolder(const AnyString& folder); + + //! Get if the output folder previously loaded is valid + bool valid() const; + + //! Operator < + bool operator<(const Output& rhs) const; + +public: + //! Version of the solver used for the simulation + StudyVersion version; + //! Date/time when the simulation has been launched + int64_t timestamp; + //! Mode (economy/adequacy/other) + Data::SimulationMode mode; + //! Tag for storing a wx menu id + int menuID; + //! Tag for storing a wx menu id (from the menu `output`) + int viewMenuID; + //! Tag for storing a wx menu id (for the output viewer) + int outputViewerID; + + //! Title to use for visual representation of the output + Title title; + //! Name + Name name; + //! Output folder + YString path; + +}; // class Output + +} // namespace Data +} // namespace Antares + +#include "output.hxx" + +#endif // __ANTARES_STUDY_LIBS_OUTPUT_H__ diff --git a/src/libs/antares/study/include/antares/study/output.hxx b/src/libs/antares/study/include/antares/study/output.hxx new file mode 100644 index 0000000000..cba7ae582b --- /dev/null +++ b/src/libs/antares/study/include/antares/study/output.hxx @@ -0,0 +1,35 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_OUTPUT_HXX__ +#define __ANTARES_LIBS_STUDY_OUTPUT_HXX__ + +namespace Antares +{ +namespace Data +{ +inline bool Output::operator<(const Output& rhs) const +{ + return not(title < rhs.title); +} +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_OUTPUT_HXX__ diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/include/antares/study/parameters.h similarity index 83% rename from src/libs/antares/study/parameters.h rename to src/libs/antares/study/include/antares/study/parameters.h index ffb5f1d643..1b2ce027d9 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/include/antares/study/parameters.h @@ -1,48 +1,44 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_PARAMETERS_H__ #define __ANTARES_LIBS_STUDY_PARAMETERS_H__ +#include +#include #include #include #include -#include "../constants.h" -#include -#include -#include + #include #include -#include "fwd.h" -#include "variable-print-info.h" -#include "parameters/adq-patch-params.h" - +#include #include +#include +#include "antares/antares/antares.h" +#include "antares/study/fwd.h" +#include "parameters/adq-patch-params.h" +#include "variable-print-info.h" +#include "version.h" namespace Antares::Data { @@ -54,21 +50,6 @@ namespace Antares::Data class Parameters final { public: - //! \name Constructor - //@{ - /*! - ** \brief Default Constructor - ** - ** \warning None of the variables are initialized. You must explicitly use - ** the method `reset()` or the method `loadFromFile()` - ** \see reset() - ** \see loadFromFile() - */ - Parameters(); - //! Destructor - ~Parameters(); - //@} - //! \name Simulation mode //@{ //! Get if the simulation is in economy mode @@ -91,9 +72,10 @@ class Parameters final ** be opened, the routine will return 0. ** ** \param filename The file to load + ** \param version Current study version ** \return True if the settings have been loaded, false if at least one error has occured */ - bool loadFromFile(const AnyString& filename, uint version, const StudyLoadOptions& options); + bool loadFromFile(const AnyString& filename, const StudyVersion& version); /*! ** \brief Prepare all settings for a simulation @@ -143,11 +125,18 @@ class Parameters final */ void resetAdqPatchParameters(); + /*! + ** \brief Handle priority between command-line option and configuration file + */ + void handleOptimizationOptions(const StudyLoadOptions& options); + /*! ** \brief Try to detect then fix any bad value */ void fixBadValues(); + void validateOptions(const StudyLoadOptions&); + /*! ** \brief Try to detect then fix refresh intervals */ @@ -202,17 +191,12 @@ class Parameters final //! \name Mode //@{ //! Mode of the study (adequacy, economy...) - StudyMode mode; + SimulationMode mode; //@} - //! \name Expansion - //@{ - //! Expansion flag - mutable bool expansion; - //! \name Horizon //@{ - //! Horizon year + //! Horizon year, not used by the solver Yuni::String horizon; //@} @@ -433,11 +417,16 @@ class Parameters final PowerFluctuations fluctuations; } power; - struct + struct UCMode { //! Unit Commitment Mode UnitCommitmentMode ucMode; - } unitCommitment; + + //! Some variables rely on dual values & marginal costs + void addExcludedVariables(std::vector&) const; + }; + + UCMode unitCommitment; struct { @@ -459,12 +448,6 @@ class Parameters final RenewableGeneration renewableGeneration; - struct - { - //! Initial reservoir levels - InitialReservoirLevels iniLevels; - } initialReservoirLevels; - struct { //! Hydro heuristic policy @@ -477,18 +460,12 @@ class Parameters final HydroPricingMode hpMode; } hydroPricing; - // In case of hydro hot start and MC years simultaneous run - // ... Answers the question : do all sets of simultaneous years have the same size ? - // (obvious if the parallel mode is not required : answer is yes). - bool allSetsHaveSameSize; - //! Transmission capacities GlobalTransmissionCapacities transmissionCapacities; //! Simplex optimization range (day/week) SimplexOptimization simplexOptimizationRange; //@} - AdequacyPatch::AdqPatchParams adqPatchParams; //! \name Scenariio Builder - Rules @@ -501,7 +478,7 @@ class Parameters final //@{ //! No output // This variable is not stored within the study but only used by the solver - bool noOutput; + bool noOutput = false; //@} bool hydroDebug; @@ -512,22 +489,18 @@ class Parameters final uint seed[seedMax]; //@} - //! \name Ortools configuration - //@{ - //! Define if ortools is used - bool ortoolsUsed; - //! Ortool solver used for simulation - std::string ortoolsSolver; - //@} // Format of results. Currently, only single files or zip archive are supported ResultFormat resultFormat = legacyFilesDirectories; // Naming constraints and variables in problems bool namedProblems; + // All options related to optimization + Antares::Solver::Optimization::OptimizationOptions optOptions; + private: //! Load data from an INI file - bool loadFromINI(const IniFile& ini, uint version, const StudyLoadOptions& options); + bool loadFromINI(const IniFile& ini, const StudyVersion& version); void resetPlayedYears(uint nbOfYears); @@ -537,18 +510,18 @@ class Parameters final }; // class Parameters /*! -** \brief Convert a study mode (enum) into a human readable C-String +** \brief Convert a simulation mode (enum) into a human readable C-String */ -const char* StudyModeToCString(StudyMode mode); +const char* SimulationModeToCString(SimulationMode mode); /*! -** \brief Convert a C-String (lowercase) into a study mode if possible +** \brief Convert a C-String (lowercase) into a simulation mode if possible ** -** \param[out] mode The study mode. It will remain untouched if the conversion failed +** \param[out] mode The simulation mode. It will remain untouched if the conversion failed ** \param Text An arbitrary Text (case insensitive) ** \return True if the conversion succeeded, false otherwise */ -bool StringToStudyMode(StudyMode& mode, Yuni::CString<20, false> text); +bool StringToSimulationMode(SimulationMode& mode, Yuni::CString<20, false> text); } // namespace Antares::Data diff --git a/src/libs/antares/study/parameters/adq-patch-params.h b/src/libs/antares/study/include/antares/study/parameters/adq-patch-params.h similarity index 75% rename from src/libs/antares/study/parameters/adq-patch-params.h rename to src/libs/antares/study/include/antares/study/parameters/adq-patch-params.h index 560f8f9d62..25c8b0f79b 100644 --- a/src/libs/antares/study/parameters/adq-patch-params.h +++ b/src/libs/antares/study/include/antares/study/parameters/adq-patch-params.h @@ -1,15 +1,35 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once -#include #include +#include -#include #include + #include +#include namespace Antares::Data::AdequacyPatch { - //! A default threshold value for initiate curtailment sharing rule const double defaultThresholdToRunCurtailmentSharing = 0.0; //! A default threshold value for display local matching rule violations @@ -58,7 +78,6 @@ enum class AdqPatchPTO }; // enum AdqPatchPTO - struct LocalMatching { bool enabled = true; @@ -71,12 +90,11 @@ struct LocalMatching //! rule. bool setToZeroOutsideOutsideLinks = true; /*! - ** \brief Reset to default values related to local matching - */ + ** \brief Reset to default values related to local matching + */ void reset(); bool updateFromKeyValue(const Yuni::String& key, const Yuni::String& value); void addProperties(IniFile::Section* section) const; - }; class CurtailmentSharing @@ -95,6 +113,8 @@ class CurtailmentSharing //! Check CSR cost function prior & after CSR optimization bool checkCsrCostFunction; + bool recomputeDTGMRG = false; + bool updateFromKeyValue(const Yuni::String& key, const Yuni::String& value); void addProperties(IniFile::Section* section) const; @@ -104,10 +124,8 @@ class CurtailmentSharing void resetThresholds(); }; - struct AdqPatchParams { - bool enabled; LocalMatching localMatching; CurtailmentSharing curtailmentSharing; @@ -116,15 +134,13 @@ struct AdqPatchParams void addExcludedVariables(std::vector&) const; bool updateFromKeyValue(const Yuni::String& key, const Yuni::String& value); void saveToINI(IniFile& ini) const; - bool checkAdqPatchParams(const StudyMode studyMode, + bool checkAdqPatchParams(const SimulationMode simulationMode, const AreaList& areas, const bool includeHurdleCostParameters) const; - - void checkAdqPatchStudyModeEconomyOnly(const StudyMode studyMode) const; + void checkAdqPatchSimulationModeEconomyOnly(const SimulationMode simulationMode) const; void checkAdqPatchContainsAdqPatchArea(const Antares::Data::AreaList& areas) const; void checkAdqPatchIncludeHurdleCost(const bool includeHurdleCost) const; - void checkAdqPatchDisabledLocalMatching() const; }; } // namespace Antares::Data::AdequacyPatch diff --git a/src/libs/antares/study/include/antares/study/parts/common/cluster.h b/src/libs/antares/study/include/antares/study/parts/common/cluster.h new file mode 100644 index 0000000000..53e5d115d6 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/common/cluster.h @@ -0,0 +1,154 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_ANTARES_STUDY_PARTS_COMMON_H__ +#define __LIBS_ANTARES_STUDY_PARTS_COMMON_H__ + +#include +#include +#include + +#include +#include + +#include +#include + +#include "../../fwd.h" + +namespace Antares +{ +namespace Data +{ +class Cluster; + +struct CompareClusterName final +{ + bool operator()(const Cluster* s1, const Cluster* s2) const; +}; + +class Cluster +{ +public: + using Set = std::set; + +public: + Cluster(Area* parent); + + virtual ~Cluster() = default; + + const ClusterName& id() const; + const ClusterName& group() const; + const ClusterName& name() const; + void setName(const AnyString& newname); + Yuni::String getFullName() const; + + virtual uint groupId() const = 0; + virtual void setGroup(Data::ClusterName newgrp) = 0; + + /*! + ** \brief Check and fix all values of a renewable cluster + ** + ** \return False if an error has been detected and fixed with a default value + */ + virtual bool integrityCheck() = 0; + + /*! + ** \brief Get the memory consummed by the cluster (in bytes) + */ + virtual uint64_t memoryUsage() const = 0; + //@} + + /*! + ** \brief Invalidate all data associated to the cluster + */ + virtual bool forceReload(bool reload) const = 0; + + /*! + ** \brief Invalidate the whole attached area + */ + void invalidateArea(); + + /*! + ** \brief Mark the cluster as modified + */ + virtual void markAsModified() const = 0; + + /*! + ** \brief Check wether the cluster is visible in a layer (it's parent area is visible in the + *layer) + */ + bool isVisibleOnLayer(const size_t& layerID) const; + + /*! + ** \brief Reset to default values + ** + ** This method should only be called from the GUI + */ + virtual void reset(); + + bool saveDataSeriesToFolder(const AnyString& folder) const; + bool loadDataSeriesFromFolder(Study& s, const AnyString& folder); + + uint unitCount = 0; + + bool isEnabled() const + { + return enabled; + } + + bool enabled = true; + + //! The associate area (alias) + Area* parentArea; + + //! Capacity of reference per unit (MW) (pMax) + double nominalCapacity = 0.; + + //! The index of the cluster from the area's point of view + //! \warning this variable is only valid when used by the solver + // (initialized in the same time that the runtime data) + uint areaWideIndex = (uint)-1; + + //! tsNumbers must be constructed before series + TimeSeriesNumbers tsNumbers; + + //! Series + TimeSeries series; + + /*! + ** \brief Modulation matrix + ** + ** It is merely a 3x8760 matrix + ** [modulation cost, modulation capacity, market bid modulation] per hour + */ + Matrix<> modulation; + +protected: + Data::ClusterName pName; + Data::ClusterName pID; + Data::ClusterName pGroup; + +private: + virtual unsigned int precision() const = 0; +}; +} // namespace Data +} // namespace Antares +#endif /* __LIBS_ANTARES_STUDY_PARTS_COMMON_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/common/cluster_list.h b/src/libs/antares/study/include/antares/study/parts/common/cluster_list.h new file mode 100644 index 0000000000..8c06990ddd --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/common/cluster_list.h @@ -0,0 +1,173 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_COMMON_CLUSTER_LIST_H__ +#define __ANTARES_LIBS_STUDY_PARTS_COMMON_CLUSTER_LIST_H__ + +#include +#include +#include +#include + +#include +#include + +#include "../../fwd.h" + +namespace Antares +{ +namespace Data +{ +/*! +** \brief Generic list of clusters +** \ingroup renewableclusters +** This class implements the base functions for a list of cluster +** It's used for thermal and renewable clusters +*/ +template +class ClusterList +{ +public: + using SharedPtr = typename std::shared_ptr; + + void clearAll(); + bool empty() const; + + /*! + ** \brief Try to find a cluster from its id (const) in the complete cluster list + ** + ** \param id ID of the cluster to find + ** \return A pointer to a cluster. nullptr if not found + */ + ClusterT* findInAll(std::string_view id) const; + + /*! + ** \brief Get if a cluster exists + ** + ** \param id ID of the cluster to find + ** \return True if the cluster exists + */ + bool exists(const Data::ClusterName& id) const; + + auto each_enabled() const + { + return allClusters_ | std::views::filter(&ClusterT::isEnabled); + } + + std::vector> all() const; + + /*! + ** \brief Rename a cluster + ** + ** \param idToFind ID of the cluster to rename + ** \param newName The new name for the cluster + ** \return True if the operation succeeded (the cluster has been renamed) + ** false otherwise (not found or if another cluster has the same name) + ** + ** The indexes for clusters will be rebuilt. + */ + bool rename(Data::ClusterName idToFind, Data::ClusterName newName); + + /*! + ** \brief Remove properly a cluster + */ + virtual bool remove(const Data::ClusterName& id); + + //@} + + SharedPtr operator[](std::size_t idx) + { + return allClusters_[idx]; + } + + SharedPtr operator[](std::size_t idx) const + { + return allClusters_[idx]; + } + + SharedPtr enabledClusterAt(unsigned int index) const; + /*! + ** \brief Resize all matrices dedicated to the sampled timeseries numbers + ** + ** \param n A number of years + */ + void resizeAllTimeseriesNumbers(uint n) const; + + void storeTimeseriesNumbers(Solver::IResultWriter& writer) const; + + //@} + + /*! + ** \brief Invalidate all clusters + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark the clusters as modified + */ + void markAsModified() const; + + /*! + ** \brief Get the size (bytes) occupied in memory by a `ClusterList` structure + ** \return A size (in bytes) + */ + virtual uint64_t memoryUsage() const = 0; + + /// \name IO functions + /// @{ + bool loadDataSeriesFromFolder(Study& study, const AnyString& folder); + + bool saveDataSeriesToFolder(const AnyString& folder) const; + + virtual bool saveToFolder(const AnyString& folder) const = 0; + ///@} + + /*! + ** \brief Retrieve the total capacity and the total unit count + ** + ** Pseudo code: + ** \code + ** each thermal clusters do + ** total += clusters{unit count} * clusters{nominal capacity} + ** unit += clusters{unit count} + ** \endcode + */ + void retrieveTotalCapacityAndUnitCount(double& total, uint& unitCount) const; + + unsigned int enabledCount() const; + unsigned int allClustersCount() const; + void addToCompleteList(std::shared_ptr cluster); + void sortCompleteList(); + +protected: + std::vector> allClusters_; + + virtual std::string typeID() const = 0; + + // Give a special index to enabled clusters (thermal / renewable) + void rebuildIndexes(); + +private: + bool alreadyInAllClusters(std::string clusterName); + +}; // class ClusterList +} // namespace Data +} // namespace Antares +#endif /* __ANTARES_LIBS_STUDY_PARTS_COMMON_CLUSTER_LIST_H__ */ diff --git a/src/libs/antares/study/parts/hydro/allocation.h b/src/libs/antares/study/include/antares/study/parts/hydro/allocation.h similarity index 83% rename from src/libs/antares/study/parts/hydro/allocation.h rename to src/libs/antares/study/include/antares/study/parts/hydro/allocation.h index df64310465..095d8349fe 100644 --- a/src/libs/antares/study/parts/hydro/allocation.h +++ b/src/libs/antares/study/include/antares/study/parts/hydro/allocation.h @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_H__ #define __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_H__ -#include "../../fwd.h" +#include #include #include +#include "../../fwd.h" + namespace Antares { namespace Data @@ -95,7 +91,7 @@ class HydroAllocation final /*! ** \brief Load allocation coefficients from a file */ - bool loadFromFile(const AreaName& referencearea, const AnyString& filename); + bool loadFromFile(const AreaName& referencearea, const std::filesystem::path& filename); /*! ** \brief Load allocation coefficients from a file diff --git a/src/libs/antares/study/include/antares/study/parts/hydro/allocation.hxx b/src/libs/antares/study/include/antares/study/parts/hydro/allocation.hxx new file mode 100644 index 0000000000..7f655d65da --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/hydro/allocation.hxx @@ -0,0 +1,42 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_HXX__ +#define __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_HXX__ + +namespace Antares +{ +namespace Data +{ +template +inline void HydroAllocation::eachNonNull(const CallbackT& callback) const +{ + assert(pMustUseValuesFromAreaID); + auto end = pValuesFromAreaID.end(); + for (auto i = pValuesFromAreaID.begin(); i != end; ++i) + { + callback(i->first, i->second); + } +} + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_HXX__ diff --git a/src/libs/antares/study/include/antares/study/parts/hydro/container.h b/src/libs/antares/study/include/antares/study/parts/hydro/container.h new file mode 100644 index 0000000000..01c219b46b --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/hydro/container.h @@ -0,0 +1,246 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ + +#include + +#include "../../fwd.h" +#include "allocation.h" +#include "prepro.h" +#include "series.h" + +namespace Antares::Data +{ + +//! The maximum number of days in a year +constexpr size_t dayYearCount = 366; + +struct DailyDemand +{ + //! Net demand, for each day of the year, for each area + double DLN = 0.; + //! Daily local effective load + double DLE = 0.; +}; + +struct MonthlyGenerationTargetData +{ + //! Monthly local effective demand + double MLE = 0.; + //! Monthly optimal generation + double MOG = 0.; + //! Monthly optimal level + double MOL = 0.; + //! Monthly target generations + double MTG = 0.; +}; + +//! Hydro Management Data for a given area +struct TimeDependantHydroManagementData +{ + std::array daily{0}; + std::array monthly{0}; +}; + +//! Area Hydro Management Data for a given year +struct AreaDependantHydroManagementData +{ + //! inflows + std::array inflows{}; + //! monthly minimal generation + std::array mingens{}; + + //! daily minimal generation + std::array dailyMinGen{}; + + // Data for minGen<->inflows preChecks + //! monthly total mingen + std::array totalMonthMingen{}; + //! monthly total inflows + std::array totalMonthInflows{}; + //! yearly total mingen + double totalYearMingen = 0; + //! yearly total inflows + double totalYearInflows = 0; + +}; // struct AreaDependantHydroManagementData + +/*! +** \brief Hydro for a single area +*/ +class PartHydro +{ +public: + enum + { + //! The minimum value + minimum = 0, + //! The average value + average, + //! The maximum value + maximum, + }; + + enum weeklyHydroMod + { + //! Weekly generating modulation + genMod = 0, + //! Weekly pumping modulation + pumpMod, + }; + + /*! + ** \brief Load data for hydro container from a folder + ** + ** \param folder The targer folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + static bool LoadFromFolder(Study& study, const AnyString& folder); + + /*! + ** \brief Check and validate the loaded datas + ** + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + static bool validate(Study& study); + + /*! + ** \brief Save data from several containers to a folder (except data for the prepro and + *time-series) + ** + ** \param l List of areas + ** \param folder The targer folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + static bool SaveToFolder(const AreaList& areas, const AnyString& folder); + + /*! + ** \brief Default Constructor + */ + PartHydro(); + //! Destructor + ~PartHydro(); + + /*! + ** \brief Reset internal data + */ + void reset(); + + void copyFrom(const PartHydro& rhs); + + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark all data as modified + */ + void markAsModified() const; + + /*! + ** \brief Load daily max energy + */ + bool LoadDailyMaxEnergy(const AnyString& folder, const AnyString& areaid); + + bool CheckDailyMaxEnergy(const AnyString& areaName); + + //! Inter-daily breakdown (previously called Smoothing Factor or alpha) + double interDailyBreakdown; + //! Intra-daily modulation + double intraDailyModulation; + + //! Intermonthly breakdown + double intermonthlyBreakdown; + + //! Enabled reservoir management + bool reservoirManagement; + + //! Following load modulation + bool followLoadModulations; + //! Use water values + bool useWaterValue; + //! Hard bound on rule curves + bool hardBoundsOnRuleCurves; + //! Use heuristic target + bool useHeuristicTarget; + //! Reservoir capacity (MWh) + double reservoirCapacity; + // gp : pb - initializeReservoirLevelDate must be an enum from january (= 0) to december (= 11) + //! Initialize reservoir level date (month) + int initializeReservoirLevelDate; + //! Use Leeway + bool useLeeway; + //! Power to level modulations + bool powerToLevel; + //! Leeway low bound + double leewayLowerBound; + //! Leeway upper bound + double leewayUpperBound; + //! Puming efficiency + double pumpingEfficiency; + //! Credit Modulation (default 0, 101 * 2) + Matrix creditModulation; + + //! Daily Inflow Patern ([default 1, 0 inflowPattern; + + //! Daily reservoir level ({min,avg,max}x365) + Matrix reservoirLevel; + + //! Daily water value ({0,1,2%...100%}x365) + Matrix waterValues; + + //! Hydro allocation, from other areas + HydroAllocation allocation; + + //! Data for the pre-processor + PreproHydro* prepro; + + //! Data for time-series + DataSeriesHydro* series; + // TODO : following time series could be hosted by the series data member above (of type + // DataSeriesHydro), + // which contains other time. + Matrix dailyNbHoursAtGenPmax; + Matrix dailyNbHoursAtPumpPmax; + std::unordered_map managementData; + + std::vector> deltaBetweenFinalAndInitialLevels; + +private: + static bool checkReservoirLevels(const Study& study); + static bool checkProperties(Study& study); + +}; // class PartHydro + +// Interpolates a water value from a table according to a level and a day. +// As this function can be called a lot of times, we pass working variables and returned variables +// as arguments, so that we don't have to create them locally (as in a classical function) each +// time. +double getWaterValue(const double& level, const Matrix& waterValues, const uint day); + +// Interpolates a rate from the credit modulation table according to a level +double getWeeklyModulation(const double& level /* format : in % of reservoir capacity */, + Matrix& creditMod, + int modType); + +} // namespace Antares::Data + +#endif /* __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/hydro/finalLevelValidator.h b/src/libs/antares/study/include/antares/study/parts/hydro/finalLevelValidator.h new file mode 100644 index 0000000000..518e29d40b --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/hydro/finalLevelValidator.h @@ -0,0 +1,73 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ +#pragma once + +#include "antares/study/parts/hydro/container.h" + +namespace Antares::Data +{ +class PartHydro; + +class FinalLevelValidator +{ +public: + FinalLevelValidator(PartHydro& hydro, + unsigned int areaIndex, + const AreaName areaName, + double initialLevel, + double finalLevel, + const unsigned int year, + const unsigned int lastSimulationDay, + const unsigned int firstMonthOfSimulation); + bool check(); + bool finalLevelFineForUse(); + +private: + bool wasSetInScenarioBuilder(); + bool compatibleWithReservoirProperties(); + bool skippingFinalLevelUse(); + bool checkForInfeasibility(); + bool hydroAllocationStartMatchesSimulation() const; + bool isFinalLevelReachable() const; + double calculateTotalInflows() const; + bool isBetweenRuleCurves() const; + + // Data from simulation + unsigned int year_ = 0; + unsigned int lastSimulationDay_ = 0; + unsigned int firstMonthOfSimulation_ = 0; + + // Data from area + PartHydro& hydro_; + unsigned int areaIndex_; + const AreaName areaName_; + double initialLevel_; + double finalLevel_; + + bool finalLevelFineForUse_ = false; +}; +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/parts/hydro/hydromaxtimeseriesreader.h b/src/libs/antares/study/include/antares/study/parts/hydro/hydromaxtimeseriesreader.h new file mode 100644 index 0000000000..f1c4cb8e36 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/hydro/hydromaxtimeseriesreader.h @@ -0,0 +1,85 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ + +#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_MAX_TIME_SERIES_READER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_MAX_TIME_SERIES_READER_H__ + +#include "antares/study/parts/hydro/container.h" + +namespace Antares::Data +{ +/*! +** This class provides support for old studies, reading from deprecated files, +** fils matrix dailyMaxPumpAndGen and transfers data to the corresponding data +** class members of class PartHydro. Just versions below 8.7 will use instance +** of this class to be compatible with current implementation. +*/ +class HydroMaxTimeSeriesReader +{ +public: + HydroMaxTimeSeriesReader(PartHydro& hydro, std::string areaID, std::string areaName); + + bool read(const AnyString& folder, bool usedBySolver); + + enum powerDailyE + { + //! Generated max power + genMaxP = 0, + //! Generated max energy + genMaxE, + //! Pumping max Power + pumpMaxP, + // Pumping max Energy + pumpMaxE, + }; + +private: + Matrix dailyMaxPumpAndGen; + + PartHydro& hydro_; + std::string areaID_; + std::string areaName_; + + /** + * \brief Loading deprecated files + * This function provides reading from deprecated files which + * contains daily maximum generation/pumping power and energy data. + */ + bool loadDailyMaxPowersAndEnergies(const AnyString& folder, bool usedBySolver); + + /** + * \brief Copy energy functions + * These functions provides coping of energy data loaded + * from deprecated file. + */ + void copyDailyMaxEnergy() const; + void copyDailyMaxGenerationEnergy() const; + void copyDailyMaxPumpingEnergy() const; +}; +} // namespace Antares::Data + +#endif /*__ANTARES_LIBS_STUDY_PARTS_HYDRO_MAX_TIME_SERIES_READER_H__*/ diff --git a/src/libs/antares/study/include/antares/study/parts/hydro/prepro.h b/src/libs/antares/study/include/antares/study/parts/hydro/prepro.h new file mode 100644 index 0000000000..b35798f862 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/hydro/prepro.h @@ -0,0 +1,135 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_PREPRO_H__ +#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_PREPRO_H__ + +#include + +#include "../../fwd.h" + +namespace Antares +{ +namespace Data +{ +/*! +** \brief Data for the hydro preprocessor +** \ingroup hydroprepro +*/ +class PreproHydro +{ +public: + enum + { + /*! + ** \brief The expectation of the total capacity (Espérance du logarithme de 'energie totale) + ** + ** These values will be modified before launching a simulation. + ** The solver requires log(expectaction) and log(stddeviation) + */ + expectation = 0, + /*! + ** \brief The standard deviation of the total capacity (ecart-type du logarithme de + *l'energie totale) + ** + ** These values will be modified before launching a simulation. + ** The solver requires log(expectaction) and log(stddeviation) + */ + stdDeviation, + //! Minimum capacity per month + minimumEnergy, + //! Maximum capacity per month + maximumEnergy, + /*! + ** \brief Power over water + ** + ** Proportion du fil de l'eau : l'hydraulique est representee au travers de son + ** energie totale mensuelle; cette proportion est donc une proportion en énergie + ** La valeur peut varier entre 0 (pas de fil de l'eau) et 1 (pas d'hydraulique modulable) + */ + powerOverWater, + //! The maximum number of item + hydroPreproMax + + }; // anonymous enum + +public: + //! \name Constructor + //@{ + /*! + ** \brief Default constructor + */ + PreproHydro(); + //@} + + /*! + ** \brief Reset all data to their default values + */ + void reset(); + + /*! + ** \brief Copy data from another PreproHydro structure + */ + void copyFrom(const PreproHydro& rhs); + + /*! + ** \brief Load hydro settings for the prepro from a folder + ** + ** \param folder The source folder (ex: `input/hydro/prepro`) + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool loadFromFolder(Study& s, const AreaName& areaID, const std::string& folder); + + bool validate(const std::string& areaID); + /*! + ** \brief Save hydro settings for the prepro into a folder + ** + ** \param folder The target folder (ex: `input/hydro/prepro`) + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool saveToFolder(const AreaName& areaID, const char* folder); + + bool forceReload(bool reload = false) const; + + void markAsModified() const; + +public: + //! The intermonthly correlation value + double intermonthlyCorrelation; + //! data + Matrix<> data; + +}; // class PreproHydro + +int PreproHydroLoadFromFolder(Study& s, + PreproHydro* h, + const AreaName& areaID, + const char folder[]); + +/*! +** \brief Get the size (bytes) occupied in memory by a `PreproHydro` structure +** \ingroup hydroprepro +*/ +uint64_t PreproHydroMemoryUsage(PreproHydro* h); + +} // namespace Data +} // namespace Antares + +#endif /* __ANTARES_LIBS_STUDY_PARTS_HYDRO_PREPRO_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/hydro/series.h b/src/libs/antares/study/include/antares/study/parts/hydro/series.h new file mode 100644 index 0000000000..431f14905c --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/hydro/series.h @@ -0,0 +1,155 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_H__ +#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_H__ + +#include +#include +#include + +#include "../../fwd.h" + +namespace Antares +{ +namespace Data +{ + +/*! +** \brief Data series (Hydro) +*/ +class DataSeriesHydro +{ +public: + //! \name Constructor + //@{ + /*! + ** \brief Default constructor + */ + DataSeriesHydro(); + //@} + + void copyGenerationTS(const DataSeriesHydro& source); + void copyMaxPowerTS(const DataSeriesHydro& source); + + //! \name Data + //@{ + /*! + ** \brief Reset all data, as if it were a new area + */ + void reset(); + + // This method erases data + void resizeTS(uint nbSeries); + + /*! + ** \brief Load all data not already loaded + ** + ** If the load-on-demand is enabled, some data might not be loaded (see `Matrix`) + */ + bool forceReload(bool reload = false) const; + + void markAsModified() const; + //@} + + // Loading hydro time series collection + // Returned boolean : reading from file failed + bool loadGenerationTS(const AreaName& areaID, const AnyString& folder, StudyVersion version); + + // Loading hydro max generation and mqx pumping TS's + bool LoadMaxPower(const AreaName& areaID, const AnyString& folder); + + void buildHourlyMaxPowerFromDailyTS(const Matrix::ColumnType& DailyMaxGenPower, + const Matrix::ColumnType& DailyMaxPumpPower); + + /*! + ** \brief Save data series for hydro into a folder (`input/hydro/series`) + ** + ** Nothing will be done if the pointer to the structure is null. + ** + ** \param d The data series for hydro + ** \param folder The target folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool saveToFolder(const AreaName& areaID, const AnyString& folder) const; + //@} + + //! \name Memory + //@{ + /*! + ** \brief Get the size (bytes) in memory occupied by a `DataSeriesHydro` structure + */ + uint64_t memoryUsage() const; + /*! + ** \brief Try to estimate the amount of memory required for launching a simulation + */ + + //@} + + TimeSeriesNumbers timeseriesNumbers; + + /*! + ** \brief Run-of-the-river - ROR (MW) + ** + ** (it was DAYS_PER_YEAR before 3.9) + */ + TimeSeries ror; + + /*! + ** \brief Mod (MW) + ** + ** Merely a matrix of TimeSeriesCount * 365 values + ** This matrix is not used in `adequation` mode. + */ + TimeSeries storage; + + /*! + ** \brief Minimum Generation (MW) + ** + ** Merely a matrix of TimeSeriesCount * HOURS_PER_YEAR values + */ + TimeSeries mingen; + + /*! + ** \brief Maximum Generation (MW) + ** + ** Merely a matrix of TimeSeriesCount * HOURS_PER_YEAR values + */ + + TimeSeries maxHourlyGenPower; + + /*! + ** \brief Maximum Pumping (MW) + ** + ** Merely a matrix of TimeSeriesCount * HOURS_PER_YEAR values + */ + TimeSeries maxHourlyPumpPower; + + // Getters for generation (ror, storage and mingen) and + // max power (generation and pumping) number of TS + uint TScount() const; + + // Setting TS's when derated mode is on + void resizeTSinDeratedMode(bool derated, StudyVersion version, bool useBySolver); +}; // class DataSeriesHydro +} // namespace Data +} // namespace Antares + +#endif /* __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/load/container.h b/src/libs/antares/study/include/antares/study/parts/load/container.h new file mode 100644 index 0000000000..083dc6df7d --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/load/container.h @@ -0,0 +1,85 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_LOAD_CONTAINER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_LOAD_CONTAINER_H__ + +#include + +#include + +namespace Antares +{ +namespace Data +{ +namespace Load +{ + +class Prepro; + +class Container final: private Yuni::NonCopyable +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Container(); + //! Destructor + ~Container(); + //@} + + /*! + ** \brief Reset to default values + */ + void resetToDefault(); + + /*! + ** \brief Make sure that all data are loaded + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark the load data as modified + */ + void markAsModified() const; + + /*! + ** \brief Get the amount of memory currently used by the class + */ + uint64_t memoryUsage() const; + +public: + //! Data for the pre-processor + Data::Load::Prepro* prepro; + + TimeSeriesNumbers tsNumbers; + + /*! Data for time-series */ + TimeSeries series; + +}; // class Container + +} // namespace Load +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PARTS_LOAD_CONTAINER_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/load/prepro.h b/src/libs/antares/study/include/antares/study/parts/load/prepro.h new file mode 100644 index 0000000000..bbe3c7a008 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/load/prepro.h @@ -0,0 +1,95 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "../../fwd.h" +#include "../../xcast.h" + +namespace Antares +{ +namespace Data +{ +namespace Load +{ +/*! +** \brief Prepro Load +*/ +class Prepro +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + Prepro(); + //! Destructor + ~Prepro(); + //@} + + /*! + ** \brief Try to estimate the amount of memory required by this class for a simulation + */ + + /*! + ** \brief Load data from a folder + */ + bool loadFromFolder(const AnyString& folder); + + /*! + ** \brief Save data to a folder + */ + bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Get the amount of memory currently used + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Make sure that all data are loaded in memory + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark the load data as modified + */ + void markAsModified() const; + + /*! + ** \brief Reset to default all values + */ + void resetToDefault(); + +public: + //! XCast + Data::XCast xcast; + +private: + bool internalLoadFromFolder(Study& study, const char* folder, uint length); + +}; // Prepro + +} // namespace Load +} // namespace Data +} // namespace Antares + +#include "prepro.hxx" diff --git a/src/libs/antares/study/include/antares/study/parts/load/prepro.hxx b/src/libs/antares/study/include/antares/study/parts/load/prepro.hxx new file mode 100644 index 0000000000..c0bb3b6f6d --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/load/prepro.hxx @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_LOAD_PREPRO_HXX__ +#define __ANTARES_LIBS_STUDY_PARTS_LOAD_PREPRO_HXX__ + +namespace Antares::Data::Load +{ + +inline uint64_t Prepro::memoryUsage() const +{ + return xcast.memoryUsage(); +} + +inline bool Prepro::forceReload(bool reload) const +{ + return xcast.forceReload(reload); +} + +inline void Prepro::markAsModified() const +{ + xcast.markAsModified(); +} + +inline void Prepro::resetToDefault() +{ + xcast.resetToDefaultValues(); +} + +} // namespace Antares::Data::Load + +#endif // __ANTARES_LIBS_STUDY_PARTS_LOAD_PREPRO_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/parts.h b/src/libs/antares/study/include/antares/study/parts/parts.h new file mode 100644 index 0000000000..8f3657d210 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/parts.h @@ -0,0 +1,54 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_H__ +#define __ANTARES_LIBS_STUDY_PARTS_H__ + +// Load +#include "load/container.h" + +// Solar +#include "solar/container.h" +#include "solar/prepro.h" + +// Hydro +#include "hydro/container.h" +#include "hydro/hydromaxtimeseriesreader.h" +#include "hydro/prepro.h" +#include "hydro/series.h" + +// Wind +#include "wind/container.h" +#include "wind/prepro.h" + +// Thermal +#include "thermal/cluster.h" +#include "thermal/container.h" +#include "thermal/defines.h" + +// Renewable +#include "renewable/cluster.h" +#include "renewable/container.h" +#include "renewable/defines.h" + +// Short-term storage +#include "short-term-storage/container.h" + +#endif // __ANTARES_LIBS_STUDY_PARTS_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/renewable/cluster.h b/src/libs/antares/study/include/antares/study/parts/renewable/cluster.h new file mode 100644 index 0000000000..3651706149 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/renewable/cluster.h @@ -0,0 +1,166 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_H__ + +#include +#include + +#include + +#include "../../fwd.h" +#include "../common/cluster.h" +#include "defines.h" + +namespace Antares +{ +namespace Data +{ + +/* +** \brief A single renewable cluster +*/ +class RenewableCluster final: public Cluster +{ +public: + enum RenewableGroup + { + //! Wind offshore + windOffShore = 0, + //! Wind onshore + windOnShore, + //! Concentration solar + thermalSolar, + //! PV solar + PVSolar, + //! Rooftop solar + rooftopSolar, + //! Other 1 + renewableOther1, + //! Other 2 + renewableOther2, + //! Other 3 + renewableOther3, + //! Other 4 + renewableOther4, + + //! The highest value + groupMax + }; + + enum TimeSeriesMode + { + //! TS contain power generation for each unit + //! Nominal capacity is *ignored* + powerGeneration = 0, + //! TS contain production factor for each unit + //! Nominal capacity is used as a multiplicative factor + productionFactor + }; + + //! Set of renewable clusters + using Set = std::set; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor, with a parent area + */ + explicit RenewableCluster(Data::Area* parent); + //@} + + /*! + ** \brief Invalidate all data associated to the renewable cluster + */ + bool forceReload(bool reload) const override; + + /*! + ** \brief Mark the renewable cluster as modified + */ + void markAsModified() const override; + + /*! + ** \brief Reset to default values + ** + ** This method should only be called from the GUI + */ + void reset() override; + + //! Set the group + void setGroup(Data::ClusterName newgrp) override; + //@} + + /*! + ** \brief Check and fix all values of a renewable cluster + ** + ** \return False if an error has been detected and fixed with a default value + */ + bool integrityCheck() override; + + /*! + ** \brief Copy data from another cluster + ** + ** The name and the id will remain untouched. + */ + void copyFrom(const RenewableCluster& cluster); + + /*! + ** \brief Group ID as an uint + */ + uint groupId() const override; + + /*! + ** \brief Get the memory consummed by the renewable cluster (in bytes) + */ + uint64_t memoryUsage() const override; + //@} + + bool setTimeSeriesModeFromString(const YString& value); + + YString getTimeSeriesModeAsString() const; + + /* ! + ** Get production value at time-step ts + */ + double valueAtTimeStep(uint year, uint hourInYear) const; + +public: + /*! + ** \brief The group ID + ** + ** This value is computed from the field 'group' in 'group() + ** \see group() + */ + enum RenewableGroup groupID = renewableOther1; + + enum TimeSeriesMode tsMode = powerGeneration; + + friend class RenewableClusterList; + +private: + unsigned int precision() const override; +}; // class RenewableCluster + +} // namespace Data +} // namespace Antares + +#endif //__ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/renewable/cluster.hxx b/src/libs/antares/study/include/antares/study/parts/renewable/cluster.hxx new file mode 100644 index 0000000000..2b2ccc7cbf --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/renewable/cluster.hxx @@ -0,0 +1,31 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_HXX__ +#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_HXX__ + +namespace Antares +{ +namespace Data +{ +} // namespace Data +} // namespace Antares + +#endif //__ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_HXX__ diff --git a/src/libs/antares/study/include/antares/study/parts/renewable/cluster_list.h b/src/libs/antares/study/include/antares/study/parts/renewable/cluster_list.h new file mode 100644 index 0000000000..275d495020 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/renewable/cluster_list.h @@ -0,0 +1,48 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_LIST_H__ +#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_LIST_H__ + +#include "../../fwd.h" +#include "../common/cluster_list.h" +#include "cluster.h" + +namespace Antares::Data +{ +/*! +** \brief List of renewable clusters +** \ingroup renewableclusters +*/ +class RenewableClusterList: public ClusterList +{ +public: + std::string typeID() const override; + uint64_t memoryUsage() const override; + + bool loadFromFolder(const AnyString& folder, Area* area); + bool validateClusters() const; + + bool saveToFolder(const AnyString& folder) const override; +}; // class RenewableClusterList +} // namespace Antares::Data + +#endif /* __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_LIST_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/renewable/container.h b/src/libs/antares/study/include/antares/study/parts/renewable/container.h new file mode 100644 index 0000000000..c396f6814a --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/renewable/container.h @@ -0,0 +1,80 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_H__ + +#include + +#include "../../fwd.h" +#include "cluster.h" +#include "cluster_list.h" + +namespace Antares +{ +namespace Data +{ +class PartRenewable +{ +public: + //! \name Constructor + //@{ + /*! + ** \brief Default constructor + */ + PartRenewable(); + //! Destructor + ~PartRenewable(); + //@} + + /*! + ** \brief Reset internal data + */ + void reset(); + + /*! + ** \brief Resize all matrices dedicated to the sampled timeseries numbers + ** + ** \param n A number of years + */ + void resizeAllTimeseriesNumbers(uint n); + + /*! + ** \brief Invalidate all JIT data + */ + bool forceReload(bool reload) const; + + /*! + ** \brief Mark the renewable cluster as modified + */ + void markAsModified() const; + +public: + //! List of all renewable clusters (enabled and disabled) + RenewableClusterList list; + +}; // class PartRenewable + +} // namespace Data +} // namespace Antares + +#include "container.hxx" + +#endif /* __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/renewable/container.hxx b/src/libs/antares/study/include/antares/study/parts/renewable/container.hxx new file mode 100644 index 0000000000..0afed2c3eb --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/renewable/container.hxx @@ -0,0 +1,36 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_HXX__ +#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_HXX__ + +namespace Antares +{ +namespace Data +{ +inline void PartRenewable::resizeAllTimeseriesNumbers(uint n) +{ + list.resizeAllTimeseriesNumbers(n); +} + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_HXX__ diff --git a/src/libs/antares/study/include/antares/study/parts/renewable/defines.h b/src/libs/antares/study/include/antares/study/parts/renewable/defines.h new file mode 100644 index 0000000000..98980effc2 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/renewable/defines.h @@ -0,0 +1,34 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_DEFINES_H__ +#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_DEFINES_H__ + +namespace Antares +{ +namespace Data +{ +// Forward declaration +class RenewableCluster; + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_DEFINES_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/short-term-storage/cluster.h b/src/libs/antares/study/include/antares/study/parts/short-term-storage/cluster.h new file mode 100644 index 0000000000..cc9af74015 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/short-term-storage/cluster.h @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include +#include + +#include + +#include "properties.h" +#include "series.h" + +namespace Antares::Data::ShortTermStorage +{ +class STStorageCluster +{ +public: + bool enabled() const; + bool validate() const; + + bool loadFromSection(const IniFile::Section& section); + bool loadSeries(const std::string& folder) const; + + void saveProperties(IniFile& ini) const; + bool saveSeries(const std::string& path) const; + + std::string id; + + std::shared_ptr series = std::make_shared(); + mutable Properties properties; +}; +} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/include/antares/study/parts/short-term-storage/container.h b/src/libs/antares/study/include/antares/study/parts/short-term-storage/container.h new file mode 100644 index 0000000000..d2469032dc --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/short-term-storage/container.h @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once +#include +#include +#include + +#include "cluster.h" + +namespace Antares::Data::ShortTermStorage +{ +class STStorageInput +{ +public: + bool validate() const; + /// 1. Read list.ini + bool createSTStorageClustersFromIniFile(const std::filesystem::path& path); + /// 2. Read ALL series + bool loadSeriesFromFolder(const std::string& folder) const; + /// Number of enabled ST storages, ignoring disabled ST storages + std::size_t count() const; + /// erase disabled cluster from the vector + uint removeDisabledClusters(); + + bool saveToFolder(const std::string& folder) const; + bool saveDataSeriesToFolder(const std::string& folder) const; + + std::vector storagesByIndex; +}; +} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/include/antares/study/parts/short-term-storage/properties.h b/src/libs/antares/study/include/antares/study/parts/short-term-storage/properties.h new file mode 100644 index 0000000000..11b4808e0d --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/short-term-storage/properties.h @@ -0,0 +1,61 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include +#include + +#include + +namespace Antares::Data::ShortTermStorage +{ +class Properties +{ +public: + bool validate(); + bool loadKey(const IniFile::Property* p); + void save(IniFile& ini) const; + + /// Not optional Injection nominal capacity, >= 0 + std::optional injectionNominalCapacity; + /// Not optional Withdrawal nominal capacity, >= 0 + std::optional withdrawalNominalCapacity; + /// Not optional Reservoir capacity in MWh, >= 0 + std::optional reservoirCapacity; + /// Initial level, <= 1 + double initialLevel = initiallevelDefault; + /// Bool to optimise or not initial level + bool initialLevelOptim = false; + /// Efficiency factor between 0 and 1 + double efficiencyFactor = 1; + // Used to sort outputs + std::string groupName = "OTHER1"; + /// cluster name + std::string name; + + /// Enabled ? + bool enabled = true; + +private: + static constexpr double initiallevelDefault = .5; +}; +} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/include/antares/study/parts/short-term-storage/series.h b/src/libs/antares/study/include/antares/study/parts/short-term-storage/series.h new file mode 100644 index 0000000000..e6302680f8 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/short-term-storage/series.h @@ -0,0 +1,57 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include +#include + +namespace Antares::Data::ShortTermStorage +{ +class Series +{ +public: + // check if series values are valid + bool validate() const; + + // load all series files with folder path + bool loadFromFolder(const std::string& folder); + void fillDefaultSeriesIfEmpty(); + + bool saveToFolder(const std::string& folder) const; + + std::vector maxInjectionModulation; + std::vector maxWithdrawalModulation; + std::vector inflows; + std::vector lowerRuleCurve; + std::vector upperRuleCurve; + +private: + bool validateSizes() const; + bool validateMaxInjection() const; + bool validateMaxWithdrawal() const; + bool validateRuleCurves() const; + bool validateUpperRuleCurve() const; + bool validateLowerRuleCurve() const; +}; + +bool loadFile(const std::string& folder, std::vector& vect); +bool writeVectorToFile(const std::string& path, const std::vector& vect); + +} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/include/antares/study/parts/solar/container.h b/src/libs/antares/study/include/antares/study/parts/solar/container.h new file mode 100644 index 0000000000..a4ea96d55b --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/solar/container.h @@ -0,0 +1,82 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_CONTAINER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_CONTAINER_H__ + +#include + +namespace Antares +{ +namespace Data +{ +namespace Solar +{ +class Prepro; + +class Container +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Container(); + //! Destructor + ~Container(); + //@} + + /*! + ** \brief Reset to default values + */ + void resetToDefault(); + + /*! + ** \brief Make sure that all data are loaded + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark all data as modified + */ + void markAsModified() const; + + /*! + ** \brief Get the amount of memory currently used by the class + */ + uint64_t memoryUsage() const; + +public: + //! Data for the pre-processor + Data::Solar::Prepro* prepro; + + TimeSeriesNumbers tsNumbers; + + /*! Data for time-series */ + TimeSeries series; + +}; // class Container + +} // namespace Solar +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_CONTAINER_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/solar/prepro.h b/src/libs/antares/study/include/antares/study/parts/solar/prepro.h new file mode 100644 index 0000000000..4365c0c6cf --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/solar/prepro.h @@ -0,0 +1,95 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ +#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ + +#include "../../xcast.h" + +namespace Antares +{ +namespace Data +{ +namespace Solar +{ +/*! +** \brief Prepro Solar +*/ +class Prepro +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + Prepro(); + //! Destructor + ~Prepro(); + //@} + + /*! + ** \brief Try to estimate the amount of memory required by this class for a simulation + */ + + /*! + ** \brief Solar data from a folder + */ + bool loadFromFolder(const AnyString& folder); + + /*! + ** \brief Save data to a folder + */ + bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Get the amount of memory currently used + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Make sure that all data are loaded in memory + */ + bool forceReload(bool reload = false) const; + + void markAsModified() const; + + /*! + ** \brief Reset to default all values + */ + void resetToDefault(); + +public: + //! XCast + Data::XCast xcast; + +private: + bool internalSolarFromFolder(Study& study, const char* folder, uint length); + bool internalSolarFormatBefore33(Study& study, const YString& folder); + +}; // Prepro + +} // namespace Solar +} // namespace Data +} // namespace Antares + +#include "prepro.hxx" + +#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/solar/prepro.hxx b/src/libs/antares/study/include/antares/study/parts/solar/prepro.hxx new file mode 100644 index 0000000000..5bf5a90d98 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/solar/prepro.hxx @@ -0,0 +1,48 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_HXX__ +#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_HXX__ + +namespace Antares::Data::Solar +{ +inline uint64_t Prepro::memoryUsage() const +{ + return xcast.memoryUsage(); +} + +inline bool Prepro::forceReload(bool reload) const +{ + return xcast.forceReload(reload); +} + +inline void Prepro::markAsModified() const +{ + xcast.markAsModified(); +} + +inline void Prepro::resetToDefault() +{ + xcast.resetToDefaultValues(); +} + +} // namespace Antares::Data::Solar + +#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/cluster.h b/src/libs/antares/study/include/antares/study/parts/thermal/cluster.h new file mode 100644 index 0000000000..7d1ce30bac --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/cluster.h @@ -0,0 +1,405 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_H__ + +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "../../fwd.h" +#include "../common/cluster.h" +#include "defines.h" +#include "ecoInput.h" +#include "pollutant.h" + +namespace Antares +{ +namespace Data +{ +enum ThermalModulation +{ + thermalModulationCost = 0, + thermalModulationMarketBid, + thermalModulationCapacity, + thermalMinGenModulation, + thermalModulationMax +}; + +enum CostGeneration +{ + setManually = 0, + useCostTimeseries +}; + +enum class LocalTSGenerationBehavior +{ + useGlobalParameter = 0, + forceGen, + forceNoGen +}; + +/*! +** \brief A single thermal cluster +*/ +class ThermalCluster final: public Cluster, public std::enable_shared_from_this +{ +public: + enum ThermalDispatchableGroup + { + //! Nuclear + thermalDispatchGrpNuclear = 0, + //! Lignite + thermalDispatchGrpLignite, + //! Hard Coal + thermalDispatchGrpHardCoal, + //! Gas + thermalDispatchGrpGas, + //! Oil + thermalDispatchGrpOil, + //! Mixed fuel + thermalDispatchGrpMixedFuel, + //! Other 1 + thermalDispatchGrpOther1, + //! Other 2 + thermalDispatchGrpOther2, + //! Other 3 + thermalDispatchGrpOther3, + //! Other 4 + thermalDispatchGrpOther4, + + //! The highest value + groupMax + }; + + Pollutant emissions; + + //! Set of thermal clusters + using Set = std::set; + //! Set of thermal clusters (pointer) + using SetPointer = std::set; + //! Vector of thermal clusters + using Vector = std::vector; + + /*! + ** \brief Get the group name string + ** \return A valid CString + */ + static const char* GroupName(enum ThermalDispatchableGroup grp); + + explicit ThermalCluster(Data::Area* parent); + + ThermalCluster() = delete; + ~ThermalCluster(); + + /*! + ** \brief Invalidate all data associated to the thermal cluster + */ + bool forceReload(bool reload) const override; + + /*! + ** \brief Mark the thermal cluster as modified + */ + void markAsModified() const override; + + /*! + ** \brief Reset to default values + ** + ** This method should only be called from the GUI + */ + void reset() override; + + //! Set the group + void setGroup(Data::ClusterName newgrp) override; + //@} + + //! \name Spinning + //@{ + /*! + ** \brief Calculation of spinning + ** + ** The formula is : TS[i,j] = TS[i,j] * (1 - Spinning / 100) + */ + void calculationOfSpinning(); + + //! \name MarketBid and Marginal Costs + //@{ + /*! + ** \brief Calculation of market bid and marginals costs per hour + */ + void ComputeCostTimeSeries(); + + /*! + ** \brief Calculation of spinning (reverse) + ** + ** The original formula for the calculation of the spinning is : + ** TS[i,j] = TS[i,j] * (1 - Spinning / 100) + ** + ** This method is used to removed the spinning, before exporting the TS matrices + ** into the input. + */ + void reverseCalculationOfSpinning(); + //@} + + /*! + ** \brief Check and fix all values of a thermal cluster + ** + ** \return False if an error has been detected and fixed with a default value + */ + bool integrityCheck() override; + + /*! + ** \brief Copy data from another cluster + ** + ** The name and the id will remain untouched. + */ + void copyFrom(const ThermalCluster& cluster); + + /*! + ** \brief Group ID as an uint + */ + uint groupId() const override; + + /*! + ** \brief Get the memory consummed by the thermal cluster (in bytes) + */ + uint64_t memoryUsage() const override; + //@} + + //! \name validity of Min Stable Power + //@{ + // bool minStablePowerValidity() const; + + /*! + ** \brief Calculte the minimum modulation/ceil(modulation) from 8760 capacity modulation + */ + void calculatMinDivModulation(); + + /*! + ** \brief Check the validity of Min Stable Power + */ + bool checkMinStablePower(); + + /*! + ** \brief Check the validity of Min Stable Power with a new modulation value + */ + bool checkMinStablePowerWithNewModulation(uint idx, double value); + //@} + + bool doWeGenerateTS(bool globalTSgeneration) const; + + double getOperatingCost(uint tsIndex, uint hourInTheYear) const; + double getMarginalCost(uint tsIndex, uint hourInTheYear) const; + double getMarketBidCost(uint hourInTheYear, uint year) const; + + // Check & correct availability timeseries for thermal availability + // Only applies if time-series are ready-made + void checkAndCorrectAvailability(); + + bool isActive() const; + + //! The index of the cluster (within a list) + uint index = 0; + + /*! + ** \brief The group ID + ** + ** This value is computed from the field 'group' in 'group() + ** \see group() + */ + ThermalDispatchableGroup groupID = thermalDispatchGrpOther1; + + //! Mustrun + bool mustrun = false; + + bool isMustRun() const + { + return mustrun; + } + + //! Mustrun (as it were at the loading of the data) + // + // This value might differ from mustrun, because `mustrun` might be + // modified for different reasons. + // Only used by the solver in adequacy mode + bool mustrunOrigin = false; + + //! Nominal capacity - spinning (solver only) + double nominalCapacityWithSpinning = 0.; + + //! \name PMin + //@{ + //! Min. Stable Power (MW) + double minStablePower = 0.; + + struct DivModulation + { + DivModulation(): + value(0.0), + isCalculated(false), + isValidated(false) + { + } + + double value; + double border; + uint index; + bool isCalculated; + bool isValidated; + } minDivModulation; + + //! Min. Up time (1..168) + uint minUpTime = 1; + //! Min. Down time (1..168) + uint minDownTime = 1; + //! Max entre . minUp/minDown time (1..168) + uint minUpDownTime; + //@} + + //! Spinning (%) + double spinning = 0.; + + //! Efficiency (%) + double fuelEfficiency = 100; + + //! Forced Volatility + double forcedVolatility = 0.; + //! Planned volatility + double plannedVolatility = 0.; + + //! Law (ts-generator) + StatisticalLaw forcedLaw = LawUniform; + //! Law (ts-generator) + StatisticalLaw plannedLaw = LawUniform; + + //! \name Costs + // Marginal (€/MWh) MA + // Spread (€/MWh) SP + // Fixed (€ / hour) FI + // Start-up (€/start) SU + // Market bid (€/ MWh) MB + // + // v3.4: + // O(h) = MB * P(h) + // + // v3.5: + // solver input : MB + // output : + // O(h) = MA * P(h) + // if (P(h) > 0) + // O(h) += FI + // if (N(h) > N(h-1)) + // O(h) += SU* (N(h)-N(h-1)) + // + // \see 101206-antares-couts.doc + // + // v5.0: + // Abs( SU ) = 0 or in [0.005;5000000] + // v4.5: + // Abs( MA ) = 0 or in [0.005;50000] + // Abs( FI ) = 0 or in [0.005;50000] + // Abs( SU ) = 0 or in [0.005;50000] + // Abs( MB ) = 0 or in [0.005;50000] + // SP >=0 or in [0.005;50000] + // + //@{ + + //! Cost generation + CostGeneration costgeneration = setManually; + //! Marginal cost (euros/MWh) + double marginalCost = 0; + //! Spread (euros/MWh) + double spreadCost = 0; + //! Fixed cost (euros/hour) + double fixedCost = 0; + //! Startup cost (euros/startup) + double startupCost = 0; + //! Market bid cost (euros/MWh) + double marketBidCost = 0; + //! Variable O&M cost (euros/MWh) + double variableomcost = 0; + //@} + + /*! + ** \brief thermalMinGenModulation vector used in solver only to store the year values + ** 8760 vector + ** PthetaInf[hour] + */ + std::vector PthetaInf; + + //! Data for the preprocessor + PreproAvailability* prepro = nullptr; + + /*! + ** \brief Production Cost, Market Bid Cost and Marginal Cost Matrixes - Per Hour and per Time + *Series + */ + struct CostsTimeSeries + { + std::array productionCostTs; + std::array marketBidCostTS; + std::array marginalCostTS; + }; + + std::vector costsTimeSeries; + + EconomicInputData ecoInput; + + LocalTSGenerationBehavior tsGenBehavior = LocalTSGenerationBehavior::useGlobalParameter; + + friend class ThermalClusterList; + + double computeMarketBidCost(double fuelCost, double co2EmissionFactor, double co2cost); + + unsigned int precision() const override; + +private: + // Calculation of marketBid and marginal costs hourly time series + // + // Calculation of market bid and marginals costs per hour + // + // These time series can be set + // Market bid and marginal costs are set manually. + // Or if time series are used the formula is: + // Marginal_Cost[€/MWh] = Market_Bid_Cost[€/MWh] = (Fuel_Cost[€/GJ] * 3.6 * 100 / Efficiency[%]) + // CO2_emission_factor[tons/MWh] * C02_cost[€/tons] + Variable_O&M_cost[€/MWh] + + void fillMarketBidCostTS(); + void fillMarginalCostTS(); + void resizeCostTS(); + void ComputeMarketBidTS(); + void MarginalCostEqualsMarketBid(); + void ComputeProductionCostTS(); + +}; // class ThermalCluster +} // namespace Data +} // namespace Antares + +#include "cluster.hxx" + +#endif /* __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/cluster.hxx b/src/libs/antares/study/include/antares/study/parts/thermal/cluster.hxx new file mode 100644 index 0000000000..8c2eaaf7cd --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/cluster.hxx @@ -0,0 +1,156 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_HXX__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_HXX__ + +namespace Yuni +{ +namespace Extension +{ +namespace CString +{ +template +class Append +{ +public: + static void Perform(CStringT& string, Antares::Data::StatisticalLaw law) + { + switch (law) + { + case Antares::Data::LawUniform: + string += "uniform"; + break; + case Antares::Data::LawGeometric: + string += "geometric"; + break; + } + } +}; + +template +class Append +{ +public: + static void Perform(CStringT& string, Antares::Data::CostGeneration costgeneration) + { + switch (costgeneration) + { + case Antares::Data::setManually: + string += "setManually"; + break; + case Antares::Data::useCostTimeseries: + string += "useCostTimeseries"; + break; + } + } +}; + +template +class Append +{ +public: + static void Perform(CStringT& string, Antares::Data::LocalTSGenerationBehavior behavior) + { + switch (behavior) + { + case Antares::Data::LocalTSGenerationBehavior::forceGen: + string += "force generation"; + break; + case Antares::Data::LocalTSGenerationBehavior::forceNoGen: + string += "force no generation"; + break; + default: + string += "use global"; + break; + } + } +}; + +template<> +class Into +{ +public: + using TargetType = Antares::Data::StatisticalLaw; + + enum + { + valid = 1 + }; + + static bool Perform(AnyString string, TargetType& out); + + template + static TargetType Perform(const StringT& s) + { + TargetType law = Antares::Data::LawUniform; + Perform(s, law); + return law; + } +}; + +template<> +class Into +{ +public: + using TargetType = Antares::Data::CostGeneration; + enum class Validation + { + valid = 1 + }; + + static bool Perform(AnyString string, TargetType& out); + + template + static TargetType Perform(const StringT& s) + { + TargetType costgeneration = Antares::Data::setManually; + Perform(s, costgeneration); + return costgeneration; + } +}; + +template<> +class Into +{ +public: + using TargetType = Antares::Data::LocalTSGenerationBehavior; + + enum + { + valid = 1 + }; + + static bool Perform(AnyString string, TargetType& out); + + template + static TargetType Perform(const StringT& s) + { + TargetType behavior = Antares::Data::LocalTSGenerationBehavior::useGlobalParameter; + Perform(s, behavior); + return behavior; + } +}; + +} // namespace CString +} // namespace Extension +} // namespace Yuni + +#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_HXX__ diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/cluster_list.h b/src/libs/antares/study/include/antares/study/parts/thermal/cluster_list.h new file mode 100644 index 0000000000..9f091defda --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/cluster_list.h @@ -0,0 +1,136 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include + +#include "../common/cluster_list.h" +#include "cluster.h" + +namespace Antares +{ +namespace Data +{ +/*! +** \brief List of clusters +** \ingroup thermalclusters +*/ +class ThermalClusterList: public ClusterList +{ +public: + std::string typeID() const override; + uint64_t memoryUsage() const override; + + /*! + ** \brief Get the size (bytes) occupied in memory by a `ThermalClusterList` structure + ** \return A size (in bytes) + */ + bool loadFromFolder(Study& s, const AnyString& folder, Area* area); + + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + ThermalClusterList(); + /*! + ** \brief Destructor + */ + virtual ~ThermalClusterList(); + //@} + + //! \name Spinning + //@{ + /*! + ** \brief Calculation of Spinning for all thermal clusters + */ + void calculationOfSpinning(); + + /*! + ** \brief Calculation of Spinning for all thermal clusters (reverse) + */ + void reverseCalculationOfSpinning(); + //@} + + //! \name Mustrun + //@{ + /*! + ** \brief Enable the 'mustrun' mode for every cluster + ** + ** This method is especially useful for the adequacy mode, where all clusters + ** must be in mustrun mode + */ + void enableMustrunForEveryone(); + + //@} + + auto each_mustrun_and_enabled() const + { + return allClusters_ | std::views::filter(&ThermalCluster::isMustRun) + | std::views::filter(&ThermalCluster::isEnabled); + } + + auto each_enabled_and_not_mustrun() const + { + return allClusters_ | std::views::filter(&ThermalCluster::isEnabled) + | std::views::filter(std::not_fn(&ThermalCluster::isMustRun)); + } + + /*! + ** \brief Ensure data for the prepro are initialized + ** \ingroup thermalclusters + ** + ** \todo Remaining of old C-library. this routine should be moved into the appropriate class + ** \param l The list of thermal clusters + */ + void ensureDataPrepro(); + + /*! + ** \brief Load data related to the preprocessor from a list of thermal clusters from a folder + ** \ingroup thermalclusters + ** + ** \todo Remaining of old C-library. this routine should be moved into the appropriate class + ** \param l A list of thermal clusters + ** \param folder The target folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool loadPreproFromFolder(Study& s, const AnyString& folder); + bool validatePrepro(const Study& study); + + bool validateClusters(const Parameters& param) const; + + bool loadEconomicCosts(Study& s, const AnyString& folder); + + bool savePreproToFolder(const AnyString& folder) const; + bool saveEconomicCosts(const AnyString& folder) const; + + bool saveToFolder(const AnyString& folder) const override; + + unsigned int enabledAndMustRunCount() const; + unsigned int enabledAndNotMustRunCount() const; + +private: + // Give a special index to enbled and not must-run THERMAL clusters + void rebuildIndex() const; + +}; // class ThermalClusterList +} // namespace Data +} // namespace Antares diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/container.h b/src/libs/antares/study/include/antares/study/parts/thermal/container.h new file mode 100644 index 0000000000..ce9634cfdb --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/container.h @@ -0,0 +1,97 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_H__ + +#include + +#include "cluster_list.h" + +namespace Antares +{ +namespace Data +{ +class PartThermal +{ +public: + //! \name Constructor + //@{ + /*! + ** \brief Default constructor + */ + PartThermal(); + //! Destructor + ~PartThermal() = default; + //@} + + /*! + ** \brief Reset internal data + */ + void reset(); + + /*! + ** \brief Resize all matrices dedicated to the sampled timeseries numbers + ** + ** \param n A number of years + */ + void resizeAllTimeseriesNumbers(uint n) const; + + /*! + ** \brief Invalidate all JIT data + */ + bool forceReload(bool reload) const; + + /*! + ** \brief Mark the thermal cluster as modified + */ + void markAsModified() const; + + /*! + ** \brief Some clusters force the generation of timeseries, + overriding the global (study) parameter. + */ + bool hasForcedTimeseriesGeneration() const; + + /*! + ** \brief Some clusters prevent the generation of timeseries, + overriding the global (study) parameter. + */ + bool hasForcedNoTimeseriesGeneration() const; + + // Check & correct availability timeseries for thermal availability + // Only applies if time-series are ready-made + void checkAndCorrectAvailability() const; + +public: + //! The unsupplied energy cost (Euros/MWh) + double unsuppliedEnergyCost; + //! The spilled energy cost + double spilledEnergyCost; + + //! List of all thermal clusters (enabled and disabled) except must-run clusters + ThermalClusterList list; + +}; // class PartThermal + +} // namespace Data +} // namespace Antares + +#endif /* __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/defines.h b/src/libs/antares/study/include/antares/study/parts/thermal/defines.h new file mode 100644 index 0000000000..5d74c795ff --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/defines.h @@ -0,0 +1,36 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_DEFINES_H__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_DEFINES_H__ + +namespace Antares +{ +namespace Data +{ +// Forward declaration +class ThermalCluster; +class ThermalClusterList; +class PreproAvailability; + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_DEFINES_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/ecoInput.h b/src/libs/antares/study/include/antares/study/parts/thermal/ecoInput.h new file mode 100644 index 0000000000..ef31c31f66 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/ecoInput.h @@ -0,0 +1,89 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_ECOINPUT_H__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_ECOINPUT_H__ + +#include + +#include +#include + +#include "../../fwd.h" +#include "defines.h" + +namespace Antares::Data +{ +/*! +** \brief Thermal +*/ +class EconomicInputData +{ +public: + //! \name Constructor + //@{ + /*! + ** \brief Default constructor + */ + explicit EconomicInputData(); + //@} + + bool forceReload(bool reload) const; + + void markAsModified() const; + + /*! + ** \brief Reset all values to their default ones + */ + void reset(); + + //! Copy data from another struct + void copyFrom(const EconomicInputData& rhs); + + /*! + ** \brief Load settings for the thermal prepro from a folder + ** + ** \param folder The source folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool loadFromFolder(Study& study, const std::string& folder); + + /*! + ** \brief Save settings used by the thermal prepro to a folder + ** + ** \param folder The targer folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Get the amount of memory used by the class + */ + uint64_t memoryUsage() const; + + //! All {FO,PO}{Duration,Rate} annual values + // max x DAYS_PER_YEAR + TimeSeries::TS fuelcost; + TimeSeries::TS co2cost; + +}; // class EconomicInputData + +} // namespace Antares::Data +#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_ECOINPUT_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/thermal/pollutant.h b/src/libs/antares/study/include/antares/study/parts/thermal/pollutant.h new file mode 100644 index 0000000000..b632e44510 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/thermal/pollutant.h @@ -0,0 +1,63 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_POLLUTANT_H__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_POLLUTANT_H__ + +#include +#include +#include + +namespace Antares::Data +{ + +class Pollutant +{ +public: + enum PollutantEnum + { + CO2 = 0, + NH3, + SO2, + NOX, + PM2_5, + PM5, + PM10, + NMVOC, + OP1, + OP2, + OP3, + OP4, + OP5, + POLLUTANT_MAX + }; + + static const std::map pollutantNamesOutputVariables; + static const std::string& getPollutantName(int index); + + static const std::map namesToEnum; + + std::array factors{0}; + +}; // class Pollutant + +} // namespace Antares::Data + +#endif /* __ANTARES_LIBS_STUDY_PARTS_THERMAL_POLLUTANT_H__ */ diff --git a/src/libs/antares/study/include/antares/study/parts/wind/container.h b/src/libs/antares/study/include/antares/study/parts/wind/container.h new file mode 100644 index 0000000000..7e36522597 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/wind/container.h @@ -0,0 +1,82 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_CONTAINER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_WIND_CONTAINER_H__ + +#include + +#include "prepro.h" + +namespace Antares +{ +namespace Data +{ +namespace Wind +{ +class Container +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Container(); + //! Destructor + ~Container(); + //@} + + /*! + ** \brief Reset to default values + */ + void resetToDefault(); + + /*! + ** \brief Make sure that all data are loaded + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark all data as modified + */ + void markAsModified() const; + + /*! + ** \brief Get the amount of memory currently used by the class + */ + uint64_t memoryUsage() const; + +public: + //! Data for the pre-processor + Data::Wind::Prepro* prepro; + + TimeSeriesNumbers tsNumbers; + + /*! Data for time-series */ + TimeSeries series; + +}; // class Container + +} // namespace Wind +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_CONTAINER_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/wind/prepro.h b/src/libs/antares/study/include/antares/study/parts/wind/prepro.h new file mode 100644 index 0000000000..1d0ed8722e --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/wind/prepro.h @@ -0,0 +1,85 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ +#define __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ + +#include "../../fwd.h" +#include "../../xcast.h" + +namespace Antares::Data::Wind +{ +/*! +** \brief Prepro Wind +*/ +class Prepro +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + Prepro(); + //! Destructor + ~Prepro(); + //@} + + /*! + ** \brief Try to estimate the amount of memory required by this class for a simulation + */ + + /*! + ** \brief Load data from a folder + */ + bool loadFromFolder(const AnyString& folder); + + /*! + ** \brief Save data to a folder + */ + bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Get the amount of memory currently used + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Make sure that all data are loaded in memory + */ + bool forceReload(bool reload = false) const; + + void markAsModified() const; + + /*! + ** \brief Reset to default all values + */ + void resetToDefault(); + + //! XCast + Data::XCast xcast; + +}; // Prepro + +} // namespace Antares::Data::Wind + +#include "prepro.hxx" + +#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ diff --git a/src/libs/antares/study/include/antares/study/parts/wind/prepro.hxx b/src/libs/antares/study/include/antares/study/parts/wind/prepro.hxx new file mode 100644 index 0000000000..5013c89f8c --- /dev/null +++ b/src/libs/antares/study/include/antares/study/parts/wind/prepro.hxx @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_HXX__ +#define __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_HXX__ + +namespace Antares::Data::Wind +{ + +inline uint64_t Prepro::memoryUsage() const +{ + return xcast.memoryUsage(); +} + +inline bool Prepro::forceReload(bool reload) const +{ + return xcast.forceReload(reload); +} + +inline void Prepro::markAsModified() const +{ + xcast.markAsModified(); +} + +inline void Prepro::resetToDefault() +{ + xcast.resetToDefaultValues(); +} + +} // namespace Antares::Data::Wind + +#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ diff --git a/src/libs/antares/study/progression/progression.h b/src/libs/antares/study/include/antares/study/progression/progression.h similarity index 84% rename from src/libs/antares/study/progression/progression.h rename to src/libs/antares/study/include/antares/study/progression/progression.h index e183dfc675..bcdeca82ac 100644 --- a/src/libs/antares/study/progression/progression.h +++ b/src/libs/antares/study/include/antares/study/progression/progression.h @@ -1,42 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_SOLVER_SIMULATION_PROGRESSION_H__ #define __ANTARES_LIBS_SOLVER_SIMULATION_PROGRESSION_H__ -#include -#include -#include -#include +#include #include +#include +#include #include -#include "../fwd.h" + +#include #include +#include + #include +#include "../fwd.h" + namespace Antares { namespace Solver @@ -59,6 +57,7 @@ class Progression final sectImportTS, sectMax }; + enum { npos = (uint)-1, @@ -79,7 +78,7 @@ class Progression final //! The total number of ticks to achieve int maxTickCount; //! The current number of ticks - Yuni::Atomic::Int<32> tickCount; + std::atomic tickCount; //! The last number of ticks, to reduce the log verbosity int lastTickCount; // Caption to use when displaying logs @@ -165,14 +164,17 @@ class Progression final void end(Part& part); private: - class Meter final : public Yuni::Thread::Timer + class Meter final: public Yuni::Thread::Timer { public: Meter(); + virtual ~Meter() { if (logsContainer) + { delete[] logsContainer; + } } void allocateLogsContainer(uint nb); @@ -189,7 +191,7 @@ class Progression final // Progression::Part::Map parts; Part::ListRef inUse; - Yuni::Mutex mutex; + std::mutex mutex; uint nbParallelYears; // Because writing something to the logs might be expensive, we have to diff --git a/src/libs/antares/study/include/antares/study/progression/progression.hxx b/src/libs/antares/study/include/antares/study/progression/progression.hxx new file mode 100644 index 0000000000..91430681dc --- /dev/null +++ b/src/libs/antares/study/include/antares/study/progression/progression.hxx @@ -0,0 +1,86 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PROGRESSION_PROGRESSION_HXX__ +#define __ANTARES_LIBS_STUDY_PROGRESSION_PROGRESSION_HXX__ + +namespace Antares +{ +namespace Solver +{ +inline Progression::Meter::Meter(): + nbParallelYears(0), + logsContainer(nullptr) +{ +} + +inline void Progression::Meter::allocateLogsContainer(uint nb) +{ + logsContainer = new Yuni::CString<256, false>[nb]; +} + +inline void Progression::Meter::taskCount(uint n) +{ + (void)n; +} + +inline void Progression::add(Section section, int nbTicks) +{ + add((uint)-1, section, nbTicks); +} + +inline void Progression::setNumberOfParallelYears(uint nb) +{ + pProgressMeter.nbParallelYears = nb; + pProgressMeter.allocateLogsContainer(nb); +} + +inline Progression::Part& Progression::begin(uint year, Progression::Section section) +{ + // Alias + Part& part = pProgressMeter.parts[year][section]; + // Reset + part.tickCount = 0; + // It is useless to display 0%, so lastTickCount and tickCount can be equals + part.lastTickCount = 0; + pProgressMeter.mutex.lock(); + pProgressMeter.inUse.push_front(&part); + pProgressMeter.mutex.unlock(); + return part; +} + +inline const char* Progression::SectionToCStr(Section section) +{ + static const char* const sectName[sectMax] = {"mc", + "output", + "load", + "solar", + "wind", + "hydro", + "thermal", + "import timeseries"}; + assert((uint)section < (uint)sectMax); + return sectName[section]; +} + +} // namespace Solver +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_PROGRESSION_PROGRESSION_HXX__ diff --git a/src/libs/antares/study/include/antares/study/runtime.h b/src/libs/antares/study/include/antares/study/runtime.h new file mode 100644 index 0000000000..2d40d3b45b --- /dev/null +++ b/src/libs/antares/study/include/antares/study/runtime.h @@ -0,0 +1,26 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __LIBS_ANTARES_STUDY_RUNTIME_H__ +#define __LIBS_ANTARES_STUDY_RUNTIME_H__ + +#include "runtime/runtime.h" + +#endif // __LIBS_ANTARES_STUDY_RUNTIME_H__ diff --git a/src/libs/antares/study/include/antares/study/runtime/runtime.h b/src/libs/antares/study/include/antares/study/runtime/runtime.h new file mode 100644 index 0000000000..0ea07ce3bc --- /dev/null +++ b/src/libs/antares/study/include/antares/study/runtime/runtime.h @@ -0,0 +1,146 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_H__ +#define __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_H__ + +#include +#include + +#include +#include "antares/study/study.h" + +namespace Antares::Data +{ + +enum RangeLimitsIndex +{ + rangeBegin = 0, + rangeEnd, + rangeCount, + rangeMax +}; + +struct StudyRangeLimits +{ +public: + /*! + ** \brief Dynamic bound-checking (debug only) + */ + void checkIntegrity() const; + + //! Hours + uint hour[rangeMax]; + //! Day + uint day[rangeMax]; + //! Week + uint week[rangeMax]; + //! Month + uint month[rangeMax]; + //! Year + uint year[rangeMax]; + +}; // class StudyRangeLimits + +/*! +** \brief Runtime informations +** \ingroup runtimedata +*/ +class StudyRuntimeInfos +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + StudyRuntimeInfos(); + /*! + ** \brief Destructor + */ + ~StudyRuntimeInfos(); + //@} + + /*! + ** \brief Reset internal data according a given study + */ + bool loadFromStudy(Study& study); + + void initializeRandomNumberGenerators(const Parameters& parameters); + +public: + //! The number of years to process + uint nbYears; + + //! Range limits + StudyRangeLimits rangeLimits; + + //! Mode of the simulation + SimulationMode mode; + + //! The number of interconnections + uint interconnectionsCount() const; + //! All interconnections + std::vector areaLink; + + //! Random numbers generators + MersenneTwister random[seedMax]; + + //! Total + uint thermalPlantTotalCount; + uint thermalPlantTotalCountMustRun; + + uint shortTermStorageCount = 0; + + //! Override enable/disable TS generation per cluster + bool thermalTSRefresh = false; + + /*! + ** \brief The number of simulation days per month + */ + uint simulationDaysPerMonth[12]; + + /*! + ** \brief The number of simulation days per week + */ + uint simulationDaysPerWeek[53]; + + /*! + ** \brief Flag to know if at least one error occured during the quadratic optimization + ** + ** In this case, error on NaN should be disabled + */ + bool quadraticOptimizationHasFailed; + +private: + void initializeRangeLimits(const Study& study, StudyRangeLimits& limits); + //! Prepare all thermal clusters in 'must-run' mode + void initializeThermalClustersInMustRunMode(Study& study) const; + void removeDisabledShortTermStorageClustersFromSolverComputations(Study& study); + void removeAllRenewableClustersFromSolverComputations(Study& study); + void disableAllFilters(Study& study); + void checkThermalTSGeneration(Study& study); +}; // struct StudyRuntimeInfos + +} // namespace Antares::Data + +#include "runtime.hxx" + +#endif // __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_H__ diff --git a/src/libs/antares/study/include/antares/study/runtime/runtime.hxx b/src/libs/antares/study/include/antares/study/runtime/runtime.hxx new file mode 100644 index 0000000000..0e04ed3b93 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/runtime/runtime.hxx @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_HXX__ +#define __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_HXX__ + +namespace Antares +{ +namespace Data +{ +#ifdef NDEBUG +inline void StudyRangeLimits::checkIntegrity() const +{ +} +#endif + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_HXX__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h b/src/libs/antares/study/include/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h new file mode 100644 index 0000000000..5a8e2595ee --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h @@ -0,0 +1,70 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 03/07/23. +// + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class BindingConstraintsTSNumberData: public TSNumberData +{ +public: + BindingConstraintsTSNumberData() = default; + virtual ~BindingConstraintsTSNumberData() = default; + + bool reset(const Study& study) override; + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; + + void setTSnumber(const std::string& group_name, unsigned year, unsigned value); + unsigned get(const std::string& group_name, unsigned year) const; + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + unsigned get_tsGenCount(const Study& study) const override; + +private: + std::map rules_; +}; + +inline unsigned BindingConstraintsTSNumberData::get(const std::string& group_name, + const unsigned year) const +{ + auto it = rules_.find(group_name); + if (it == rules_.end()) + { + return 0; + } + return it->second[0][year]; +} + +inline CString<512, false> BindingConstraintsTSNumberData::get_prefix() const +{ + return "bc,"; +} + +inline unsigned BindingConstraintsTSNumberData::get_tsGenCount(const Study&) const +{ + return 0; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/HydroTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/HydroTSNumberData.h new file mode 100644 index 0000000000..9930d1ded7 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/HydroTSNumberData.h @@ -0,0 +1,40 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class hydroTSNumberData: public TSNumberData +{ +public: + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; +}; + +inline CString<512, false> hydroTSNumberData::get_prefix() const +{ + return "h,"; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/LoadTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/LoadTSNumberData.h new file mode 100644 index 0000000000..bcf7382cbf --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/LoadTSNumberData.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class loadTSNumberData: public TSNumberData +{ +public: + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; +}; + +inline CString<512, false> loadTSNumberData::get_prefix() const +{ + return "l,"; +} + +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/NTCTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/NTCTSNumberData.h new file mode 100644 index 0000000000..1a2ec3e49f --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/NTCTSNumberData.h @@ -0,0 +1,70 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 03/07/23. +// + +#pragma once +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class ntcTSNumberData: public TSNumberData +{ +public: + ntcTSNumberData() = default; + virtual ~ntcTSNumberData() = default; + + bool reset(const Study& study) override; + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; + + void attachArea(const Area* area) + { + pArea = area; + } + + void setDataForLink(const Antares::Data::AreaLink* link, const uint year, uint value); + uint get(const Antares::Data::AreaLink* link, const uint year) const; + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; + +private: + //! The attached area, if any + const Area* pArea = nullptr; +}; + +inline uint ntcTSNumberData::get(const Antares::Data::AreaLink* link, const uint year) const +{ + assert(link != nullptr); + if (year < pTSNumberRules.height && link->indexForArea < pTSNumberRules.width) + { + const uint index = link->indexForArea; + return pTSNumberRules[index][year]; + } + return 0; +} + +inline CString<512, false> ntcTSNumberData::get_prefix() const +{ + return "ntc,"; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/RenewableTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/RenewableTSNumberData.h new file mode 100644 index 0000000000..3f60bdefb3 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/RenewableTSNumberData.h @@ -0,0 +1,75 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 03/07/23. +// + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class renewableTSNumberData: public TSNumberData +{ +public: + renewableTSNumberData() = default; + + virtual ~renewableTSNumberData() + { + } + + bool reset(const Study& study) override; + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; + + void attachArea(const Area* area) + { + pArea = area; + } + + void setTSnumber(const Antares::Data::RenewableCluster* cluster, const uint year, uint value); + uint get(const Antares::Data::RenewableCluster* cluster, const uint year) const; + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; + +private: + //! The attached area, if any + const Area* pArea = nullptr; +}; + +inline uint renewableTSNumberData::get(const Antares::Data::RenewableCluster* cluster, + const uint year) const +{ + assert(cluster != nullptr); + if (year < pTSNumberRules.height && cluster->areaWideIndex < pTSNumberRules.width) + { + const uint index = cluster->areaWideIndex; + return pTSNumberRules[index][year]; + } + return 0; +} + +inline CString<512, false> renewableTSNumberData::get_prefix() const +{ + return "r,"; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/TSnumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/TSnumberData.h new file mode 100644 index 0000000000..98255adbbc --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/TSnumberData.h @@ -0,0 +1,98 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_TS_NUMBER_H__ +#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_TS_NUMBER_H__ + +#include "scBuilderDataInterface.h" + +namespace Antares::Data::ScenarioBuilder +{ +/*! +** \brief Rules for TS numbers, for all years and a single timeseries +*/ +class TSNumberData: public dataInterface +{ +public: + //! Matrix + using MatrixType = Matrix; + +public: + // We use default constructor and destructor + + //! \name Data manupulation + //@{ + /*! + ** \brief Reset data from the study + */ + bool reset(const Study& study) override; + + /*! + ** \brief Export the data into a mere INI file + */ + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; + + /*! + ** \brief Assign a single value + ** + ** \param index An area index or a thermal cluster index + ** \param year A year + ** \param value The new TS number + */ + void setTSnumber(uint index, uint year, uint value); + //@} + + uint width() const override; + uint height() const override; + + double get_value(uint x, uint y) const; + void set_value(uint x, uint y, uint value); + +protected: + virtual CString<512, false> get_prefix() const = 0; + + virtual uint get_tsGenCount(const Study& study) const = 0; + +protected: + //! All TS number overlay (0 if auto) + MatrixType pTSNumberRules; + +}; // class TSNumberData + +// class TSNumberData : inline functions + +inline uint TSNumberData::width() const +{ + return pTSNumberRules.width; +} + +inline uint TSNumberData::height() const +{ + return pTSNumberRules.height; +} + +inline double TSNumberData::get_value(uint x, uint y) const +{ + return pTSNumberRules.entry[y][x]; +} + +} // namespace Antares::Data::ScenarioBuilder + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_TS_NUMBER_H__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/ThermalTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/ThermalTSNumberData.h new file mode 100644 index 0000000000..6cc6070473 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/ThermalTSNumberData.h @@ -0,0 +1,72 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 04/07/23. +// + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class thermalTSNumberData: public TSNumberData +{ +public: + thermalTSNumberData() = default; + virtual ~thermalTSNumberData() = default; + + bool reset(const Study& study) override; + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; + + void attachArea(const Area* area) + { + pArea = area; + } + + void setTSnumber(const Antares::Data::ThermalCluster* cluster, const uint year, uint value); + uint get(const Antares::Data::ThermalCluster* cluster, const uint year) const; + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; + +private: + //! The attached area, if any + const Area* pArea = nullptr; +}; + +inline uint thermalTSNumberData::get(const Antares::Data::ThermalCluster* cluster, + const uint year) const +{ + assert(cluster != nullptr); + if (year < pTSNumberRules.height && cluster->areaWideIndex < pTSNumberRules.width) + { + const uint index = cluster->areaWideIndex; + return pTSNumberRules[index][year]; + } + return 0; +} + +inline CString<512, false> thermalTSNumberData::get_prefix() const +{ + return "t,"; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/WindTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/WindTSNumberData.h new file mode 100644 index 0000000000..afc218682f --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/WindTSNumberData.h @@ -0,0 +1,40 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class windTSNumberData: public TSNumberData +{ +public: + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; +}; + +inline CString<512, false> windTSNumberData::get_prefix() const +{ + return "w,"; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/applyToMatrix.hxx b/src/libs/antares/study/include/antares/study/scenario-builder/applyToMatrix.hxx new file mode 100644 index 0000000000..868a20d5b4 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/applyToMatrix.hxx @@ -0,0 +1,122 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +// +// Created by marechaljas on 03/07/23. +// + +#pragma once + +#include + +#include "yuni/core/system/stdint.h" + +#include "antares/study/binding_constraint/BindingConstraintGroup.h" +#include "antares/study/parts/hydro/series.h" +#include "antares/study/scenario-builder/TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ + +static constexpr unsigned maxErrors = 20; + +template +static inline bool CheckValidity(uint value, const D& data, uint tsGenMax) +{ + // When the TS-Generators are not used + return (!tsGenMax) ? (value < data.timeSeries.width) : (value < tsGenMax); +} + +template<> +inline bool CheckValidity(uint value, + const Data::DataSeriesHydro& data, + uint tsGenMax) +{ + // When the TS-Generators are not used + return (!tsGenMax) ? (value < data.TScount()) : (value < tsGenMax); +} + +template<> +inline bool CheckValidity(uint value, + const Data::AreaLink& data, + uint /* tsGenMax */) +{ + // Value = index of time series + // Direct Capacities = all time series + // directCapacities.timeSeries.width = Number of time series + return value < data.directCapacities.timeSeries.width; +} + +template<> +inline bool CheckValidity(uint value, + const BindingConstraintGroup& group, + uint) +{ + return value < group.numberOfTimeseries(); +} + +template +bool ApplyToMatrix(uint& errors, + StringT& logprefix, + D& data, + const TSNumberData::MatrixType::ColumnType& years, + uint tsGenMax) +{ + bool ret = true; + + // In this case, m.height represents the total number of years + const uint nbYears = data.timeseriesNumbers.height(); + // The matrix m has only one column + auto& target = data.timeseriesNumbers; + + for (uint y = 0; y != nbYears; ++y) + { + if (years[y] != 0) + { + // The new TS number + uint32_t tsNum = years[y] - 1; + + // When the TS-Generators are not used + if (!CheckValidity(tsNum, data, tsGenMax)) + { + if (errors <= maxErrors) + { + if (++errors == maxErrors) + { + logs.warning() << "scenario-builder: ... (skipped)"; + } + else + { + logs.warning() << "scenario-builder: " << logprefix + << "value out of bounds for the year " << (y + 1); + } + } + ret = false; + continue; + } + // Ok, assign. The value provided by the interface is user-friendly + // and starts from 1. + target[y] = tsNum; + } + } + + return ret; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/include/antares/study/scenario-builder/hydroLevelsData.h new file mode 100644 index 0000000000..b5cb21073d --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/hydroLevelsData.h @@ -0,0 +1,131 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ +#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ + +#include + +#include "scBuilderDataInterface.h" + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +/*! +** \brief Rules for hydro levels, for all years and areas +*/ +class hydroLevelsData final: public dataInterface +{ +public: + //! Matrix + using MatrixType = Matrix; + +public: + // Constructor + + hydroLevelsData(const std::string& iniFilePrefix, + std::function applyToTarget); + + //! \name Data manupulation + //@{ + /*! + ** \brief Reset data from the study + */ + bool reset(const Study& study); + + /*! + ** \brief Export the data into a mere INI file + */ + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; + + /*! + ** \brief Assign a single value + ** + ** \param index An area index + ** \param year A year + ** \param value The new hydro level + */ + void setTSnumber(uint index, uint year, double value); + //@} + + uint width() const; + + uint height() const; + + double get_value(uint x, uint y) const; + + void set_value(uint x, uint y, double value); + + bool apply(Study& study) override; + +private: + //! Hydro levels overlay (0 if auto) + MatrixType pHydroLevelsRules; + // prefix to be added when calling saveToINIFileHydroLevel + const std::string addToPrefix_; + + std::function applyToTarget_; + +}; // class hydroLevelsData + +// class hydroLevelsData : inline functions + +inline void hydroLevelsData::setTSnumber(uint areaindex, uint year, double value) +{ + assert(areaindex < pHydroLevelsRules.width); + if (year < pHydroLevelsRules.height) + { + pHydroLevelsRules[areaindex][year] = value; + } +} + +inline uint hydroLevelsData::width() const +{ + return pHydroLevelsRules.width; +} + +inline uint hydroLevelsData::height() const +{ + return pHydroLevelsRules.height; +} + +inline double hydroLevelsData::get_value(uint x, uint y) const +{ + return pHydroLevelsRules.entry[y][x]; +} + +inline void initLevelApply(Study& study, Matrix& matrix) +{ + study.scenarioInitialHydroLevels.copyFrom(matrix); +} + +inline void finalLevelApply(Study& study, Matrix& matrix) +{ + study.scenarioFinalHydroLevels.copyFrom(matrix); +} + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/include/antares/study/scenario-builder/rules.h similarity index 80% rename from src/libs/antares/study/scenario-builder/rules.h rename to src/libs/antares/study/include/antares/study/scenario-builder/rules.h index 60039c14be..ff5261d64a 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/include/antares/study/scenario-builder/rules.h @@ -1,47 +1,43 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __LIBS_STUDY_SCENARIO_BUILDER_RULES_H__ #define __LIBS_STUDY_SCENARIO_BUILDER_RULES_H__ +#include +#include + #include #include + #include "../fwd.h" +#include "BindingConstraintsTSNumbersData.h" +#include "HydroTSNumberData.h" +#include "LoadTSNumberData.h" +#include "NTCTSNumberData.h" +#include "RenewableTSNumberData.h" #include "TSnumberData.h" #include "ThermalTSNumberData.h" +#include "WindTSNumberData.h" #include "hydroLevelsData.h" -#include "NTCTSNumberData.h" -#include "BindingConstraintsTSNumbersData.h" -#include "RenewableTSNumberData.h" #include "solarTSNumberData.h" -#include "HydroTSNumberData.h" -#include "WindTSNumberData.h" -#include "LoadTSNumberData.h" -#include -#include namespace Antares { @@ -52,7 +48,7 @@ namespace ScenarioBuilder /*! ** \brief Rules for TS numbers, for all years and a single timeseries */ -class Rules final : private Yuni::NonCopyable +class Rules final: private Yuni::NonCopyable { public: //! Smart pointer @@ -123,8 +119,10 @@ class Rules final : private Yuni::NonCopyable //! Renewable (array [0..pAreaCount - 1]) std::vector renewable; - //! hydro levels - hydroLevelsData hydroLevels; + //! hydro initial levels + hydroLevelsData hydroInitialLevels = {"hl,", initLevelApply}; + //! hydro final levels + hydroLevelsData hydroFinalLevels = {"hfl,", finalLevelApply}; // Links NTC std::vector linksNTC; @@ -139,10 +137,10 @@ class Rules final : private Yuni::NonCopyable bool readWind(const AreaName::Vector& instrs, String value, bool updaterMode); bool readHydro(const AreaName::Vector& instrs, String value, bool updaterMode); bool readSolar(const AreaName::Vector& instrs, String value, bool updaterMode); - bool readHydroLevels(const AreaName::Vector& instrs, String value, bool updaterMode); + bool readInitialHydroLevels(const AreaName::Vector& instrs, String value, bool updaterMode); + bool readFinalHydroLevels(const AreaName::Vector& instrs, String value, bool updaterMode); bool readLink(const AreaName::Vector& instrs, String value, bool updaterMode); - bool readBindingConstraints(const AreaName::Vector &splitKey, String value); - + bool readBindingConstraints(const AreaName::Vector& splitKey, String value); Data::Area* getArea(const AreaName& areaname, bool updaterMode); Data::AreaLink* getLink(const AreaName& fromAreaName, diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/rules.hxx b/src/libs/antares/study/include/antares/study/scenario-builder/rules.hxx new file mode 100644 index 0000000000..3313738677 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/rules.hxx @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_RULES_HXX__ +#define __LIBS_STUDY_SCENARIO_BUILDER_RULES_HXX__ + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +inline uint Rules::areaCount() const +{ + return pAreaCount; +} + +inline const RulesScenarioName& Rules::name() const +{ + return pName; +} + +inline void Rules::setName(RulesScenarioName name) +{ + pName = name; +} + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_RULES_H__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/scBuilderDataInterface.h b/src/libs/antares/study/include/antares/study/scenario-builder/scBuilderDataInterface.h new file mode 100644 index 0000000000..aa3923c93a --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/scBuilderDataInterface.h @@ -0,0 +1,72 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_INTERFACE_H__ +#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_INTERFACE_H__ + +#include +#include + +#include "antares/study/study.h" + +using namespace Yuni; + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +/*! +** \brief Interface for scenario builder data (time series, hydro levels, ...) +*/ +class dataInterface +{ +public: + //! \name Data manupulation + //@{ + /*! + ** \brief Reset data from the study + */ + virtual bool reset(const Study& study) = 0; + + /*! + ** \brief Export the data into a mere INI file + */ + virtual void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const = 0; + + virtual uint width() const = 0; + + virtual uint height() const = 0; + + /*! + ** \brief Apply the changes to the study corresponding data (time series, hydro levels, ...) + ** + ** This method is only useful when launched from the solver. + */ + virtual bool apply(Study& study) = 0; + +}; // class dataInterface + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_INTERFACE_H__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/scBuilderUtils.h b/src/libs/antares/study/include/antares/study/scenario-builder/scBuilderUtils.h new file mode 100644 index 0000000000..a10f511506 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/scBuilderUtils.h @@ -0,0 +1,44 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_UTILS_H__ +#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_UTILS_H__ + +#include + +#include +#include + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +std::string fromHydroLevelToString(double d); +double fromStringToHydroLevel(const Yuni::String& value, const double maxLevel); + +uint fromStringToTSnumber(const Yuni::String& value); + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_UTILS_H__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/sets.h b/src/libs/antares/study/include/antares/study/scenario-builder/sets.h new file mode 100644 index 0000000000..81117af589 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/sets.h @@ -0,0 +1,160 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ +#define __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ + +#include + +#include "rules.h" + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +/*! +** \brief Sets for TS numbers, for all years and a single timeseries +*/ +class Sets final: private Yuni::NonCopyable +{ +public: + //! Iterator + using iterator = Rules::Map::iterator; + //! Const iterator + using const_iterator = Rules::Map::const_iterator; + +public: + //! Update mode, indicates wether we are called from with a ScenarioBuilderUpdater instance or + //! not + bool inUpdaterMode; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + ** + ** \param tstype Type of the timeseries + */ + Sets(); + //! Destructor + ~Sets(); + //@} + + void setStudy(Study& study); + + //! \name Data manupulation + //@{ + /*! + ** \brief Load data from the study + */ + bool loadFromStudy(Study& study); + + /*! + ** \brief Clear all data + */ + void clear(); + + /*! + ** \brief Load all rulesets from an INI file + */ + template + bool loadFromINIFile(const StringT& filename); + /*! + ** \brief Save all rulesets into a mere INI file + */ + template + bool saveToINIFile(const StringT& filename); + //@} + + //! \name Set manipulation + //@{ + /*! + ** \brief Create a new set + ** + ** \return A non-null pointer if the operation succeeded, null otherwise + */ + Rules::Ptr createNew(const RulesScenarioName& name); + + /*! + ** \brief Test if a rules set exist + ** + ** \param lname Name of the rule set (in lower case) + */ + bool exists(const RulesScenarioName& lname) const; + + /*! + ** \brief Find a rule set + */ + Rules::Ptr find(const RulesScenarioName& lname) const; + + /*! + ** \brief Rename a given ruleset + ** + ** \return The object to the ruleset, null if the operation failed + */ + Rules::Ptr rename(const RulesScenarioName& lname, const RulesScenarioName& newname); + + /*! + ** \brief Delete a ruleset + ** + ** \return True if the operation suceeded, false otherwise + */ + bool remove(const RulesScenarioName& lname); + + iterator begin(); + const_iterator begin() const; + + iterator end(); + const_iterator end() const; + + /*! + ** \brief Get the number of available sets + */ + uint size() const; + + /*! + ** \brief Get if empty + */ + bool empty() const; + //@} + +private: + //! Load all rulesets into a mere INI file + bool internalLoadFromINIFile(const AnyString& filename); + //! Save all rulesets into a mere INI file + bool internalSaveToIniFile(const AnyString& filename) const; + +private: + //! All available sets, ordered by their lower name + Rules::Map pMap; + //! Alias to the study + Study* pStudy; +}; // class Sets + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#include "sets.hxx" + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/sets.hxx b/src/libs/antares/study/include/antares/study/scenario-builder/sets.hxx new file mode 100644 index 0000000000..389e9fb59d --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/sets.hxx @@ -0,0 +1,104 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __LIBS_STUDY_SCENARIO_BUILDER_SETS_HXX__ +#define __LIBS_STUDY_SCENARIO_BUILDER_SETS_HXX__ + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +inline uint Sets::size() const +{ + return (uint)pMap.size(); +} + +inline bool Sets::empty() const +{ + return pMap.empty(); +} + +inline Sets::iterator Sets::begin() +{ + return pMap.begin(); +} + +inline Sets::const_iterator Sets::begin() const +{ + return pMap.begin(); +} + +inline Sets::iterator Sets::end() +{ + return pMap.end(); +} + +inline Sets::const_iterator Sets::end() const +{ + return pMap.end(); +} + +inline bool Sets::exists(const RulesScenarioName& lname) const +{ + return pMap.find(lname) != pMap.end(); +} + +inline Rules::Ptr Sets::find(const RulesScenarioName& lname) const +{ + using namespace Yuni; + const_iterator i = pMap.find(lname); + if (i != pMap.end()) + { + return i->second; + } + return nullptr; +} + +template +inline bool Sets::saveToINIFile(const StringT& filename) +{ + const AnyString adapter(filename); + return internalSaveToIniFile(adapter); +} + +template +bool Sets::loadFromINIFile(const StringT& filename) +{ + // If the source code below is changed, please change it in loadFromStudy too + const AnyString adapter(filename); + bool r = internalLoadFromINIFile(adapter); + if (!r) + { + pMap.clear(); + } + if (pMap.empty()) + { + createNew("Default Ruleset"); + } + return r; +} + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/solarTSNumberData.h b/src/libs/antares/study/include/antares/study/scenario-builder/solarTSNumberData.h new file mode 100644 index 0000000000..55642cb7da --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/solarTSNumberData.h @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 04/07/23. +// + +#pragma once + +#include "TSnumberData.h" + +namespace Antares::Data::ScenarioBuilder +{ +class solarTSNumberData: public TSNumberData +{ +public: + bool apply(Study& study) override; + CString<512, false> get_prefix() const override; + uint get_tsGenCount(const Study& study) const override; +}; + +inline CString<512, false> solarTSNumberData::get_prefix() const +{ + return "s,"; +} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/updater.hxx b/src/libs/antares/study/include/antares/study/scenario-builder/updater.hxx new file mode 100644 index 0000000000..a554450084 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/scenario-builder/updater.hxx @@ -0,0 +1,89 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_SCENARIO_BUILDER_UPDATER_HXX__ +#define __ANTARES_LIBS_STUDY_SCENARIO_BUILDER_UPDATER_HXX__ + +#include + +#include "antares/study/study.h" + +#include "sets.h" + +#define SEP IO::Separator + +namespace Antares +{ +namespace // anonymous +{ +class ScenarioBuilderUpdater +{ +public: + ScenarioBuilderUpdater(Data::Study& study): + pStudy(study) + { + using namespace Yuni; + // We can store the INI files in disk because it may not fit in memory + + if (study.scenarioRules) + { + study.scenarioRules->inUpdaterMode = true; + logs.debug() << "[scenario-builder] updater mode ON"; + + logs.debug() + << "[scenario-builder] writing data to a temporary file before structure changes"; + pTempFile << memory.cacheFolder() << SEP << "antares-scenbld-save-" + << memory.processID() << '-' << (size_t)(this) << "-scenariobuilder.tmp"; + // Dump the memory + study.scenarioRules->saveToINIFile(pTempFile); + study.scenarioRules->clear(); + } + } + + ~ScenarioBuilderUpdater() + { + using namespace Yuni; + + if (not pTempFile.empty()) + { + if (pStudy.scenarioRules) + { + logs.debug() << "[scenario-builder] reloading data from a temporary file"; + pStudy.scenarioRules->loadFromINIFile(pTempFile); + + pStudy.scenarioRules->inUpdaterMode = false; + logs.debug() << "[scenario-builder] updater mode OFF"; + } + // Removing the temporary file + IO::File::Delete(pTempFile); + } + } + +private: + Data::Study& pStudy; + Yuni::String pTempFile; + +}; // class ScenarioBuilderUpdater + +} // anonymous namespace + +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_SCENARIO_BUILDER_UPDATER_HXX__ diff --git a/src/libs/antares/study/include/antares/study/sets.h b/src/libs/antares/study/include/antares/study/sets.h new file mode 100644 index 0000000000..0309916749 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/sets.h @@ -0,0 +1,283 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_SETS_H__ +#define __ANTARES_LIBS_STUDY_SETS_H__ + +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace Antares +{ +namespace Data +{ +template +class Sets final +{ +public: + //! Type + using Type = T; + + // + using IDType = Yuni::CString<128, false>; + //! Value + using TypePtr = std::shared_ptr; + + //! Map of Item + using MapType = std::map; + //! Standard iterators from the STL + using iterator = typename MapType::iterator; + //! Standard iterators from the STL (const) + using const_iterator = typename MapType::const_iterator; + + enum RuleType + { + ruleNone = 0, + ruleAdd, + ruleRemove, + ruleFilter, + ruleMax, + }; + + //! Definition of a single rule + using Rule = std::pair; + //! Rule Set + using RuleSet = std::vector; + + class Options final + { + public: + Options(): + output(true), + resultSize(0) + { + } + + Options(const Options& rhs): + caption(rhs.caption), + comments(rhs.comments), + rules(rhs.rules), + output(rhs.output), + resultSize(rhs.resultSize) + { + } + + void reset(const IDType& id) + { + caption = id; + comments.clear(); + rules.clear(); + output = false; + resultSize = 0; + } + + Options& operator=(const Options& rhs) + { + caption = rhs.caption; + comments = rhs.comments; + rules = rhs.rules; + output = rhs.output; + resultSize = rhs.resultSize; + return *this; + } + + public: + //! Caption + IDType caption; + //! Comments + Yuni::String comments; + //! Rules to build the group + RuleSet rules; + //! Enable/Disable the results in the output + bool output; + //! The number of items in the result set + uint resultSize; + + }; // class Options + + using MapOptions = std::map; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Sets(); + /*! + ** \brief Copy constructor + */ + Sets(const Sets& rhs); + //! Destructor + ~Sets(); + //@} + + //! \name Iterators + //@{ + iterator begin(); + const_iterator begin() const; + iterator end(); + const_iterator end() const; + //@} + + /*! + ** \brief Clear all groups + */ + void clear(); + + /*! + ** + */ + TypePtr add(const IDType& name) + { + TypePtr p = new T(); + pMap[name] = p; + pOptions[name].reset(name); + return p; + } + + /*! + ** + */ + TypePtr add(const IDType& name, const TypePtr& data) + { + pMap[name] = data; + pOptions[name].reset(name); + return data; + } + + /*! + ** + */ + TypePtr add(const IDType& name, const TypePtr& data, Options& opts) + { + pMap[name] = data; + pOptions[name] = opts; + return data; + } + + bool forceReload(bool /*reload*/) const + { + pModified = true; + return true; + } + + void markAsModified() const + { + pModified = true; + } + + uint size() const; + + void rebuildIndexes(); + + /*! + ** \brief Get if the results for a given group should be written to the output + */ + template + bool hasOutput(const StringT& s) const; + + /*! + ** \brief Get if the results for a given group should be written to the output + */ + bool hasOutput(const uint index) const; + + /*! + ** \brief Get the size of a result set + */ + template + uint resultSize(const StringT& s) const; + + /*! + ** \brief Get the size of a result set + */ + uint resultSize(const uint index) const; + + template + void dumpToLogs(L& log) const; + + /*! + ** \brief Load a rule set from an INI File + */ + bool loadFromFile(const std::filesystem::path& filename); + + template + bool saveToFile(const StringT& filename) const; + /*! + ** \brief format the string to match the options + */ + YString toString(); + + /*! + ** \brief Create default groups for set of areas + */ + void defaultForAreas(); + + /*! + ** \brief Rebuild the lists of a group from the rules + */ + template + void rebuildFromRules(const IDType& id, HandlerT& handler); + + /*! + ** \brief Rebuild the lists of all group from the rules + */ + template + void rebuildAllFromRules(HandlerT& handler); + + const IDType& nameByIndex(const uint i) const + { + assert(i < pMap.size() && "Sets: operator[] index out of bounds"); + return pNameByIndex[i]; + } + + template + IDType caption(const StringT& s) const; + + IDType caption(const uint i) const; + + T& operator[](uint i); + const T& operator[](uint i) const; + +private: + //! All groups + MapType pMap; + MapOptions pOptions; + //! + TypePtr* pByIndex; + IDType* pNameByIndex; + mutable bool pModified; + +}; // class Sets + +} // namespace Data +} // namespace Antares + +#include "sets.hxx" + +#endif // __ANTARES_LIBS_STUDY_SETS_H__ diff --git a/src/libs/antares/study/include/antares/study/sets.hxx b/src/libs/antares/study/include/antares/study/sets.hxx new file mode 100644 index 0000000000..931e044ba0 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/sets.hxx @@ -0,0 +1,487 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_SETS_HXX__ +#define __ANTARES_LIBS_STUDY_SETS_HXX__ + +namespace Antares +{ +namespace Data +{ +template +inline Sets::Sets(): + pByIndex(NULL), + pNameByIndex(NULL), + pModified(false) +{ +} + +template +inline Sets::Sets(const Sets& rhs): + pMap(rhs.pMap), + pOptions(rhs.pOptions), + pByIndex(NULL), + pNameByIndex(NULL), + pModified(false) +{ + if (rhs.pByIndex) + { + rebuildIndexes(); + } +} + +template +inline Sets::~Sets() +{ + delete[] pByIndex; +} + +template +typename Sets::iterator Sets::begin() +{ + return pMap.begin(); +} + +template +typename Sets::const_iterator Sets::begin() const +{ + return pMap.begin(); +} + +template +typename Sets::iterator Sets::end() +{ + return pMap.end(); +} + +template +typename Sets::const_iterator Sets::end() const +{ + return pMap.end(); +} + +template +void Sets::clear() +{ + if (pByIndex) + { + delete[] pByIndex; + pByIndex = NULL; + } + if (pNameByIndex) + { + delete[] pNameByIndex; + pNameByIndex = NULL; + } + + pMap.clear(); + pOptions.clear(); +} + +template +inline T& Sets::operator[](uint i) +{ + assert(i < pMap.size() && "Sets: operator[] index out of bounds"); + return *(pByIndex[i]); +} + +template +inline const T& Sets::operator[](uint i) const +{ + assert(i < pMap.size() && "Sets: operator[] index out of bounds"); + return *(pByIndex[i]); +} + +template +template +void Sets::dumpToLogs(L& log) const +{ + using namespace Yuni; + const typename MapType::const_iterator end = pMap.end(); + for (typename MapType::const_iterator i = pMap.begin(); i != end; ++i) + { + log.info() << " found `" << i->first << "` (" << (uint)i->second->size() << ' ' + << (i->second->size() < 2 ? "item" : "items") + << ((!hasOutput(i->first)) ? ", no output" : "") << ')'; + } +} + +template +void Sets::defaultForAreas() +{ + using namespace Yuni; + clear(); + Options opts; + opts.caption = "All areas"; + opts.comments = "Spatial aggregates on all areas"; + opts.output = false; + opts.rules.push_back(Rule(ruleFilter, new String("add-all"))); + auto item = std::make_shared(); + add("all areas", item, opts); +} + +template +YString Sets::toString() +{ + using namespace Yuni; + using namespace Antares; + static const char* cmds[ruleMax] = {"none", "+", "-", "apply-filter"}; + const auto end = pOptions.cend(); + YString ret = ""; + for (auto i = pOptions.cbegin(); i != end; ++i) + { + const Options& opts = i->second; + ret << '[' << i->first << "]\n"; + ret << "caption = " << opts.caption << '\n'; + if (not opts.comments.empty()) + { + ret << "comments = " << opts.comments << '\n'; + } + if (!opts.output) + { + ret << "output = false\n"; + } + + for (uint r = 0; r != opts.rules.size(); ++r) + { + const Rule& rule = opts.rules[r]; + ret << cmds[rule.first] << " = " << rule.second << '\n'; + } + ret << '\n'; + } + return ret; +} + +template +template +bool Sets::saveToFile(const StringT& filename) const +{ + using namespace Yuni; + using namespace Antares; + + Yuni::IO::File::Stream file; + if (!file.open(filename, Yuni::IO::OpenMode::write | Yuni::IO::OpenMode::truncate)) + { + logs.error() << "I/O Error: " << filename << ": impossible to write the file"; + return false; + } + + static const char* cmds[ruleMax] = {"none", "+", "-", "apply-filter"}; + const auto end = pOptions.cend(); + for (auto i = pOptions.cbegin(); i != end; ++i) + { + const Options& opts = i->second; + file << '[' << i->first << "]\n"; + file << "caption = " << opts.caption << '\n'; + if (not opts.comments.empty()) + { + file << "comments = " << opts.comments << '\n'; + } + if (!opts.output) + { + file << "output = false\n"; + } + + for (uint r = 0; r != opts.rules.size(); ++r) + { + const Rule& rule = opts.rules[r]; + file << cmds[rule.first] << " = " << rule.second << '\n'; + } + file << '\n'; + } + return true; +} + +template +bool Sets::loadFromFile(const std::filesystem::path& filename) +{ + using namespace Yuni; + using namespace Antares; + + // Empty the container first + clear(); + + // Loading the INI file + if (!std::filesystem::exists(filename)) + { + // Error silently ignored + return true; + } + + IniFile ini; + if (ini.open(filename)) + { + Yuni::String value; + + // each section... + for (auto* section = ini.firstSection; section != nullptr; section = section->next) + { + // Clearing the name. + if (!section->name) + { + continue; + } + + // Creating a new section + auto item = std::make_shared(); + Options opts; + opts.caption = section->name; + + // each property... + const IniFile::Property* p; + for (p = section->firstProperty; p != nullptr; p = p->next) + { + if (p->key.empty()) + { + continue; + } + + value = p->value; + value.toLower(); + + if (p->key == "+") + { + opts.rules.push_back(Rule(ruleAdd, new String(value))); + continue; + } + if (p->key == "-") + { + opts.rules.push_back(Rule(ruleRemove, new String(value))); + continue; + } + if (p->key == "apply-filter") + { + opts.rules.push_back(Rule(ruleFilter, new String(value))); + continue; + } + if (p->key == "output") + { + opts.output = value.to(); + continue; + } + if (p->key == "comments") + { + opts.comments = p->value; + opts.comments.trim(" \t"); + continue; + } + if (p->key == "caption") + { + opts.caption = p->value; + continue; + } + + logs.warning() << "sets: `" << filename << "`: Invalid property `" << p->key + << '\''; + } + + // Add the new group + IDType newid = section->name; + newid.toLower(); + add(newid, item, opts); + } + + // Not modified anymore + pModified = false; + // All indexes must be rebuilt + rebuildIndexes(); + return true; + } + return false; +} + +template +template +inline void Sets::rebuildAllFromRules(HandlerT& handler) +{ + for (uint i = 0; i != pMap.size(); ++i) + { + rebuildFromRules(pNameByIndex[i], handler); + } +} + +template +template +void Sets::rebuildFromRules(const IDType& id, HandlerT& handler) +{ + using namespace Yuni; + using namespace Antares; + + typename MapOptions::iterator i = pOptions.find(id); + if (i == pOptions.end()) + { + return; + } + // Options + Options& opts = i->second; + Type& set = *(pMap[id]); + + // Clear the result first + handler.clear(set); + // Apply all rules + for (uint i = 0; i != opts.rules.size(); ++i) + { + const Rule& rule = opts.rules[i]; + const Yuni::String& arg = *(rule.second); + switch (rule.first) // type + { + case ruleAdd: + { + // Trying to add a single item + if (!handler.add(set, arg)) + { + // Failed. Maybe the argument references another group + const IDType other = arg; + typename MapType::iterator i = pMap.find(other); + if (i != pMap.end()) + { + if (handler.add(set, *(i->second))) + { + break; + } + } + } + break; + } + case ruleRemove: + { + // Trying to remove a single item + if (!handler.remove(set, arg)) + { + // Failed. Maybe the argument references another group + const IDType other = arg; + typename MapType::iterator i = pMap.find(other); + if (i != pMap.end()) + { + if (handler.remove(set, *(i->second))) + { + break; + } + } + } + break; + } + case ruleFilter: + { + handler.applyFilter(set, arg); + break; + } + case ruleNone: + case ruleMax: + { + // Huh ?? + assert(false && "Should not be here !"); + break; + } + } + } + // Retrieving the size of the result set + opts.resultSize = handler.size(set); + logs.debug() << " > set :: " << opts.caption << ": applying " << opts.rules.size() + << " rules, got " << opts.resultSize << " items"; +} + +template +void Sets::rebuildIndexes() +{ + delete[] pByIndex; + delete[] pNameByIndex; + + if (!pMap.empty()) + { + pByIndex = new TypePtr[pMap.size()]; + pNameByIndex = new IDType[pMap.size()]; + const typename MapType::iterator end = pMap.end(); + uint index = 0; + for (typename MapType::iterator i = pMap.begin(); i != end; ++i) + { + pByIndex[index] = i->second; + pNameByIndex[index] = i->first; + ++index; + } + } + else + { + pByIndex = NULL; + pNameByIndex = NULL; + } +} + +template +template +inline bool Sets::hasOutput(const StringT& s) const +{ + // Assert, if a C* container can not be found at compile time + static_assert(Yuni::Traits::CString::valid); + + typename MapOptions::const_iterator i = pOptions.find(s); + return (i != pOptions.end()) ? i->second.output : false; +} + +template +inline bool Sets::hasOutput(const uint index) const +{ + return hasOutput(IDType(pNameByIndex[index])); +} + +template +template +inline uint Sets::resultSize(const StringT& s) const +{ + // Assert, if a C* container can not be found at compile time + static_assert(Yuni::Traits::CString::valid); + + typename MapOptions::const_iterator i = pOptions.find(s); + return (i != pOptions.end()) ? i->second.resultSize : 0; +} + +template +template +inline typename Sets::IDType Sets::caption(const StringT& s) const +{ + // Assert, if a C* container can not be found at compile time + static_assert(Yuni::Traits::CString::valid); + + typename MapOptions::const_iterator i = pOptions.find(s); + return (i != pOptions.end()) ? i->second.caption : IDType(); +} + +template +inline typename Sets::IDType Sets::caption(const uint i) const +{ + return caption(IDType(pNameByIndex[i])); +} + +template +inline uint Sets::resultSize(const uint index) const +{ + return resultSize(IDType(pNameByIndex[index])); +} + +template +inline uint Sets::size() const +{ + return (uint)pMap.size(); +} + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_SETS_HXX__ diff --git a/src/libs/antares/study/include/antares/study/simulation.h b/src/libs/antares/study/include/antares/study/simulation.h new file mode 100644 index 0000000000..b3ca6addd8 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/simulation.h @@ -0,0 +1,85 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_SIMULATION_H__ +#define __ANTARES_LIBS_STUDY_SIMULATION_H__ + +#include + +#include + +#include "fwd.h" + +namespace Antares +{ +namespace Data +{ +/*! +** \brief Set of settings for a simulation +*/ +class SimulationComments final +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + SimulationComments(Study& study); + + //! Destructor + ~SimulationComments() + { + } + + //@} + + /*! + ** \brief Load a simulation from a folder + ** + ** \return A non-zero value if succeeded, 0 otherwise + */ + bool loadFromFolder(const StudyLoadOptions& options); + + /*! + ** \brief Save settings to the appropriate folder + */ + bool saveToFolder(const AnyString& folder) const; + + void saveUsingWriter(Solver::IResultWriter& writer, const AnyString& folder) const; + + //! Get (in bytes) the amount of memory used by the class + uint64_t memoryUsage() const; + +public: + //! Comments + YString comments; + //! name + YString name; + +private: + Study& pStudy; + +}; // class SimulationComments + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_SIMULATION_H__ diff --git a/src/libs/antares/study/study.h b/src/libs/antares/study/include/antares/study/study.h similarity index 90% rename from src/libs/antares/study/study.h rename to src/libs/antares/study/include/antares/study/study.h index 73698e6b1a..03e2df8bed 100644 --- a/src/libs/antares/study/study.h +++ b/src/libs/antares/study/include/antares/study/study.h @@ -1,60 +1,52 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_STUDY_H__ #define __ANTARES_LIBS_STUDY_STUDY_H__ +#include + #include -#include -#include #include +#include #include +#include +#include +#include #include +#include "antares/antares/antares.h" +#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" +#include "antares/study/binding_constraint/BindingConstraintsRepository.h" -#include "../antares.h" -#include "../object/object.h" -#include "fwd.h" - -#include "simulation.h" -#include "parameters.h" +#include "area/store-timeseries-numbers.h" #include "binding_constraint/BindingConstraint.h" +#include "fwd.h" #include "header.h" -#include "version.h" -#include "sets.h" -#include "progression/progression.h" -#include "load-options.h" -#include #include "layerdata.h" -#include //TODO Collision -#include "area/store-timeseries-numbers.h" -#include "antares/study/binding_constraint/BindingConstraintsRepository.h" -#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" - -#include +#include "load-options.h" +#include "parameters.h" +#include "progression/progression.h" +#include "sets.h" +#include "simulation.h" +#include "version.h" namespace Antares::Data { @@ -63,7 +55,8 @@ namespace Antares::Data */ class UIRuntimeInfo; -class Study: public Yuni::NonCopyable, public IObject, public LayerData + +class Study: public Yuni::NonCopyable, public LayerData { public: using Ptr = std::shared_ptr; @@ -164,7 +157,7 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData ** This method does not have any effect except modifying ** internal variables (`folder`, `folderInput`, ...). */ - void relocate(AnyString newFolder); + void relocate(const std::string& newFolder); /*! ** \brief Load a study from a folder @@ -172,7 +165,7 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData ** \param path The path where data are located ** \return True if succeeded, false otherwise */ - bool loadFromFolder(const AnyString& path, const StudyLoadOptions& options); + bool loadFromFolder(const std::string& path, const StudyLoadOptions& options); /*! ** \brief Clear all ressources held by the study @@ -240,7 +233,8 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData ** \param name The name of the new area ** \return A pointer to a new area, or NULL if the operation failed */ - // TODO no need for the 2nd argument, remove it after the GUI has been removed, keeping the default value + // TODO no need for the 2nd argument, remove it after the GUI has been removed, keeping the + // default value Area* areaAdd(const AreaName& name, bool update = false); /*! @@ -427,22 +421,6 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData */ void getNumberOfCores(const bool forceParallel, const uint nbYearsParallelForced); - /*! - ** \brief In case hydro hot start is enabled, checking all conditions are met. - ** - ** If hydro hot start is enabled, check that : - ** - For all areas for which reservoir management is enabled : - ** + Their starting level is initialized on the same day - ** + This day is the first day of the simulation calendar - ** - The simulation lasts exactly one year - ** - All batches (or sets) of simultaneous years have the same size (obvious if a parallel run - *is not required : answer is yes). - ** - ** If these conditions are not met, some error message is raised, when attempting to run the - *study. - */ - bool checkHydroHotStart(); - /*! ** \brief Remove timeseries if ts-generator is enabled */ @@ -610,8 +588,9 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData ScenarioBuilder::Sets* scenarioRules = nullptr; //@} - Matrix scenarioHydroLevels; - + TimeSeries::TS scenarioInitialHydroLevels; + // Hydro Final Levels + TimeSeries::TS scenarioFinalHydroLevels; /*! ** \brief Runtime informations ** @@ -664,11 +643,6 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData void* cacheTSGenerator[timeSeriesCount]; //@} - /*! - ** \brief - */ - bool gotFatalError = false; - /*! ** \brief A non-zero value when the study will be used by the solver ** @@ -681,7 +655,7 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData //! \name Loading //@{ //! Load a study from a folder - bool internalLoadFromFolder(const YString& path, const StudyLoadOptions& options); + bool internalLoadFromFolder(const std::filesystem::path& path, const StudyLoadOptions& options); //! Load the study header bool internalLoadHeader(const YString& folder); //! Load all correlation matrices @@ -709,15 +683,14 @@ class Study: public Yuni::NonCopyable, public IObject, public LayerData */ extern YString StudyIconFile; -YString StudyCreateOutputPath(StudyMode mode, +YString StudyCreateOutputPath(SimulationMode mode, ResultFormat fmt, const YString& folder, const YString& label, int64_t startTime); } // namespace Antares::Data - -#include "study.hxx" #include "runtime.h" +#include "study.hxx" #endif /* __ANTARES_LIBS_STUDY_STUDY_H__ */ diff --git a/src/libs/antares/study/include/antares/study/study.hxx b/src/libs/antares/study/include/antares/study/study.hxx new file mode 100644 index 0000000000..9f0053d0a4 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/study.hxx @@ -0,0 +1,67 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_STUDY_HXX__ +#define __ANTARES_LIBS_STUDY_STUDY_HXX__ + +namespace Antares +{ +namespace Data +{ +inline bool Study::readonly() const +{ + return (parameters.readonly); +} + +template +inline void Study::storeTimeSeriesNumbers(Solver::IResultWriter& resultWriter) const +{ + storeTimeseriesNumbers(resultWriter, areas); +} + +template +inline void Study::destroyTSGeneratorData() +{ + switch (TS) + { + case TimeSeriesType::timeSeriesLoad: + destroyAllLoadTSGeneratorData(); + break; + case TimeSeriesType::timeSeriesSolar: + destroyAllSolarTSGeneratorData(); + break; + case TimeSeriesType::timeSeriesWind: + destroyAllWindTSGeneratorData(); + break; + case TimeSeriesType::timeSeriesHydro: + destroyAllHydroTSGeneratorData(); + break; + case TimeSeriesType::timeSeriesThermal: + destroyAllThermalTSGeneratorData(); + break; + default: + break; + } +} + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_STUDY_HXX__ diff --git a/src/libs/antares/study/ui-runtimeinfos.h b/src/libs/antares/study/include/antares/study/ui-runtimeinfos.h similarity index 79% rename from src/libs/antares/study/ui-runtimeinfos.h rename to src/libs/antares/study/include/antares/study/ui-runtimeinfos.h index 7a35ddf6bf..61409977b3 100644 --- a/src/libs/antares/study/ui-runtimeinfos.h +++ b/src/libs/antares/study/include/antares/study/ui-runtimeinfos.h @@ -1,37 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_UI_RUNTIME_INFOS_H__ #define __ANTARES_LIBS_STUDY_UI_RUNTIME_INFOS_H__ #include #include -#include "fwd.h" + +#include "antares/study/binding_constraint/BindingConstraintsRepository.h" + #include "area/area.h" #include "binding_constraint/BindingConstraint.h" +#include "fwd.h" namespace Antares { @@ -40,7 +37,8 @@ namespace Data class UIRuntimeInfo final { public: - using VectorByType = std::map; + using VectorByType = std::map; using ByOperatorAndType = std::map; public: @@ -50,10 +48,12 @@ class UIRuntimeInfo final ** \brief Constructor */ UIRuntimeInfo(Study& study); + //! Destructor ~UIRuntimeInfo() { } + //@} /*! @@ -92,6 +92,7 @@ class UIRuntimeInfo final assert(i < pLink.size()); return pLink[i]; } + const AreaLink* link(uint i) const { assert(i < pLink.size()); @@ -106,6 +107,7 @@ class UIRuntimeInfo final assert(i < pClusters.size()); return pClusters[i]; } + const ThermalCluster* cluster(uint i) const { assert(i < pClusters.size()); @@ -117,11 +119,13 @@ class UIRuntimeInfo final assert(i < pConstraint.size()); return pConstraint[i].get(); } + const BindingConstraint* constraint(uint i) const { assert(i < pConstraint.size()); return pConstraint[i].get(); } + uint constraintCount() const { return (uint)pConstraint.size(); diff --git a/src/libs/antares/study/variable-print-info.h b/src/libs/antares/study/include/antares/study/variable-print-info.h similarity index 82% rename from src/libs/antares/study/variable-print-info.h rename to src/libs/antares/study/include/antares/study/variable-print-info.h index a734648ecc..e609728f3d 100644 --- a/src/libs/antares/study/variable-print-info.h +++ b/src/libs/antares/study/include/antares/study/variable-print-info.h @@ -1,36 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_PRINT_POLICY_H__ #define __SOLVER_VARIABLE_PRINT_POLICY_H__ +#include #include #include -#include + #include #include #include @@ -55,8 +50,15 @@ class VariablePrintInfo uint getMaxColumnsCount(); void setMaxColumns(uint maxColumnsNumber); - bool isPrintedOnDataLevel(uint dataLevel) const { return dataLevel_ & dataLevel; }; - bool isPrintedOnFileLevel(uint fileLevel) const { return fileLevel_ & fileLevel; }; + bool isPrintedOnDataLevel(uint dataLevel) const + { + return dataLevel_ & dataLevel; + } + + bool isPrintedOnFileLevel(uint fileLevel) const + { + return fileLevel_ & fileLevel; + } private: // Is the variable printed ? @@ -70,7 +72,8 @@ class VariablePrintInfo // Which reports the output variable has columns in ? // Example : areas/values-.txt // dataLevel can be : areas, links, bindingConstraint - // fileLevel can be : values-.txt, details-.txt, id-.txt, ... + // fileLevel can be : values-.txt, details-.txt, + // id-.txt, ... uint dataLevel_ = 0; uint fileLevel_ = 0; }; @@ -124,6 +127,7 @@ class AllVariablesPrintInfo { return numberSelectedAreaVariables; } + uint getNbSelectedLinkVars() const { return numberSelectedLinkVariables; diff --git a/src/libs/antares/study/include/antares/study/version.h b/src/libs/antares/study/include/antares/study/version.h new file mode 100644 index 0000000000..4a1e5962cf --- /dev/null +++ b/src/libs/antares/study/include/antares/study/version.h @@ -0,0 +1,64 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include +#include + +namespace Antares::Data +{ +/*! +** \brief Version of a study +** +** \ingroup study +** \see CHANGELOG.txt +*/ +class StudyVersion +{ +public: + /// allows automatic members comparison + auto operator<=>(const StudyVersion&) const = default; + + constexpr StudyVersion() = default; + + constexpr StudyVersion(unsigned major, unsigned minor): + major_(major), + minor_(minor) + { + } + + ~StudyVersion() = default; + + bool isSupported(bool verbose) const; + + bool fromString(const std::string& versionStr); + + std::string toString() const; + + static StudyVersion latest(); + static StudyVersion unknown(); + +private: + unsigned major_ = 0; + unsigned minor_ = 0; +}; +} // namespace Antares::Data diff --git a/src/libs/antares/study/include/antares/study/xcast.h b/src/libs/antares/study/include/antares/study/xcast.h new file mode 100644 index 0000000000..e74a96ce83 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/xcast.h @@ -0,0 +1,26 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LIBS_STUDY_XCAST_H__ +#define __ANTARES_LIBS_STUDY_XCAST_H__ + +#include "xcast/xcast.h" + +#endif // __ANTARES_LIBS_STUDY_XCAST_H__ diff --git a/src/libs/antares/study/include/antares/study/xcast/xcast.h b/src/libs/antares/study/include/antares/study/xcast/xcast.h new file mode 100644 index 0000000000..e331287881 --- /dev/null +++ b/src/libs/antares/study/include/antares/study/xcast/xcast.h @@ -0,0 +1,218 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_XCAST_XCAST_H__ +#define __ANTARES_LIBS_STUDY_XCAST_XCAST_H__ + +#include + +#include +#include + +#include + +namespace Antares::Data +{ +class XCast final: private Yuni::NonCopyable +{ +public: + //! Vector + using Vector = std::vector; + //! Vector with the const qualifier + using VectorConst = std::vector; + + /*! + ** \brief All coefficients + */ + enum + { + dataCoeffAlpha = 0, + dataCoeffBeta, + dataCoeffGamma, + dataCoeffDelta, + dataCoeffTheta, + dataCoeffMu, + //! The maximum number of coefficients + dataMax, + }; + + /*! + ** \brief All available probability distribution + */ + enum Distribution + { + //! None + dtNone = 0, + //! The uniform distribution + dtUniform = 1, + //! The Beta distribution + dtBeta = 2, + //! The normal distribution + dtNormal = 3, + //! The Weibul distribution, of shape A + dtWeibullShapeA = 4, + //! The Gamma distribution, of shape A + dtGammaShapeA = 5, + //! The maximum number of distributions + dtMax + }; + + enum + { + //! Hard limit for the number of points of the transfer function + conversionMaxPoints = 100, + }; + + enum TSTranslationUse + { + //! Do not use the time-series average + tsTranslationNone = 0, + //! Add the time-series average before computing the transfer function + tsTranslationBeforeConversion, + //! Add the time-series average after computing the transfer function + tsTranslationAfterConversion, + }; + +public: + /*! + ** \brief Convert a distribution into its human readable representation + */ + static const char* DistributionToCString(Distribution d); + + /*! + ** \brief Convert a CString into a probability distribution + */ + static Distribution StringToDistribution(AnyString str); + + /*! + ** \brief Convert a probability distribution into its string id representation + */ + static const char* DistributionToNameID(Distribution d); + + /*! + ** \brief How to use the timeseries average + */ + static const char* TSTranslationUseToCString(TSTranslationUse use); + + static TSTranslationUse CStringToTSTranslationUse(const AnyString& str); + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Constructor + */ + XCast(TimeSeriesType ts); + /*! + ** \brief Destructor + */ + ~XCast(); + //@} + + /*! + ** \brief Reset to default values + */ + void resetToDefaultValues(); + + /*! + ** \brief Copy settings from another XCast struct + */ + void copyFrom(const XCast& rhs); + + /*! + ** \brief Load data from a folder + */ + bool loadFromFolder(const AnyString& folder); + + /*! + ** \brief Save data to a folder + */ + bool saveToFolder(const AnyString& folder) const; + + //! \name Memory management + //@{ + /*! + ** \brief Make sure that all data are loaded in memory + */ + bool forceReload(bool reload = false) const; + + /*! + ** \brief Mark the load data as modified + */ + void markAsModified() const; + + /*! + ** \brief Get the amount of memory currently used by the XCast data + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Estimate the amount of memory required by this class for a simulation + */ + + //@} + +public: + /*! + ** \brief Data required for XCast: coefficients (coeffMax x 12) + */ + Matrix data; + + /*! + ** \brief K (12x24) + */ + Matrix K; + + /*! + ** \brief Time-series average + */ + Matrix translation; + + //! How to use the timeseries average + TSTranslationUse useTranslation; + + //! The probability distribution to use + Distribution distribution; + + //! The installed capacity + double capacity; + + //! True to use the transfer function after the generation of the time-series + bool useConversion; + /*! + ** \brief The conversion function + ** + ** The first row gives the X-Coordinates, the second one the Y-Coordinates. + */ + Matrix conversion; + + //! The related time-series + const TimeSeriesType timeSeries; + +protected: + void resetTransferFunction(); + +}; // class XCast + +} // namespace Antares::Data + +#include "xcast.hxx" + +#endif // __ANTARES_LIBS_STUDY_XCAST_XCAST_H__ diff --git a/src/libs/antares/study/include/antares/study/xcast/xcast.hxx b/src/libs/antares/study/include/antares/study/xcast/xcast.hxx new file mode 100644 index 0000000000..e5072fb81e --- /dev/null +++ b/src/libs/antares/study/include/antares/study/xcast/xcast.hxx @@ -0,0 +1,39 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_XCAST_XCAST_HXX__ +#define __ANTARES_LIBS_STUDY_XCAST_XCAST_HXX__ + +#include + +namespace Antares +{ +namespace Data +{ +inline uint64_t XCast::memoryUsage() const +{ + return sizeof(XCast) + data.memoryUsage() + K.memoryUsage() + translation.memoryUsage() + + conversion.memoryUsage(); +} + +} // namespace Data +} // namespace Antares + +#endif // __ANTARES_LIBS_STUDY_XCAST_XCAST_HXX__ diff --git a/src/libs/antares/study/layerdata.cpp b/src/libs/antares/study/layerdata.cpp index c473176c38..781a807037 100644 --- a/src/libs/antares/study/layerdata.cpp +++ b/src/libs/antares/study/layerdata.cpp @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include +#include "antares/study/layerdata.h" + #include +#include +#include + #include -#include "layerdata.h" #include using namespace Yuni; @@ -67,7 +63,9 @@ void LayerData::loadLayers(const AnyString& filename) p = p->next; if (p) + { showAllLayer = p->value.to(); + } } return; } @@ -84,15 +82,15 @@ bool LayerData::saveLayers(const AnyString& filename) CString<256, true> data; data << "[layers]\n"; - for (const auto& [key, value] : layers) + for (const auto& [key, value]: layers) + { data << key << " = " << value << '\n'; + } data << "[activeLayer]\n"; - data << "activeLayerID" - << " = " << activeLayerID; + data << "activeLayerID" << " = " << activeLayerID; data << '\n'; - data << "showAllLayer" - << " = " << showAllLayer; + data << "showAllLayer" << " = " << showAllLayer; file << data; diff --git a/src/libs/antares/study/layerdata.h b/src/libs/antares/study/layerdata.h deleted file mode 100644 index 08d3df654d..0000000000 --- a/src/libs/antares/study/layerdata.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_LAYERDATA_H__ -#define __ANTARES_LIBS_STUDY_LAYERDATA_H__ - -#include -#include - -namespace Antares::Data -{ -/*! -** \brief Antares Study -*/ - -class LayerData -{ -public: - LayerData(size_t activeLayer, bool showLayer) : - activeLayerID(activeLayer), showAllLayer(showLayer) - { - } - - //! \name Layers - //@{ - //! All available layers - std::map layers; - //@} - size_t activeLayerID; - bool showAllLayer; - -protected: - bool saveLayers(const AnyString& filename); - void loadLayers(const AnyString& filename); -}; - -} // namespace Antares::Data - -#endif /* __ANTARES_LIBS_STUDY_LAYERDATA_H__ */ diff --git a/src/libs/antares/study/load-options.cpp b/src/libs/antares/study/load-options.cpp index ed9e57eded..b84b5a0a1a 100644 --- a/src/libs/antares/study/load-options.cpp +++ b/src/libs/antares/study/load-options.cpp @@ -1,84 +1,70 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "load-options.h" -#include +#include "antares/study/load-options.h" #include +#include -namespace Antares +namespace Antares::Data { -namespace Data -{ -StudyLoadOptions::StudyLoadOptions() : - nbYears(0), - prepareOutput(false), - loadOnlyNeeded(false), - forceYearByYear(false), - forceDerated(false), - noTimeseriesImportIntoInput(false), - simplexOptimizationRange(sorUnknown), - mpsToExport(false), - ignoreConstraints(false), - forceMode(stdmUnknown), - enableParallel(false), - forceParallel(false), - maxNbYearsInParallel(0), - usedByTheSolver(false), - ortoolsUsed(false) +StudyLoadOptions::StudyLoadOptions(): + nbYears(0), + prepareOutput(false), + loadOnlyNeeded(false), + forceYearByYear(false), + forceDerated(false), + noTimeseriesImportIntoInput(false), + simplexOptimizationRange(sorUnknown), + mpsToExport(false), + ignoreConstraints(false), + forceMode(SimulationMode::Unknown), + enableParallel(false), + forceParallel(false), + maxNbYearsInParallel(0), + usedByTheSolver(false) { } -void StudyLoadOptions::pushProgressLogs() const -{ - if (loadOnlyNeeded && progressTicks) - { - uint percent = progressTicks * 100 / progressTickCount; - if (percent < 100) - logs.info() << logMessage << " " << percent << '%'; - } -} - void StudyLoadOptions::checkForceSimulationMode() { - const uint number_of_enabled_force_options - = static_cast(forceExpansion) + static_cast(forceEconomy) - + static_cast(forceAdequacy); + const uint number_of_enabled_force_options = static_cast(forceExpansion) + + static_cast(forceEconomy) + + static_cast(forceAdequacy); if (number_of_enabled_force_options > 1) { throw Error::InvalidSimulationMode(); } if (forceExpansion) - forceMode = stdmExpansion; + { + forceMode = SimulationMode::Expansion; + } else if (forceEconomy) - forceMode = stdmEconomy; + { + forceMode = SimulationMode::Economy; + } else if (forceAdequacy) - forceMode = stdmAdequacy; + { + forceMode = SimulationMode::Adequacy; + } } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/load-options.h b/src/libs/antares/study/load-options.h deleted file mode 100644 index df655816ed..0000000000 --- a/src/libs/antares/study/load-options.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_SOLVER_LOAD_OPTIONS_H__ -#define __ANTARES_LIBS_SOLVER_LOAD_OPTIONS_H__ - -#include -#include -#include "parameters.h" - -namespace Antares -{ -namespace Data -{ -class StudyLoadOptions -{ -public: - //! \name Constructor - //@{ - //! Default constructor - StudyLoadOptions(); - //@} - - //! Push a new log entry according to the local progress data - void pushProgressLogs() const; - - void checkForceSimulationMode(); - -public: - //! The number of MC years (non-zero to force the value) - uint nbYears; - //! True to prepare the output folder - bool prepareOutput; - //! True to load only the strictly required data - bool loadOnlyNeeded; - //! Force the year-by-year flag - bool forceYearByYear; - //! Force the derated mode - bool forceDerated; - - //! No Timeseries import in the input - // This option might be useful for running old studies without upgrading - bool noTimeseriesImportIntoInput; - - //! Simplex optimization range - SimplexOptimization simplexOptimizationRange; - //! Mps files export asked - bool mpsToExport; - //! named problems - bool namedProblems = false; - //! Ignore all constraints - bool ignoreConstraints; - //! Simulation mode - StudyMode forceMode; - - //! Enables the parallel computation of MC years - bool enableParallel; - - //! Force a maximum number of MC years computed simultaneously - bool forceParallel; - uint maxNbYearsInParallel; - - //! A non-zero value if the data will be used for a simulation - bool usedByTheSolver; - - //! Force ortools use - bool ortoolsUsed; - //! THe solver name, sirius is the default - std::string ortoolsSolver = "sirius"; - - //! Temporary string for passing log message - mutable Yuni::String logMessage; - //! Porgression, tick count - mutable uint progressTickCount; - //! The current number of ticks - mutable uint progressTicks; - - //! Display version number and exit - bool displayVersion = false; - - //! True => display the list of OR-Tools solvers and exit - bool listSolvers = false; - - //! Simulation mode - bool forceExpansion = false; - bool forceEconomy = false; - bool forceAdequacy = false; - - YString studyFolder; - YString simulationName; -}; // class StudyLoadOptions - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_SOLVER_LOAD_OPTIONS_H__ diff --git a/src/libs/antares/study/load.cpp b/src/libs/antares/study/load.cpp index b93af9dcea..749d0d81ff 100644 --- a/src/libs/antares/study/load.cpp +++ b/src/libs/antares/study/load.cpp @@ -1,39 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "study.h" -#include "version.h" + #include -#include "scenario-builder/sets.h" -#include "ui-runtimeinfos.h" +#include "antares/study/scenario-builder/sets.h" +#include "antares/study/study.h" +#include "antares/study/ui-runtimeinfos.h" +#include "antares/study/version.h" using namespace Yuni; using Antares::Constants::nbHoursInAWeek; +namespace fs = std::filesystem; + #define SEP IO::Separator namespace Antares @@ -53,16 +50,16 @@ bool Study::internalLoadHeader(const String& path) // Informations about the study logs.info(); logs.notice() << "Preparing " << header.caption << "..."; - logs.info() << " detected version: " << header.version; + logs.info() << " detected study version: " << header.version.toString(); logs.info() << " from `" << path << '`'; logs.info(); return true; } -bool Study::loadFromFolder(const AnyString& path, const StudyLoadOptions& options) +bool Study::loadFromFolder(const std::string& path, const StudyLoadOptions& options) { - String normPath; - IO::Normalize(normPath, path); + fs::path normPath = path; + normPath = normPath.lexically_normal(); return internalLoadFromFolder(normPath, options); } @@ -71,21 +68,33 @@ bool Study::internalLoadIni(const String& path, const StudyLoadOptions& options) if (!internalLoadHeader(path)) { if (options.loadOnlyNeeded) + { return false; + } } // The simulation settings if (!simulationComments.loadFromFolder(options)) { if (options.loadOnlyNeeded) + { return false; + } } // Load the general data buffer.clear() << folderSettings << SEP << "generaldata.ini"; - if (!parameters.loadFromFile(buffer, header.version, options)) + bool errorWhileLoading = !parameters.loadFromFile(buffer, header.version); + + parameters.validateOptions(options); + + parameters.fixBadValues(); + + if (errorWhileLoading) { if (options.loadOnlyNeeded) + { return false; + } } // Load the layer data @@ -107,20 +116,21 @@ void Study::parameterFiller(const StudyLoadOptions& options) } if (options.loadOnlyNeeded && !parameters.timeSeriesToGenerate) + { // Nothing to refresh parameters.timeSeriesToRefresh = 0; + } // We can not run the simulation if the study folder is not in the latest // version and that we would like to re-importe the generated timeseries if (usedByTheSolver) { // We have time-series to import - StudyVersion studyVersion; - if (parameters.exportTimeSeriesInInput && studyVersion.isStudyLatestVersion(folder.c_str())) + if (parameters.exportTimeSeriesInInput && header.version != StudyVersion::latest()) { logs.info() << "Stochastic TS stored in input parametrized." - " Disabling Store in input because study is not at latest version" - "Prevents writing data in unsupported format at the study version"; + " Disabling Store in input because study is not at latest version." + " This prevents writing data in unsupported format at the study version"; parameters.exportTimeSeriesInInput = 0; } } @@ -143,28 +153,36 @@ void Study::parameterFiller(const StudyLoadOptions& options) // calendar update if (usedByTheSolver) - calendar.reset({parameters.dayOfThe1stJanuary, parameters.firstWeekday, parameters.firstMonthInYear, false}); + { + calendar.reset({parameters.dayOfThe1stJanuary, + parameters.firstWeekday, + parameters.firstMonthInYear, + false}); + } else - calendar.reset({parameters.dayOfThe1stJanuary, parameters.firstWeekday, parameters.firstMonthInYear, parameters.leapYear}); - - calendarOutput.reset({parameters.dayOfThe1stJanuary, parameters.firstWeekday, parameters.firstMonthInYear, parameters.leapYear}); + { + calendar.reset({parameters.dayOfThe1stJanuary, + parameters.firstWeekday, + parameters.firstMonthInYear, + parameters.leapYear}); + } - // In case hydro hot start is enabled, check all conditions are met. - // (has to be called after areas load and calendar building) - if (usedByTheSolver && !checkHydroHotStart()) - logs.error() << "hydro hot start is enabled, conditions are not met. Aborting"; + calendarOutput.reset({parameters.dayOfThe1stJanuary, + parameters.firstWeekday, + parameters.firstMonthInYear, + parameters.leapYear}); // Reducing memory footprint reduceMemoryUsage(); } -bool Study::internalLoadFromFolder(const String& path, const StudyLoadOptions& options) +bool Study::internalLoadFromFolder(const fs::path& path, const StudyLoadOptions& options) { // IO statistics Statistics::LogsDumper statisticsDumper; // Check if the path is correct - if (!IO::Directory::Exists(path)) + if (!fs::exists(path)) { logs.error() << path << ": The directory does not exist (or not enough privileges to read the folder)"; @@ -172,14 +190,14 @@ bool Study::internalLoadFromFolder(const String& path, const StudyLoadOptions& o } // Initialize all internal paths - relocate(path); + relocate(path.string()); // Reserving enough space in buffer to avoid several calls to realloc this->dataBuffer.reserve(4 * 1024 * 1024); // For matrices, reserving 4Mo this->bufferLoadingTS.reserve(2096); assert(this->bufferLoadingTS.capacity() > 0); - if (!internalLoadIni(path, options)) + if (!internalLoadIni(path.string(), options)) { return false; } @@ -193,7 +211,9 @@ bool Study::internalLoadFromFolder(const String& path, const StudyLoadOptions& o // In case parallel mode was not chosen, only 1 core is allowed if (!options.enableParallel && !options.forceParallel) + { maxNbYearsInParallel = 1; + } // End logical core -------- @@ -216,19 +236,19 @@ bool Study::internalLoadCorrelationMatrices(const StudyLoadOptions& options) { // Load if (!options.loadOnlyNeeded || timeSeriesLoad & parameters.timeSeriesToRefresh - || timeSeriesLoad & parameters.timeSeriesToGenerate) + || timeSeriesLoad & parameters.timeSeriesToGenerate) { buffer.clear() << folderInput << SEP << "load" << SEP << "prepro" << SEP - << "correlation.ini"; + << "correlation.ini"; preproLoadCorrelation.loadFromFile(*this, buffer); } // Solar if (!options.loadOnlyNeeded || timeSeriesSolar & parameters.timeSeriesToRefresh - || timeSeriesSolar & parameters.timeSeriesToGenerate) + || timeSeriesSolar & parameters.timeSeriesToGenerate) { buffer.clear() << folderInput << SEP << "solar" << SEP << "prepro" << SEP - << "correlation.ini"; + << "correlation.ini"; preproSolarCorrelation.loadFromFile(*this, buffer); } @@ -262,7 +282,8 @@ bool Study::internalLoadBindingConstraints(const StudyLoadOptions& options) // (actually internalLoadFromFolder) buffer.clear() << folderInput << SEP << "bindingconstraints"; bool r = bindingConstraints.loadFromFolder(*this, options, buffer); - if (r) { + if (r) + { r &= bindingConstraintsGroups.buildFrom(bindingConstraints); } return (!r && options.loadOnlyNeeded) ? false : r; @@ -271,7 +292,8 @@ bool Study::internalLoadBindingConstraints(const StudyLoadOptions& options) class SetHandlerAreas { public: - SetHandlerAreas(Study& study) : pStudy(study) + explicit SetHandlerAreas(Study& study): + pStudy(study) { } @@ -302,7 +324,9 @@ class SetHandlerAreas { auto end = otherSet.end(); for (auto i = otherSet.begin(); i != end; ++i) + { set.insert(*i); + } } return true; } @@ -337,7 +361,9 @@ class SetHandlerAreas { auto end = pStudy.areas.end(); for (auto i = pStudy.areas.begin(); i != end; ++i) + { set.insert(i->second); + } return true; } @@ -356,6 +382,7 @@ class SetHandlerAreas bool Study::internalLoadSets() { + const fs::path path = fs::path(folderInput.c_str()) / "areas" / "sets.ini"; // Set of areas logs.info(); logs.info() << "Loading sets of areas..."; @@ -364,7 +391,7 @@ bool Study::internalLoadSets() buffer.clear() << folderInput << SEP << "areas" << SEP << "sets.ini"; // Load the rules - if (setsOfAreas.loadFromFile(buffer)) + if (setsOfAreas.loadFromFile(path)) { // Apply the rules SetHandlerAreas handler(*this); @@ -389,21 +416,23 @@ bool Study::reloadXCastData() { // if changes are required, please update AreaListLoadFromFolderSingleArea() bool ret = true; - areas.each([&](Data::Area& area) { - assert(area.load.prepro); - assert(area.solar.prepro); - assert(area.wind.prepro); - - // Load - buffer.clear() << folderInput << SEP << "load" << SEP << "prepro" << SEP << area.id; - ret = area.load.prepro->loadFromFolder(buffer) && ret; - // Solar - buffer.clear() << folderInput << SEP << "solar" << SEP << "prepro" << SEP << area.id; - ret = area.solar.prepro->loadFromFolder(buffer) && ret; - // Wind - buffer.clear() << folderInput << SEP << "wind" << SEP << "prepro" << SEP << area.id; - ret = area.wind.prepro->loadFromFolder(buffer) && ret; - }); + areas.each( + [this, &ret](Data::Area& area) + { + assert(area.load.prepro); + assert(area.solar.prepro); + assert(area.wind.prepro); + + // Load + buffer.clear() << folderInput << SEP << "load" << SEP << "prepro" << SEP << area.id; + ret = area.load.prepro->loadFromFolder(buffer) && ret; + // Solar + buffer.clear() << folderInput << SEP << "solar" << SEP << "prepro" << SEP << area.id; + ret = area.solar.prepro->loadFromFolder(buffer) && ret; + // Wind + buffer.clear() << folderInput << SEP << "wind" << SEP << "prepro" << SEP << area.id; + ret = area.wind.prepro->loadFromFolder(buffer) && ret; + }); return ret; } diff --git a/src/libs/antares/study/output.cpp b/src/libs/antares/study/output.cpp index ad35c6519c..0409f2bb6e 100644 --- a/src/libs/antares/study/output.cpp +++ b/src/libs/antares/study/output.cpp @@ -1,53 +1,52 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "output.h" +#include "antares/study/output.h" + +#include + #include using namespace Yuni; +namespace fs = std::filesystem; + #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data { namespace // anonymous { -class OutputFolderIterator : public IO::Directory::IIterator +class OutputFolderIterator: public IO::Directory::IIterator { public: using IteratorType = IO::Directory::IIterator; using Flow = IO::Flow; public: - OutputFolderIterator(Data::Output::List& list) : pList(list) + OutputFolderIterator(Data::Output::List& list): + pList(list) { } + virtual ~OutputFolderIterator() { // For code robustness and to avoid corrupt vtable @@ -74,7 +73,9 @@ class OutputFolderIterator : public IO::Directory::IIterator { auto info = std::make_shared(parent); if (info->valid()) + { pList.push_back(info); + } return IO::flowSkip; } return IO::flowContinue; @@ -88,8 +89,12 @@ class OutputFolderIterator : public IO::Directory::IIterator } // anonymous namespace -Output::Output(const AnyString& folder) : - version(0), timestamp(0), mode(Data::stdmEconomy), menuID(-1), viewMenuID(-1), outputViewerID(-1) +Output::Output(const AnyString& folder): + timestamp(0), + mode(Data::SimulationMode::Economy), + menuID(-1), + viewMenuID(-1), + outputViewerID(-1) { loadFromFolder(folder); } @@ -97,7 +102,7 @@ Output::Output(const AnyString& folder) : bool Output::valid() const { // The outputs as we know them was first introduced in Antares 3.0 - return (uint)version <= (uint)Data::versionLatest; + return version <= Data::StudyVersion::latest(); } bool Output::loadFromFolder(const AnyString& folder) @@ -109,8 +114,7 @@ bool Output::loadFromFolder(const AnyString& folder) title.clear(); name.clear(); path.clear(); - version = 0; - mode = Data::stdmUnknown; + mode = Data::SimulationMode::Unknown; // Load the INI file in memory IniFile ini; @@ -135,33 +139,39 @@ bool Output::loadFromFolder(const AnyString& folder) { if (p->key == "version") { - version = p->value.to(); + version.fromString(p->value); // Early checks about the version - if (version > (uint)Data::versionLatest) + if (version > Data::StudyVersion::latest()) { - version = 0; + logs.warning() << "Study Version greater then supported"; return false; } } else { if (p->key == "title") + { title = p->value; + } else { if (p->key == "mode") { - StringToStudyMode(mode, p->value); + StringToSimulationMode(mode, p->value); } else { if (p->key == "timestamp") + { timestamp = p->value.to(); + } else { if (p->key == "name") + { name = p->value; + } } } } @@ -172,7 +182,9 @@ bool Output::loadFromFolder(const AnyString& folder) // Post-processing about the title if (not name.empty()) + { title << " - " << name; + } return true; } @@ -183,13 +195,12 @@ void Output::RetrieveListFromStudy(List& out, const Study& study) if (not study.folder.empty()) { - String folder; - folder << study.folder << SEP << "output"; + fs::path folder = fs::path(study.folder.c_str()) / "output"; - if (IO::Directory::Exists(folder)) + if (fs::exists(folder)) { OutputFolderIterator iterator(out); - iterator.add(folder); + iterator.add(folder.string()); iterator.start(); iterator.wait(15000); // 15s - arbitrary } @@ -206,5 +217,4 @@ void Output::RetrieveListFromStudy(List& out, const Study& study) } } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/output.h b/src/libs/antares/study/output.h deleted file mode 100644 index 5b3615c4a1..0000000000 --- a/src/libs/antares/study/output.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_OUTPUT_H__ -#define __ANTARES_LIBS_STUDY_OUTPUT_H__ - -#include -#include -#include -#include -#include -#include "study.h" - -namespace Antares -{ -namespace Data -{ -class Output final -{ -public: - //! Smartptr - using Ptr = std::shared_ptr; - //! List - using List = std::list; - //! Title - using Title = Yuni::CString<128, false>; - //! Name - using Name = Yuni::CString<128, false>; - - //! Map of study output info, ordered by their timestamp - using MapByTimestamp = std::map; - //! Map of study output info, ordered by their timestamp (desc) - using MapByTimestampDesc = std::map>; - -public: - /*! - ** \brief Retrieve the list of all available outputs - */ - static void RetrieveListFromStudy(List& out, const Study& study); - /*! - ** \brief Retrieve the list of all available outputs - */ - static void RetrieveListFromStudy(List& out, const Study::Ptr& study); - -public: - //! \name Constructor - //@{ - /*! - ** \brief Constructor, with an output folder - */ - explicit Output(const AnyString& folder); - //@} - - /*! - ** \brief Load data from an output folder - */ - bool loadFromFolder(const AnyString& folder); - - //! Get if the output folder previously loaded is valid - bool valid() const; - - //! Operator < - bool operator<(const Output& rhs) const; - -public: - //! Version of the solver used for the simulation - uint version; - //! Date/time when the simulation has been launched - int64_t timestamp; - //! Mode (economy/adequacy/other) - Data::StudyMode mode; - //! Tag for storing a wx menu id - int menuID; - //! Tag for storing a wx menu id (from the menu `output`) - int viewMenuID; - //! Tag for storing a wx menu id (for the output viewer) - int outputViewerID; - - //! Title to use for visual representation of the output - Title title; - //! Name - Name name; - //! Output folder - YString path; - -}; // class Output - -} // namespace Data -} // namespace Antares - -#include "output.hxx" - -#endif // __ANTARES_STUDY_LIBS_OUTPUT_H__ diff --git a/src/libs/antares/study/output.hxx b/src/libs/antares/study/output.hxx deleted file mode 100644 index 4efcf901ef..0000000000 --- a/src/libs/antares/study/output.hxx +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_OUTPUT_HXX__ -#define __ANTARES_LIBS_STUDY_OUTPUT_HXX__ - -namespace Antares -{ -namespace Data -{ -inline bool Output::operator<(const Output& rhs) const -{ - return not(title < rhs.title); -} - -inline void Output::RetrieveListFromStudy(List& out, const Study::Ptr& study) -{ - if (!study) - out.clear(); - else - RetrieveListFromStudy(out, *study); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_OUTPUT_HXX__ diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index c10519942f..628237bbef 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -1,81 +1,93 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/study/parameters.h" -#include -#include -#include -#include // std::tuple +#include +#include +#include +#include #include // std::list #include // std::stringstream +#include // std::tuple -#include "parameters.h" -#include -#include -#include -#include "load-options.h" -#include -#include "../solver/variable/economy/all.h" +#include + +#include #include -#include +#include +#include +#include "antares/antares/Enum.hpp" +#include "antares/antares/constants.h" +#include "antares/solver/variable/economy/all.h" +#include "antares/study/load-options.h" using namespace Yuni; namespace Antares::Data { -//! Hard coded maximum number of MC years -const uint maximumMCYears = 100000; static bool ConvertCStrToListTimeSeries(const String& value, uint& v) { v = 0; if (!value) + { return true; + } - value.words(" ,;\t\r\n", [&](const AnyString& element) -> bool { - ShortString16 word(element); - word.toLower(); - if (word == "load") - v |= timeSeriesLoad; - else if (word == "wind") - v |= timeSeriesWind; - else if (word == "hydro") - v |= timeSeriesHydro; - else if (word == "thermal") - v |= timeSeriesThermal; - else if (word == "solar") - v |= timeSeriesSolar; - else if (word == "renewables") - v |= timeSeriesRenewable; - else if (word == "ntc") - v |= timeSeriesTransmissionCapacities; - return true; - }); + value.words(" ,;\t\r\n", + [&v](const AnyString& element) + { + ShortString16 word(element); + word.toLower(); + if (word == "load") + { + v |= timeSeriesLoad; + } + else if (word == "wind") + { + v |= timeSeriesWind; + } + else if (word == "hydro") + { + v |= timeSeriesHydro; + } + else if (word == "thermal") + { + v |= timeSeriesThermal; + } + else if (word == "solar") + { + v |= timeSeriesSolar; + } + else if (word == "renewables") + { + v |= timeSeriesRenewable; + } + else if (word == "ntc") + { + v |= timeSeriesTransmissionCapacities; + } + return true; + }); return true; } @@ -112,11 +124,16 @@ static bool ConvertCStrToResultFormat(const AnyString& text, ResultFormat& out) out = legacyFilesDirectories; return true; } - if (s == "zip") // Using renewable clusters + if (s == "zip") { out = zipArchive; return true; } + if (s == "in-memory") + { + out = inMemory; + return true; + } logs.warning() << "parameters: invalid result format. Got '" << text << "'"; out = legacyFilesDirectories; @@ -132,17 +149,24 @@ static void ParametersSaveResultFormat(IniFile::Section* section, ResultFormat f case zipArchive: section->add(name, "zip"); break; + case inMemory: + section->add(name, "in-memory"); + break; default: section->add(name, "txt-files"); } } -bool StringToStudyMode(StudyMode& mode, CString<20, false> text) +bool StringToSimulationMode(SimulationMode& mode, CString<20, false> text) { if (!text) + { return false; + } if (text.size() == 1) + { return false; + } // Converting into lowercase text.toLower(); @@ -151,54 +175,47 @@ bool StringToStudyMode(StudyMode& mode, CString<20, false> text) if (text == "economy" || text == "economic") { // The term `economic` was mis-used in previous versions of antares (<3.4) - mode = stdmEconomy; + mode = SimulationMode::Economy; return true; } // Adequacy if (text == "adequacy") { - mode = stdmAdequacy; + mode = SimulationMode::Adequacy; return true; } // Expansion if (text == "expansion") { - mode = stdmExpansion; + mode = SimulationMode::Expansion; return true; } return false; } -const char* StudyModeToCString(StudyMode mode) +const char* SimulationModeToCString(SimulationMode mode) { switch (mode) { - case stdmEconomy: + case SimulationMode::Economy: return "Economy"; - case stdmAdequacy: + case SimulationMode::Adequacy: return "Adequacy"; - case stdmMax: - case stdmExpansion: - case stdmUnknown: + case SimulationMode::Expansion: + return "Expansion"; + default: return "Unknown"; } - return "Unknown"; } -Parameters::Parameters() : noOutput(false) -{ -} - -Parameters::~Parameters() = default; - bool Parameters::economy() const { - return mode == stdmEconomy; + return mode == SimulationMode::Economy; } bool Parameters::adequacy() const { - return mode == stdmAdequacy; + return mode == SimulationMode::Adequacy; } void Parameters::resetSeeds() @@ -207,20 +224,21 @@ void Parameters::resetSeeds() // For retro-compatibility, the wind ts-generator should produce the // same results than before 3.8. // It must have the same seed than before - auto increment = (unsigned)antaresSeedIncrement; - auto s = (unsigned)antaresSeedDefaultValue; + auto increment = antaresSeedIncrement; + auto s = antaresSeedDefaultValue; seed[seedTsGenWind] = s; // The same way for all others for (auto i = (uint)seedTsGenLoad; i != seedMax; ++i) + { seed[i] = (s += increment); + } } - void Parameters::resetPlayedYears(uint nbOfYears) { // Set the number of years - nbYears = std::min(nbOfYears, maximumMCYears); + nbYears = nbOfYears; // Reset the filter yearsFilter.resize(nbYears); @@ -230,9 +248,7 @@ void Parameters::resetPlayedYears(uint nbOfYears) void Parameters::reset() { // Mode - mode = stdmEconomy; - // Expansion - expansion = false; + mode = SimulationMode::Economy; // Calendar horizon.clear(); @@ -288,21 +304,17 @@ void Parameters::reset() readonly = false; synthesis = true; - // Initial reservoir levels - initialReservoirLevels.iniLevels = irlColdStart; - // Hydro heuristic policy hydroHeuristicPolicy.hhPolicy = hhpAccommodateRuleCurves; // Hydro pricing hydroPricing.hpMode = hpHeuristic; - allSetsHaveSameSize = true; // Shedding strategies power.fluctuations = lssFreeModulations; shedding.policy = shpShavePeaks; - unitCommitment.ucMode = ucHeuristic; + unitCommitment.ucMode = ucHeuristicFast; nbCores.ncMode = ncAvg; renewableGeneration.rgModelling = rgAggregated; @@ -333,9 +345,6 @@ void Parameters::reset() hydroDebug = false; - ortoolsUsed = false; - ortoolsSolver = "sirius"; - resultFormat = legacyFilesDirectories; // Adequacy patch parameters @@ -343,6 +352,8 @@ void Parameters::reset() // Initialize all seeds resetSeeds(); + + optOptions = Antares::Solver::Optimization::OptimizationOptions(); } bool Parameters::isTSGeneratedByPrepro(const TimeSeriesType ts) const @@ -355,41 +366,55 @@ static void ParametersSaveTimeSeries(IniFile::Section* s, const char* name, uint CString<60, false> v; if (value & timeSeriesLoad) + { v += "load"; + } if (value & timeSeriesHydro) { if (not v.empty()) + { v += ", "; + } v += "hydro"; } if (value & timeSeriesWind) { if (not v.empty()) + { v += ", "; + } v += "wind"; } if (value & timeSeriesThermal) { if (not v.empty()) + { v += ", "; + } v += "thermal"; } if (value & timeSeriesSolar) { if (not v.empty()) + { v += ", "; + } v += "solar"; } if (value & timeSeriesRenewable) { if (not v.empty()) + { v += ", "; + } v += "renewables"; } if (value & timeSeriesTransmissionCapacities) { if (!v.empty()) + { v += ", "; + } v += "ntc"; } s->add(name, v); @@ -406,22 +431,34 @@ static bool SGDIntLoadFamily_General(Parameters& d, return true; } if (key == "custom-scenario") + { return value.to(d.useCustomScenario); + } if (key == "derated") + { return value.to(d.derated); + } if (key == "first-month-in-year") + { return Date::StringToMonth(d.firstMonthInYear, value); + } if (key == "first.weekday") + { return Date::StringToDayOfTheWeek(d.firstWeekday, value); + } if (key == "geographic-trimming") + { return value.to(d.geographicTrimming); + } if (key == "generate") + { return ConvertCStrToListTimeSeries(value, d.timeSeriesToGenerate); + } if (key == "horizon") { @@ -432,21 +469,33 @@ static bool SGDIntLoadFamily_General(Parameters& d, // Same time-series if (key == "intra-modal") + { return ConvertCStrToListTimeSeries(value, d.intraModal); + } // Same time-series if (key == "inter-modal") + { return ConvertCStrToListTimeSeries(value, d.interModal); + } if (key == "improveunitsstartup") + { return true; // value.to(d.improveUnitsStartup); + } if (key == "january.1st") // after 4.3 + { return Date::StringToDayOfTheWeek(d.dayOfThe1stJanuary, value); + } if (key == "leapyear") + { return value.to(d.leapYear); + } if (key == "mode") - return StringToStudyMode(d.mode, value); + { + return StringToSimulationMode(d.mode, value); + } if (key == "nbyears") { @@ -460,123 +509,172 @@ static bool SGDIntLoadFamily_General(Parameters& d, return false; } if (key == "nbtimeseriesload") + { return value.to(d.nbTimeSeriesLoad); + } if (key == "nbtimeserieshydro") + { return value.to(d.nbTimeSeriesHydro); + } if (key == "nbtimeserieswind") + { return value.to(d.nbTimeSeriesWind); + } if (key == "nbtimeseriesthermal") + { return value.to(d.nbTimeSeriesThermal); + } if (key == "nbtimeseriessolar") + { return value.to(d.nbTimeSeriesSolar); + } + if (key == "nbtimeserieslinks") + { + // This data is among solver data, but is useless while running a simulation + // Only by TS generator. We skip it here (otherwise, we get a reading error). + return true; + } // Interval values if (key == "refreshintervalload") + { return value.to(d.refreshIntervalLoad); + } if (key == "refreshintervalhydro") + { return value.to(d.refreshIntervalHydro); + } if (key == "refreshintervalwind") + { return value.to(d.refreshIntervalWind); + } if (key == "refreshintervalthermal") + { return value.to(d.refreshIntervalThermal); + } if (key == "refreshintervalsolar") + { return value.to(d.refreshIntervalSolar); + } // What timeSeries to refresh ? if (key == "refreshtimeseries") + { return ConvertCStrToListTimeSeries(value, d.timeSeriesToRefresh); + } // readonly if (key == "readonly") + { return value.to(d.readonly); + } if (key == "simulation.start") { - uint day; - if (not value.to(day)) - return false; - if (day == 0) - day = 1; - else - { - if (day > 365) - day = 365; - --day; - } - d.simulationDays.first = day; - return true; + return value.to(d.simulationDays.first); } if (key == "simulation.end") { - uint day; - if (not value.to(day)) - return false; - if (day == 0) - day = 1; - else if (day > 365) - day = 365; - d.simulationDays.end = day; // not included - return true; + return value.to(d.simulationDays.end); } if (key == "thematic-trimming") + { return value.to(d.thematicTrimming); + } if (key == "user-playlist") + { return value.to(d.userPlaylist); + } if (key == "year-by-year") + { return value.to(d.yearByYear); + } return false; } + static bool SGDIntLoadFamily_Input(Parameters& d, const String& key, const String& value, const String&) { if (key == "import") + { return ConvertCStrToListTimeSeries(value, d.exportTimeSeriesInInput); + } return false; } + static bool SGDIntLoadFamily_Output(Parameters& d, const String& key, const String& value, const String&) { if (key == "archives") + { return ConvertCStrToListTimeSeries(value, d.timeSeriesToArchive); + } if (key == "storenewset") + { return value.to(d.storeTimeseriesNumbers); + } if (key == "synthesis") + { return value.to(d.synthesis); + } if (key == "hydro-debug") + { return value.to(d.hydroDebug); + } if (key == "result-format") + { return ConvertCStrToResultFormat(value, d.resultFormat); + } return false; } + static bool SGDIntLoadFamily_Optimization(Parameters& d, const String& key, const String& value, const String&) { if (key == "include-constraints") + { return value.to(d.include.constraints); + } if (key == "include-hurdlecosts") + { return value.to(d.include.hurdleCosts); + } if (key == "include-loopflowfee") // backward compatibility - return true; // value.to(d.include.loopFlowFee); + { + return true; // value.to(d.include.loopFlowFee); + } if (key == "include-tc-minstablepower") + { return value.to(d.include.thermal.minStablePower); + } if (key == "include-tc-min-ud-time") + { return value.to(d.include.thermal.minUPTime); + } if (key == "include-dayahead") + { return value.to(d.include.reserve.dayAhead); + } if (key == "include-strategicreserve") + { return value.to(d.include.reserve.strategic); + } if (key == "include-spinningreserve") + { return value.to(d.include.reserve.spinning); + } if (key == "include-primaryreserve") + { return value.to(d.include.reserve.primary); + } if (key == "include-exportmps") { @@ -591,7 +689,9 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, } if (key == "include-exportstructure") + { return value.to(d.include.exportStructure); + } if (key == "include-unfeasible-problem-behavior") { bool result = true; @@ -599,8 +699,8 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, try { - d.include.unfeasibleProblemBehavior - = Enum::fromString(string); + d.include.unfeasibleProblemBehavior = Enum::fromString( + string); } catch (AssertionError& ex) { @@ -626,8 +726,14 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, { return stringToGlobalTransmissionCapacities(value, d.transmissionCapacities); } + + if (key == "solver-logs") + { + return value.to(d.optOptions.solverLogs); + } return false; } + static bool SGDIntLoadFamily_AdqPatch(Parameters& d, const String& key, const String& value, @@ -667,19 +773,6 @@ static bool SGDIntLoadFamily_OtherPreferences(Parameters& d, d.hydroPricing.hpMode = hpHeuristic; return false; } - if (key == "initial-reservoir-levels") - { - auto iniLevels = StringToInitialReservoirLevels(value); - if (iniLevels != irlUnknown) - { - d.initialReservoirLevels.iniLevels = iniLevels; - return true; - } - logs.warning() << "parameters: invalid initital reservoir levels mode. Got '" << value - << "'. reset to cold start mode."; - d.initialReservoirLevels.iniLevels = irlColdStart; - return false; - } if (key == "number-of-cores-mode") { @@ -730,25 +823,31 @@ static bool SGDIntLoadFamily_OtherPreferences(Parameters& d, } logs.warning() << "parameters: invalid unit commitment mode. Got '" << value << "'. reset to fast mode"; - d.unitCommitment.ucMode = ucHeuristic; + d.unitCommitment.ucMode = ucHeuristicFast; return false; } // Renewable generation modelling if (key == "renewable-generation-modelling") + { return ConvertStringToRenewableGenerationModelling(value, d.renewableGeneration.rgModelling); + } return false; } + static bool SGDIntLoadFamily_AdvancedParameters(Parameters& d, const String& key, const String& value, const String&) { if (key == "accuracy-on-correlation") + { return ConvertCStrToListTimeSeries(value, d.timeSeriesAccuracyOnCorrelation); + } return false; } + static bool SGDIntLoadFamily_Playlist(Parameters& d, const String& key, const String& value, @@ -760,12 +859,16 @@ static bool SGDIntLoadFamily_Playlist(Parameters& d, if (mode) { for (uint i = 0; i != d.nbYears; ++i) + { d.yearsFilter[i] = true; + } } else { for (uint i = 0; i != d.nbYears; ++i) + { d.yearsFilter[i] = false; + } } return true; } @@ -775,7 +878,9 @@ static bool SGDIntLoadFamily_Playlist(Parameters& d, if (value.to(y)) { if (y < d.nbYears) + { d.yearsFilter[y] = true; + } return true; } return false; @@ -786,7 +891,9 @@ static bool SGDIntLoadFamily_Playlist(Parameters& d, if (value.to(y)) { if (y < d.nbYears) + { d.yearsFilter[y] = false; + } return true; } return false; @@ -836,11 +943,28 @@ static bool SGDIntLoadFamily_Playlist(Parameters& d, << value << "'. Value not used"; return false; } - return false; } return false; } +static bool deprecatedVariable(std::string var) +{ + static const std::vector STSGroups_legacy = { + "psp_open_level", "psp_closed_level", "pondage_level", + "battery_level", "other1_level", "other2_level", + "other3_level", "other4_level", "other5_level", + + "psp_open_injection", "psp_closed_injection", "pondage_injection", + "battery_injection", "other1_injection", "other2_injection", + "other3_injection", "other4_injection", "other5_injection", + + "psp_open_withdrawal", "psp_closed_withdrawal", "pondage_withdrawal", + "battery_withdrawal", "other1_withdrawal", "other2_withdrawal", + "other3_withdrawal", "other4_withdrawal", "other5_withdrawal"}; + boost::to_lower(var); + return std::ranges::find(STSGroups_legacy, var) != STSGroups_legacy.end(); +} + static bool SGDIntLoadFamily_VariablesSelection(Parameters& d, const String& key, const String& value, @@ -854,6 +978,12 @@ static bool SGDIntLoadFamily_VariablesSelection(Parameters& d, } if (key == "select_var +" || key == "select_var -") { + if (deprecatedVariable(value.to())) + { + logs.warning() << "Output variable `" << original + << "` no longer exists and has been ignored"; + return true; + } // Check if the read output variable exists if (not d.variablesPrintInfo.exists(value.to())) { @@ -867,6 +997,7 @@ static bool SGDIntLoadFamily_VariablesSelection(Parameters& d, } return false; } + static bool SGDIntLoadFamily_SeedsMersenneTwister(Parameters& d, const String& key, const String& value, @@ -878,17 +1009,29 @@ static bool SGDIntLoadFamily_SeedsMersenneTwister(Parameters& d, { // This block is kept for compatibility with very old studies if (key == "seed_load") + { return value.to(d.seed[seedTsGenLoad]); + } if (key == "seed_wind") + { return value.to(d.seed[seedTsGenWind]); + } if (key == "seed_hydro") + { return value.to(d.seed[seedTsGenHydro]); + } if (key == "seed_thermal") + { return value.to(d.seed[seedTsGenThermal]); + } if (key == "seed_solar") + { return value.to(d.seed[seedTsGenSolar]); + } if (key == "seed_timeseriesnumbers") + { return value.to(d.seed[seedTimeseriesNumbers]); + } } else { @@ -897,49 +1040,89 @@ static bool SGDIntLoadFamily_SeedsMersenneTwister(Parameters& d, for (uint sd = 0; sd != (uint)seedMax; ++sd) { if (SeedToID((SeedIndex)sd) == key) + { return value.to(d.seed[sd]); + } + } + if (key == "seed-tsgen-links") + { + return true; // Useless for solver, belongs to TS generator } } } return false; } + static bool SGDIntLoadFamily_Legacy(Parameters& d, const String& key, const String& value, const String&, - uint version) + const StudyVersion& version) { // Comparisons kept for compatibility reasons // Same time-series if (key == "correlateddraws") + { return ConvertCStrToListTimeSeries(value, d.intraModal); + } // Scenario builder if (key == "custom-ts-numbers") + { return value.to(d.useCustomScenario); + } - if (key == "filtering" && version < 710) + if (key == "filtering" && version < StudyVersion(7, 1)) + { return value.to(d.geographicTrimming); + } // Custom set if (key == "customset") + { return true; // value ignored + } if (key == "shedding-strategy") // Was never used + { return true; + } if (key == "day-ahead-reserve-management") // ignored since 8.4 + { return true; + } if (key == "link-type") // ignored since 8.5.2 + { return true; + } if (key == "adequacy-block-size") // ignored since 8.5 + { return true; + } // deprecated but needed for testing old studies if (key == "include-split-exported-mps") + { return true; + } + + if (key == "initial-reservoir-levels") // ignored since 9.2 + { + if (version >= StudyVersion(9, 2)) + { + logs.warning() + << "Option initial-reservoir-levels is deprecated, please remove it from the study"; + } + else if (value == "hot start") + { + logs.warning() + << "Hydro hot start not supported with this solver, please use a version < 9.2"; + } + return true; + } return false; } @@ -950,28 +1133,29 @@ bool firstKeyLetterIsValid(const String& name) return (firstLetter >= 'a' && firstLetter <= 'z'); } -bool Parameters::loadFromINI(const IniFile& ini, uint version, const StudyLoadOptions& options) +bool Parameters::loadFromINI(const IniFile& ini, const StudyVersion& version) { // Reset inner data reset(); + // A temporary buffer, used for the values in lowercase using Callback = bool (*)( - Parameters&, // [out] Parameter object to load the data into - const String&, // [in] Key, comes left to the '=' sign in the .ini file - const String&, // [in] Lowercase value, comes right to the '=' sign in the .ini file + Parameters&, // [out] Parameter object to load the data into + const String&, // [in] Key, comes left to the '=' sign in the .ini file + const String&, // [in] Lowercase value, comes right to the '=' sign in the .ini file const String&); // [in] Raw value as writtent right to the '=' sign in the .ini file - static const std::map sectionAssociatedToKeysProcess - = {{"general", &SGDIntLoadFamily_General}, - {"input", &SGDIntLoadFamily_Input}, - {"output", &SGDIntLoadFamily_Output}, - {"optimization", &SGDIntLoadFamily_Optimization}, - {"adequacy patch", &SGDIntLoadFamily_AdqPatch}, - {"other preferences", &SGDIntLoadFamily_OtherPreferences}, - {"advanced parameters", &SGDIntLoadFamily_AdvancedParameters}, - {"playlist", &SGDIntLoadFamily_Playlist}, - {"variables selection", &SGDIntLoadFamily_VariablesSelection}, - {"seeds - mersenne twister", &SGDIntLoadFamily_SeedsMersenneTwister}}; + static const std::map sectionAssociatedToKeysProcess = { + {"general", &SGDIntLoadFamily_General}, + {"input", &SGDIntLoadFamily_Input}, + {"output", &SGDIntLoadFamily_Output}, + {"optimization", &SGDIntLoadFamily_Optimization}, + {"adequacy patch", &SGDIntLoadFamily_AdqPatch}, + {"other preferences", &SGDIntLoadFamily_OtherPreferences}, + {"advanced parameters", &SGDIntLoadFamily_AdvancedParameters}, + {"playlist", &SGDIntLoadFamily_Playlist}, + {"variables selection", &SGDIntLoadFamily_VariablesSelection}, + {"seeds - mersenne twister", &SGDIntLoadFamily_SeedsMersenneTwister}}; Callback handleAllKeysInSection; // Foreach section on the ini file... @@ -994,9 +1178,13 @@ bool Parameters::loadFromINI(const IniFile& ini, uint version, const StudyLoadOp for (const IniFile::Property* p = section->firstProperty; p; p = p->next) { if (p->key.empty()) + { continue; + } if (!firstKeyLetterIsValid(p->key)) + { continue; + } // We convert the key and the value into the lower case format String value = p->value; value.toLower(); @@ -1015,89 +1203,38 @@ bool Parameters::loadFromINI(const IniFile& ini, uint version, const StudyLoadOp } } - // forcing value - if (options.nbYears != 0) - { - if (options.nbYears > nbYears) - { - // The variable `yearsFilter` must be enlarged - yearsFilter.resize(options.nbYears, false); - } - nbYears = options.nbYears; - - // Resize years weight (add or remove item) - if (yearsWeight.size() != nbYears) - { - yearsWeight.resize(nbYears, 1.f); - } - } - - // Simulation mode - // ... Expansion - if (mode == stdmExpansion) - { - mode = stdmEconomy; - expansion = true; - } - - // ... Enforcing simulation mode - if (options.forceMode != stdmUnknown) - { - if (options.forceMode == stdmExpansion) - { - mode = stdmEconomy; - expansion = true; - } - else - mode = options.forceMode; - - logs.info() << " forcing the simulation mode " << StudyModeToCString(mode); - assert(mode != stdmMax && "Invalid simulation mode"); - } - else - logs.info() << " simulation mode: " << StudyModeToCString(mode); - - if (options.forceDerated) - derated = true; - - // Define ortools parameters from options - ortoolsUsed = options.ortoolsUsed; - ortoolsSolver = options.ortoolsSolver; - - namedProblems = options.namedProblems; - - // Attempt to fix bad values if any - fixBadValues(); - fixRefreshIntervals(); fixGenRefreshForNTC(); - // Specific action before launching a simulation - if (options.usedByTheSolver) - prepareForSimulation(options); - - if (options.mpsToExport || options.namedProblems) - { - this->include.exportMPS = mpsExportStatus::EXPORT_BOTH_OPTIMS; - } - // We currently always returns true to not block any loading process // Anyway we already have reported all problems return true; } +void Parameters::handleOptimizationOptions(const StudyLoadOptions& options) +{ + // Options only set from the command-line + optOptions.ortoolsUsed = options.optOptions.ortoolsUsed; + optOptions.ortoolsSolver = options.optOptions.ortoolsSolver; + optOptions.solverParameters = options.optOptions.solverParameters; + + // Options that can be set both in command-line and file + optOptions.solverLogs = options.optOptions.solverLogs || optOptions.solverLogs; +} + void Parameters::fixRefreshIntervals() { - using T = std:: - tuple; + using T = std::tuple; const std::list timeSeriesToCheck = {{refreshIntervalLoad, timeSeriesLoad, "load"}, {refreshIntervalSolar, timeSeriesSolar, "solar"}, {refreshIntervalHydro, timeSeriesHydro, "hydro"}, {refreshIntervalWind, timeSeriesWind, "wind"}, {refreshIntervalThermal, timeSeriesThermal, "thermal"}}; - for (const auto& [refreshInterval, ts, label] : timeSeriesToCheck) + for (const auto& [refreshInterval, ts, label]: timeSeriesToCheck) { if (ts & timeSeriesToRefresh && 0 == refreshInterval) { @@ -1139,29 +1276,89 @@ void Parameters::fixBadValues() resetPlayedYears(1); resetYearsWeigth(); } - else - { - // Nb years - if (nbYears > maximumMCYears) - { - // The maximal amount of years is an hard-coded value - // If some changes are needed, please check in the same time the assert - // in the routine MatrixResize() - logs.error() << "The number of MC years is too high (>" << (uint)maximumMCYears << ")"; - nbYears = maximumMCYears; - } - } if (!nbTimeSeriesLoad) + { nbTimeSeriesLoad = 1; + } if (!nbTimeSeriesThermal) + { nbTimeSeriesThermal = 1; + } if (!nbTimeSeriesHydro) + { nbTimeSeriesHydro = 1; + } if (!nbTimeSeriesWind) + { nbTimeSeriesWind = 1; + } if (!nbTimeSeriesSolar) + { nbTimeSeriesSolar = 1; + } + + if (simulationDays.first == 0) + { + simulationDays.first = 1; + } + else + { + simulationDays.first = std::clamp(simulationDays.first, 1u, 365u); + --simulationDays.first; // value between 0 and 364 for edge cases + } + + simulationDays.end = std::clamp(simulationDays.end, 1u, 365u); +} + +void Parameters::validateOptions(const StudyLoadOptions& options) +{ + if (options.forceDerated) + { + derated = true; + } + // forcing value + if (options.nbYears != 0) + { + if (options.nbYears > nbYears) + { + // The variable `yearsFilter` must be enlarged + yearsFilter.resize(options.nbYears, false); + } + nbYears = options.nbYears; + + // Resize years weight (add or remove item) + if (yearsWeight.size() != nbYears) + { + yearsWeight.resize(nbYears, 1.f); + } + } + + // Simulation mode + // ... Enforcing simulation mode + if (options.forceMode != SimulationMode::Unknown) + { + mode = options.forceMode; + logs.info() << " forcing the simulation mode " << SimulationModeToCString(mode); + } + else + { + logs.info() << " simulation mode: " << SimulationModeToCString(mode); + } + // Specific action before launching a simulation + if (options.usedByTheSolver) + { + prepareForSimulation(options); + } + + if (options.mpsToExport || options.namedProblems) + { + this->include.exportMPS = mpsExportStatus::EXPORT_BOTH_OPTIMS; + } + + namedProblems = options.namedProblems; + + handleOptimizationOptions(options); } uint64_t Parameters::memoryUsage() const @@ -1191,6 +1388,7 @@ std::vector Parameters::getYearsWeight() const return result; } + float Parameters::getYearsWeightSum() const { float result = 0.f; @@ -1275,7 +1473,9 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) for (uint i = 0; i < nbYears; ++i) { if (yearsFilter[i]) + { ++effectiveNbYears; + } } switch (effectiveNbYears) { @@ -1344,22 +1544,24 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) std::vector excluded_vars; renewableGeneration.addExcludedVariables(excluded_vars); adqPatchParams.addExcludedVariables(excluded_vars); + unitCommitment.addExcludedVariables(excluded_vars); variablesPrintInfo.prepareForSimulation(thematicTrimming, excluded_vars); switch (mode) { - case stdmEconomy: - case stdmAdequacy: + case SimulationMode::Economy: + case SimulationMode::Adequacy: + case SimulationMode::Expansion: { // The year-by-year mode might have been requested from the command line if (options.forceYearByYear) + { yearByYear = true; + } break; } - case stdmUnknown: - case stdmExpansion: - case stdmMax: + case SimulationMode::Unknown: { // The mode year-by-year can not be enabled in adequacy yearByYear = false; @@ -1385,15 +1587,25 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) { // Removing `refresh` if (!(timeSeriesToGenerate & timeSeriesLoad)) + { timeSeriesToRefresh &= ~timeSeriesLoad; + } if (!(timeSeriesToGenerate & timeSeriesSolar)) + { timeSeriesToRefresh &= ~timeSeriesSolar; + } if (!(timeSeriesToGenerate & timeSeriesWind)) + { timeSeriesToRefresh &= ~timeSeriesWind; + } if (!(timeSeriesToGenerate & timeSeriesHydro)) + { timeSeriesToRefresh &= ~timeSeriesHydro; + } if (!(timeSeriesToGenerate & timeSeriesThermal)) + { timeSeriesToRefresh &= ~timeSeriesThermal; + } // Force mode refresh if the timeseries must be regenerated if (timeSeriesToGenerate & timeSeriesLoad && !(timeSeriesToRefresh & timeSeriesLoad)) @@ -1429,48 +1641,85 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) exportTimeSeriesInInput = 0; } - if (expansion) + if (mode == SimulationMode::Expansion) + { logs.info() << " :: enabling expansion"; + } if (yearByYear) + { logs.info() << " :: enabling the 'year-by-year' mode"; + } if (derated) + { logs.info() << " :: enabling the 'derated' mode"; + } if (userPlaylist) + { logs.info() << " :: enabling the user playlist"; + } if (thematicTrimming) + { logs.info() << " :: enabling the user variable selection"; + } if (useCustomScenario) + { logs.info() << " :: enabling the custom build mode"; + } if (geographicTrimming) + { logs.info() << " :: enabling filtering by file"; + } if (!include.constraints) + { logs.info() << " :: ignoring binding constraints"; + } if (!include.reserve.dayAhead) + { logs.info() << " :: ignoring day ahead reserves"; + } if (!include.reserve.primary) + { logs.info() << " :: ignoring primary reserves"; + } if (!include.reserve.strategic) + { logs.info() << " :: ignoring strategic reserves"; + } if (!include.reserve.spinning) + { logs.info() << " :: ignoring spinning reserves"; + } if (!include.thermal.minStablePower) + { logs.info() << " :: ignoring min stable power for thermal clusters"; + } if (!include.thermal.minUPTime) + { logs.info() << " :: ignoring min up/down time for thermal clusters"; + } if (include.exportMPS == mpsExportStatus::NO_EXPORT) + { logs.info() << " :: ignoring export mps"; + } if (!adqPatchParams.enabled) + { logs.info() << " :: ignoring adequacy patch"; + } if (!include.exportStructure) + { logs.info() << " :: ignoring export structure"; + } if (!include.hurdleCosts) + { logs.info() << " :: ignoring hurdle costs"; + } // Indicate ortools solver used - if (ortoolsUsed) + if (options.optOptions.ortoolsUsed) { - logs.info() << " :: ortools solver " << ortoolsSolver << " used for problem resolution"; + logs.info() << " :: ortools solver " << options.optOptions.ortoolsSolver + << " used for problem resolution"; } // indicated that Problems will be named @@ -1478,6 +1727,8 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) { logs.info() << " :: The problems will contain named variables and constraints"; } + // indicated whether solver logs will be printed + logs.info() << " :: Printing solver logs : " << (optOptions.solverLogs ? "True" : "False"); } void Parameters::resetPlaylist(uint nbOfYears) @@ -1493,13 +1744,7 @@ void Parameters::saveToINI(IniFile& ini) const auto* section = ini.addSection("general"); // Mode - if (expansion && mode == stdmEconomy) - section->add("mode", "Expansion"); - else - { - section->add("mode", StudyModeToCString(mode)); - expansion = false; - } + section->add("mode", SimulationModeToCString(mode)); // Calendar section->add("horizon", horizon); @@ -1519,7 +1764,9 @@ void Parameters::saveToINI(IniFile& ini) const section->add("thematic-trimming", thematicTrimming); section->add("geographic-trimming", geographicTrimming); if (not activeRulesScenario.empty()) + { section->add("active-rules-scenario", activeRulesScenario); + } // Time series ParametersSaveTimeSeries(section, "generate", timeSeriesToGenerate); @@ -1555,7 +1802,9 @@ void Parameters::saveToINI(IniFile& ini) const section->add("synthesis", synthesis); section->add("storeNewSet", storeTimeseriesNumbers); if (hydroDebug) + { section->add("hydro-debug", hydroDebug); + } ParametersSaveTimeSeries(section, "archives", timeSeriesToArchive); ParametersSaveResultFormat(section, resultFormat); } @@ -1593,6 +1842,7 @@ void Parameters::saveToINI(IniFile& ini) const // Unfeasible problem behavior section->add("include-unfeasible-problem-behavior", Enum::toString(include.unfeasibleProblemBehavior)); + section->add("solver-logs", optOptions.solverLogs); } // Adequacy patch @@ -1601,8 +1851,6 @@ void Parameters::saveToINI(IniFile& ini) const // Other preferences { auto* section = ini.addSection("other preferences"); - section->add("initial-reservoir-levels", - InitialReservoirLevelsToCString(initialReservoirLevels.iniLevels)); section->add("hydro-heuristic-policy", HydroHeuristicPolicyToCString(hydroHeuristicPolicy.hhPolicy)); section->add("hydro-pricing-mode", HydroPricingModeToCString(hydroPricing.hpMode)); @@ -1618,8 +1866,9 @@ void Parameters::saveToINI(IniFile& ini) const { auto* section = ini.addSection("advanced parameters"); // Accuracy on correlation - ParametersSaveTimeSeries( - section, "accuracy-on-correlation", timeSeriesAccuracyOnCorrelation); + ParametersSaveTimeSeries(section, + "accuracy-on-correlation", + timeSeriesAccuracyOnCorrelation); } // User's playlist @@ -1630,7 +1879,9 @@ void Parameters::saveToINI(IniFile& ini) const for (uint i = 0; i != nbYears; ++i) { if (yearsFilter[i]) + { ++effNbYears; + } weightEnabled |= yearsWeight[i] != 1.f; } @@ -1649,7 +1900,9 @@ void Parameters::saveToINI(IniFile& ini) const for (uint i = 0; i != nbYears; ++i) { if (yearsFilter[i]) + { section->add("playlist_year +", i); + } } } else @@ -1657,7 +1910,9 @@ void Parameters::saveToINI(IniFile& ini) const for (uint i = 0; i != nbYears; ++i) { if (!yearsFilter[i]) + { section->add("playlist_year -", i); + } } } @@ -1685,13 +1940,17 @@ void Parameters::saveToINI(IniFile& ini) const if (nb_selected_vars <= (nb_tot_vars / 2)) { section->add("selected_vars_reset", "false"); - for (auto& name : variablesPrintInfo.namesOfEnabledVariables()) + for (auto& name: variablesPrintInfo.namesOfEnabledVariables()) + { section->add("select_var +", name); + } } else { - for (auto& name : variablesPrintInfo.namesOfDisabledVariables()) + for (auto& name: variablesPrintInfo.namesOfDisabledVariables()) + { section->add("select_var -", name); + } } } } @@ -1700,18 +1959,20 @@ void Parameters::saveToINI(IniFile& ini) const { auto* section = ini.addSection("seeds - Mersenne Twister"); for (uint sd = 0; sd != (uint)seedMax; ++sd) + { section->add(SeedToID((SeedIndex)sd), seed[sd]); + } } } -bool Parameters::loadFromFile(const AnyString& filename, - uint version, - const StudyLoadOptions& options) +bool Parameters::loadFromFile(const AnyString& filename, const StudyVersion& version) { // Loading the INI file IniFile ini; if (ini.open(filename)) - return loadFromINI(ini, version, options); + { + return loadFromINI(ini, version); + } // Error otherwise reset(); @@ -1792,4 +2053,25 @@ bool Parameters::RenewableGeneration::isClusters() const { return rgModelling == Antares::Data::rgClusters; } + +// Some variables rely on dual values & marginal costs +void Parameters::UCMode::addExcludedVariables(std::vector& out) const +{ + // These variables rely on dual values & marginal costs + // these don't really make sense for MILP problems + // TODO : solve a LP problem with fixed values for integer variables + // extract values for dual variables & marginal costs from LP problem + const static std::vector milpExclude = {{"MARG. COST"}, + {"BC. MARG. COST"}, + {"CONG. FEE (ALG.)"}, + {"CONG. FEE (ABS.)"}, + {"MRG. PRICE"}, + {"STS Cashflow By Cluster"}, + {"Profit by plant"}}; + + if (ucMode == ucMILP) + { + out.insert(out.end(), milpExclude.begin(), milpExclude.end()); + } +} } // namespace Antares::Data diff --git a/src/libs/antares/study/parameters/adq-patch-params.cpp b/src/libs/antares/study/parameters/adq-patch-params.cpp index 4b6d9b33fa..99d0d0db33 100644 --- a/src/libs/antares/study/parameters/adq-patch-params.cpp +++ b/src/libs/antares/study/parameters/adq-patch-params.cpp @@ -1,9 +1,28 @@ -#include "adq-patch-params.h" -#include - -#include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/study/parameters/adq-patch-params.h" #include +#include +#include namespace Antares::Data::AdequacyPatch { @@ -21,18 +40,26 @@ void LocalMatching::reset() bool LocalMatching::updateFromKeyValue(const Yuni::String& key, const Yuni::String& value) { if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step") + { return value.to(setToZeroOutsideInsideLinks); + } if (key == "set-to-null-ntc-between-physical-out-for-first-step") + { return value.to(setToZeroOutsideOutsideLinks); + } if (key == "enable-first-step") + { return value.to(enabled); + } return false; } void LocalMatching::addProperties(IniFile::Section* section) const { - section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step", setToZeroOutsideInsideLinks); - section->add("set-to-null-ntc-between-physical-out-for-first-step", setToZeroOutsideOutsideLinks); + section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step", + setToZeroOutsideInsideLinks); + section->add("set-to-null-ntc-between-physical-out-for-first-step", + setToZeroOutsideOutsideLinks); section->add("enable-first-step", enabled); } @@ -44,6 +71,7 @@ void CurtailmentSharing::reset() priceTakingOrder = AdqPatchPTO::isDens; includeHurdleCost = false; checkCsrCostFunction = false; + recomputeDTGMRG = false; resetThresholds(); } @@ -55,7 +83,8 @@ void CurtailmentSharing::resetThresholds() thresholdVarBoundsRelaxation = defaultValueThresholdVarBoundsRelaxation; } -static bool StringToPriceTakingOrder(const AnyString& PTO_as_string, AdequacyPatch::AdqPatchPTO& PTO_as_enum) +static bool StringToPriceTakingOrder(const AnyString& PTO_as_string, + AdequacyPatch::AdqPatchPTO& PTO_as_enum) { Yuni::CString<24, false> s = PTO_as_string; s.trim(); @@ -80,20 +109,37 @@ bool CurtailmentSharing::updateFromKeyValue(const Yuni::String& key, const Yuni: { // Price taking order if (key == "price-taking-order") + { return StringToPriceTakingOrder(value, priceTakingOrder); + } // Include Hurdle Cost if (key == "include-hurdle-cost-csr") + { return value.to(includeHurdleCost); + } // Check CSR cost function prior and after CSR if (key == "check-csr-cost-function") + { return value.to(checkCsrCostFunction); + } + if (key == "recompute-dtg-mrg") + { + return value.to(recomputeDTGMRG); + } + // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") + { return value.to(thresholdRun); + } if (key == "threshold-display-local-matching-rule-violations") + { return value.to(thresholdDisplayViolations); + } if (key == "threshold-csr-variable-bounds-relaxation") + { return value.to(thresholdVarBoundsRelaxation); + } return false; } @@ -116,6 +162,7 @@ void CurtailmentSharing::addProperties(IniFile::Section* section) const section->add("price-taking-order", PriceTakingOrderToString(priceTakingOrder)); section->add("include-hurdle-cost-csr", includeHurdleCost); section->add("check-csr-cost-function", checkCsrCostFunction); + section->add("recompute-dtg-mrg", recomputeDTGMRG); // Thresholds section->add("threshold-initiate-curtailment-sharing-rule", thresholdRun); @@ -151,13 +198,15 @@ void AdqPatchParams::addExcludedVariables(std::vector& out) const } } - bool AdqPatchParams::updateFromKeyValue(const Yuni::String& key, const Yuni::String& value) { if (key == "include-adq-patch") + { return value.to(enabled); + } - return curtailmentSharing.updateFromKeyValue(key, value) != localMatching.updateFromKeyValue(key, value); // XOR + return curtailmentSharing.updateFromKeyValue(key, value) + != localMatching.updateFromKeyValue(key, value); // XOR } void AdqPatchParams::saveToINI(IniFile& ini) const @@ -169,47 +218,48 @@ void AdqPatchParams::saveToINI(IniFile& ini) const curtailmentSharing.addProperties(section); } -bool AdqPatchParams::checkAdqPatchParams(const StudyMode studyMode, +bool AdqPatchParams::checkAdqPatchParams(const SimulationMode simulationMode, const AreaList& areas, const bool includeHurdleCostParameters) const { - checkAdqPatchStudyModeEconomyOnly(studyMode); + checkAdqPatchSimulationModeEconomyOnly(simulationMode); checkAdqPatchContainsAdqPatchArea(areas); checkAdqPatchIncludeHurdleCost(includeHurdleCostParameters); - checkAdqPatchDisabledLocalMatching(); return true; } // Adequacy Patch can only be used with Economy Study/Simulation Mode. -void AdqPatchParams::checkAdqPatchStudyModeEconomyOnly(const StudyMode studyMode) const +void AdqPatchParams::checkAdqPatchSimulationModeEconomyOnly( + const SimulationMode simulationMode) const { - if (studyMode != StudyMode::stdmEconomy) - throw Error::IncompatibleStudyModeForAdqPatch(); + if (simulationMode != SimulationMode::Economy) + { + throw Error::IncompatibleSimulationModeForAdqPatch(); + } } // When Adequacy Patch is on at least one area must be inside Adequacy patch mode. void AdqPatchParams::checkAdqPatchContainsAdqPatchArea(const Antares::Data::AreaList& areas) const { - const bool containsAdqArea - = std::any_of(areas.cbegin(), areas.cend(), [](const std::pair& area) { - return area.second->adequacyPatchMode == physicalAreaInsideAdqPatch; - }); + const bool containsAdqArea = std::any_of(areas.cbegin(), + areas.cend(), + [](const std::pair& area) { + return area.second->adequacyPatchMode + == physicalAreaInsideAdqPatch; + }); if (!containsAdqArea) + { throw Error::NoAreaInsideAdqPatchMode(); + } } void AdqPatchParams::checkAdqPatchIncludeHurdleCost(const bool includeHurdleCostParameters) const { if (curtailmentSharing.includeHurdleCost && !includeHurdleCostParameters) + { throw Error::IncompatibleHurdleCostCSR(); + } } - -void AdqPatchParams::checkAdqPatchDisabledLocalMatching() const -{ - if (!localMatching.enabled && curtailmentSharing.priceTakingOrder == AdqPatchPTO::isDens) - throw Error::AdqPatchDisabledLMR(); -} - -} // Antares::Data::AdequacyPatch +} // namespace Antares::Data::AdequacyPatch diff --git a/src/libs/antares/study/parts/common/cluster.cpp b/src/libs/antares/study/parts/common/cluster.cpp index f302675b8a..9b38aa3c08 100644 --- a/src/libs/antares/study/parts/common/cluster.cpp +++ b/src/libs/antares/study/parts/common/cluster.cpp @@ -1,22 +1,37 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/study/parts/common/cluster.h" + #include -#include #include +#include -#include "cluster.h" -#include "../../study.h" #include +#include "antares/study/study.h" namespace Antares::Data { -Cluster::Cluster(Area* parent) : - unitCount(0), - enabled(true), - parentArea(parent), - index(0), - nominalCapacity(0.), - areaWideIndex((uint)-1), - series(nullptr) - +Cluster::Cluster(Area* parent): + parentArea(parent), + series(tsNumbers) { } @@ -46,56 +61,61 @@ void Cluster::setName(const AnyString& newname) { pName = newname; pID.clear(); - TransformNameIntoID(pName, pID); + pID = transformNameIntoID(pName); } #define SEP Yuni::IO::Separator -int Cluster::saveDataSeriesToFolder(const AnyString& folder) const + +bool Cluster::saveDataSeriesToFolder(const AnyString& folder) const { - if (not folder.empty()) + if (folder.empty()) { - Yuni::Clob buffer; - - buffer.clear() << folder << SEP << parentArea->id << SEP << id(); - if (Yuni::IO::Directory::Create(buffer)) - { - int ret = 1; - buffer.clear() << folder << SEP << parentArea->id << SEP << id() << SEP << "series.txt"; - ret = series->timeSeries.saveToCSVFile(buffer, precision()) && ret; - - return ret; - } - return 0; + return true; } - return 1; + + Yuni::Clob buffer; + buffer.clear() << folder << SEP << parentArea->id << SEP << id(); + if (!Yuni::IO::Directory::Create(buffer)) + { + return true; + } + + buffer.clear() << folder << SEP << parentArea->id << SEP << id() << SEP << "series.txt"; + return series.timeSeries.saveToCSVFile(buffer, precision()); } -int Cluster::loadDataSeriesFromFolder(Study& s, const AnyString& folder) +bool Cluster::loadDataSeriesFromFolder(Study& s, const AnyString& folder) { - if (not folder.empty()) + if (folder.empty()) { - auto& buffer = s.bufferLoadingTS; - - int ret = 1; - buffer.clear() << folder << SEP << parentArea->id << SEP << id() << SEP << "series." - << s.inputExtension; - ret = series->timeSeries.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &s.dataBuffer) && ret; + return true; + } - if (s.usedByTheSolver && s.parameters.derated) - series->timeSeries.averageTimeseries(); + auto& buffer = s.bufferLoadingTS; - series->timeseriesNumbers.clear(); + bool ret = true; + buffer.clear() << folder << SEP << parentArea->id << SEP << id() << SEP << "series." + << s.inputExtension; + ret = series.timeSeries.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &s.dataBuffer) && ret; - return ret; + if (s.usedByTheSolver && s.parameters.derated) + { + series.timeSeries.averageTimeseries(); } - return 1; + + series.timeseriesNumbers.clear(); + + return ret; } + #undef SEP void Cluster::invalidateArea() { if (parentArea) + { parentArea->forceReload(); + } } bool Cluster::isVisibleOnLayer(const size_t& layerID) const @@ -109,10 +129,7 @@ void Cluster::reset() enabled = true; nominalCapacity = 0.; - if (not series) - series = new DataSeriesCommon(); - - series->timeSeries.reset(1, HOURS_PER_YEAR); + series.timeSeries.reset(1, HOURS_PER_YEAR); } bool CompareClusterName::operator()(const Cluster* s1, const Cluster* s2) const @@ -121,4 +138,3 @@ bool CompareClusterName::operator()(const Cluster* s1, const Cluster* s2) const } } // namespace Antares::Data - diff --git a/src/libs/antares/study/parts/common/cluster.h b/src/libs/antares/study/parts/common/cluster.h deleted file mode 100644 index 9cd20ba798..0000000000 --- a/src/libs/antares/study/parts/common/cluster.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef __LIBS_ANTARES_STUDY_PARTS_COMMON_H__ -#define __LIBS_ANTARES_STUDY_PARTS_COMMON_H__ - -#include -#include -#include "series.h" -#include -#include "../../fwd.h" - -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -class Cluster; -struct CompareClusterName final -{ - bool operator()(const Cluster* s1, const Cluster* s2) const; -}; - -class Cluster -{ -public: - //! Map of renewable clusters - using Map = std::map; - -public: - Cluster(Area* parent); - - virtual ~Cluster() = default; - - //! Get the cluster ID - const ClusterName& id() const; - - //! \name Group - //@{ - //! Get the group of the cluster - const ClusterName& group() const; - - //! Get the renewable cluster name - const ClusterName& name() const; - - //! Set the name/ID - void setName(const AnyString& newname); - //@} - - //! Get the full cluster name - Yuni::String getFullName() const; - - virtual uint groupId() const = 0; - - //! Set the group - virtual void setGroup(Data::ClusterName newgrp) = 0; - //@} - - /*! - ** \brief Check and fix all values of a renewable cluster - ** - ** \return False if an error has been detected and fixed with a default value - */ - virtual bool integrityCheck() = 0; - - /*! - ** \brief Get the memory consummed by the renewable cluster (in bytes) - */ - virtual uint64_t memoryUsage() const = 0; - //@} - - /*! - ** \brief Invalidate all data associated to the renewable cluster - */ - virtual bool forceReload(bool reload) const = 0; - - /*! - ** \brief Invalidate the whole attached area - */ - void invalidateArea(); - - /*! - ** \brief Mark the renewable cluster as modified - */ - virtual void markAsModified() const = 0; - - /*! - ** \brief Check wether the cluster is visible in a layer (it's parent area is visible in the - *layer) - */ - bool isVisibleOnLayer(const size_t& layerID) const; - - /*! - ** \brief Reset to default values - ** - ** This method should only be called from the GUI - */ - virtual void reset(); - - //! Count of unit - uint unitCount; - - //! Enabled - bool enabled; - - //! The associate area (alias) - Area* parentArea; - - //! The index of the cluster (within a list) - uint index; - - //! Capacity of reference per unit (MW) (pMax) - double nominalCapacity; - - //! The index of the cluster from the area's point of view - //! \warning this variable is only valid when used by the solver - // (initialized in the same time that the runtime data) - uint areaWideIndex; - - //! Series - DataSeriesCommon* series; - - /*! - ** \brief Modulation matrix - ** - ** It is merely a 3x8760 matrix - ** [modulation cost, modulation capacity, market bid modulation] per hour - */ - Matrix<> modulation; - -protected: - //! Name - Data::ClusterName pName; - //! ID - Data::ClusterName pID; - //! Group - Data::ClusterName pGroup; - -public: - //! Set of clusters - using Set = std::set; - - int saveDataSeriesToFolder(const AnyString& folder) const; - int loadDataSeriesFromFolder(Study& s, const AnyString& folder); - -private: - virtual unsigned int precision() const = 0; -}; -} // namespace Data -} // namespace Antares -#endif /* __LIBS_ANTARES_STUDY_PARTS_COMMON_H__ */ diff --git a/src/libs/antares/study/parts/common/cluster_list.cpp b/src/libs/antares/study/parts/common/cluster_list.cpp index 5d70ae0ede..9c39ca7c8b 100644 --- a/src/libs/antares/study/parts/common/cluster_list.cpp +++ b/src/libs/antares/study/parts/common/cluster_list.cpp @@ -1,242 +1,178 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/study/parts/common/cluster_list.h" + +#include +#include + #include -#include "cluster_list.h" + #include -#include "../../study.h" +#include "antares/study/study.h" using namespace Yuni; -namespace // anonymous -{ -struct TSNumbersPredicate -{ - uint32_t operator()(uint32_t value) const - { - return value + 1; - } -}; -} // namespace namespace Antares::Data { using namespace Antares; -template -inline uint ClusterList::size() const -{ - return (uint)cluster.size(); -} - template inline bool ClusterList::empty() const { - return cluster.empty(); -} - -template -typename ClusterList::iterator ClusterList::begin() -{ - return std::begin(cluster); + return allClusters_.empty(); } template -typename ClusterList::const_iterator ClusterList::begin() const +std::shared_ptr ClusterList::enabledClusterAt(unsigned int index) const { - return std::begin(cluster); + // No operator [] was found for std::view (returned by each_enabled()). + // The current function is there to replace it. + return *(std::views::drop(each_enabled(), index).begin()); } template -typename ClusterList::iterator ClusterList::end() +ClusterT* ClusterList::findInAll(std::string_view id) const { - return std::end(cluster); -} - -template -typename ClusterList::const_iterator ClusterList::end() const -{ - return std::end(cluster); -} - -template -const ClusterT* ClusterList::find(const Data::ClusterName& id) const -{ - auto i = cluster.find(id); - return (i != cluster.end()) ? i->second.get() : nullptr; + for (auto& cluster: all()) + { + if (cluster->id() == id) + { + return cluster.get(); + } + } + return nullptr; } template -ClusterT* ClusterList::find(const Data::ClusterName& id) +std::vector> ClusterList::all() const { - auto i = cluster.find(id); - return (i != cluster.end()) ? i->second.get() : nullptr; + return allClusters_; } template -typename std::shared_ptr ClusterList::detach(iterator i) +bool ClusterList::exists(const Data::ClusterName& id) const { - SharedPtr c = i->second; - cluster.erase(i); - return c; + return std::ranges::any_of(allClusters_, [&id](const auto& c) { return c->id() == id; }); } template -void ClusterList::remove(iterator i) +void ClusterList::clearAll() { - cluster.erase(i); + allClusters_.clear(); } template -bool ClusterList::exists(const Data::ClusterName& id) const +void ClusterList::resizeAllTimeseriesNumbers(uint n) const { - if (not cluster.empty()) + for (auto& c: allClusters_) { - auto element = cluster.find(id); - return (element != cluster.end()); + c->series.timeseriesNumbers.reset(n); } - return false; } -template -Data::ClusterList::ClusterList() : byIndex(nullptr), groupCount(ClusterT::groupMax, 0) -{ -} +#define SEP IO::Separator template -Data::ClusterList::~ClusterList() +void ClusterList::storeTimeseriesNumbers(Solver::IResultWriter& writer) const { - // deleting all renewable clusters - clear(); -} + Clob path; + std::string ts_content; -template -void ClusterList::clear() -{ - if (byIndex) + for (auto& cluster: each_enabled()) { - delete[] byIndex; - byIndex = nullptr; + path.clear() << "ts-numbers" << SEP << typeID() << SEP << cluster->parentArea->id << SEP + << cluster->id() << ".txt"; + ts_content.clear(); // We must clear ts_content here, since saveToBuffer does not do it. + cluster->series.timeseriesNumbers.saveToBuffer(ts_content); + writer.addEntryFromBuffer(path.c_str(), ts_content); } - - if (not cluster.empty()) - cluster.clear(); } template -const ClusterT* ClusterList::find(const ClusterT* p) const +bool ClusterList::alreadyInAllClusters(std::string clusterId) { - auto end = cluster.end(); - for (auto i = cluster.begin(); i != end; ++i) - { - if (p == i->second.get()) - return i->second.get(); - } - return nullptr; + return std::ranges::any_of(allClusters_, + [&clusterId](const auto& c) { return c->id() == clusterId; }); } template -ClusterT* ClusterList::find(const ClusterT* p) +void ClusterList::addToCompleteList(std::shared_ptr cluster) { - auto end = cluster.end(); - for (auto i = cluster.begin(); i != end; ++i) + if (alreadyInAllClusters(cluster->id())) { - if (p == i->second.get()) - return i->second.get(); + return; } - return nullptr; + allClusters_.push_back(cluster); + sortCompleteList(); + rebuildIndexes(); } template -void ClusterList::resizeAllTimeseriesNumbers(uint n) +void ClusterList::sortCompleteList() { - assert(n < 200000); // arbitrary number - if (not cluster.empty()) - { - if (0 == n) - { - each([&](Cluster& cluster) { cluster.series->timeseriesNumbers.clear(); }); - } - else - { - each([&](Cluster& cluster) { cluster.series->timeseriesNumbers.resize(1, n); }); - } - } + std::ranges::sort(allClusters_, [](const auto a, const auto b) { return a->id() < b->id(); }); } -#define SEP IO::Separator - template -void ClusterList::storeTimeseriesNumbers(Solver::IResultWriter& writer) const +unsigned int ClusterList::enabledCount() const { - if (cluster.empty()) - return; - - TSNumbersPredicate predicate; - Clob path; - std::string ts_content; - - each([&](const Cluster& cluster) { - path.clear() << "ts-numbers" << SEP << typeID() << SEP << cluster.parentArea->id << SEP - << cluster.id() << ".txt"; - ts_content.clear(); // We must clear ts_content here, since saveToBuffer does not do it. - cluster.series->timeseriesNumbers.saveToBuffer(ts_content, 0, true, predicate, true); - writer.addEntryFromBuffer(path.c_str(), ts_content); - }); + return std::ranges::count_if(allClusters_, &ClusterT::isEnabled); } template -void ClusterList::rebuildIndex() +unsigned int ClusterList::allClustersCount() const { - delete[] byIndex; - - if (not empty()) - { - uint indx = 0; - using ClusterWeakPtr = ClusterT*; - byIndex = new ClusterWeakPtr[size()]; - - auto end = cluster.end(); - for (auto i = cluster.begin(); i != end; ++i) - { - auto cluster = i->second.get(); - byIndex[indx] = cluster; - cluster->index = indx; - ++indx; - } - } - else - byIndex = nullptr; + return allClusters_.size(); } template -typename ClusterList::SharedPtr ClusterList::add( - const ClusterList::SharedPtr& newcluster) -{ - if (newcluster) +void ClusterList::rebuildIndexes() +{ + // First, we give an index to every cluster, enabled / must-run or not. + // We do that to : + // - Stick to what was done before and not change the results + // - Avoids seg faults, for instance when storing thermal noises (solver.hxx). + // Indeed : otherwise disabled clusters have an infinite index + unsigned int index = 0; + for (auto& c: allClusters_) { - if (exists(newcluster->id())) - return cluster[newcluster->id()]; - - newcluster->index = (uint)size(); - cluster[newcluster->id()] = newcluster; - ++(groupCount[newcluster->groupId()]); - rebuildIndex(); - return cluster[newcluster->id()]; + c->areaWideIndex = index; + index++; } - return nullptr; -} -template -uint64_t ClusterList::memoryUsage() const -{ - uint64_t ret = sizeof(ClusterList) + (2 * sizeof(void*)) * this->size(); - - each([&](const ClusterT& cluster) { ret += cluster.memoryUsage(); }); - return ret; + index = 0; + for (auto& c: each_enabled()) + { + c->areaWideIndex = index; + index++; + } } template bool ClusterList::rename(Data::ClusterName idToFind, Data::ClusterName newName) { if (idToFind.empty() or newName.empty()) + { return false; + } // Internal: // It is vital to make copy of these strings. We can not make assumption that these @@ -248,156 +184,88 @@ bool ClusterList::rename(Data::ClusterName idToFind, Data::ClusterName boost::to_lower(idToFind); // The new ID - Data::ClusterName newID; - Antares::TransformNameIntoID(newName, newID); + Data::ClusterName newID = Antares::transformNameIntoID(newName); - // Looking for the renewable cluster in the list - auto it = cluster.find(idToFind); - if (it == cluster.end()) + // Looking for the renewable clusters in the list + auto* cluster_ptr = this->findInAll(idToFind); + if (!cluster_ptr) + { return true; - - SharedPtr p = it->second; + } if (idToFind == newID) { - p->setName(newName); + cluster_ptr->setName(newName); return true; } // The name is the same. Aborting nicely. - if (p->name() == newName) + if (cluster_ptr->name() == newName) + { return true; + } // Already exist if (this->exists(newID)) + { return false; + } - cluster.erase(it); - - p->setName(newName); - cluster[newID] = p; + cluster_ptr->setName(newName); // Invalidate matrices attached to the area - // It is a bit excessive (all matrices not only those related to the renewable cluster) + // It is a bit excessive (all matrices not only those related to the renewable clusters) // will be rewritten but currently it is the less error-prone. - if (p->parentArea) - (p->parentArea)->invalidateJIT = true; + if (cluster_ptr->parentArea) + { + (cluster_ptr->parentArea)->invalidateJIT = true; + } - // Rebuilding the index - rebuildIndex(); return true; } template bool ClusterList::forceReload(bool reload) const { - bool ret = true; - auto end = cluster.end(); - for (auto i = cluster.begin(); i != end; ++i) - ret = (i->second)->forceReload(reload) and ret; - return ret; + return std::ranges::all_of(allClusters_, + [&reload](const auto& c) { return c->forceReload(reload); }); } template void ClusterList::markAsModified() const { - auto end = cluster.end(); - for (auto i = cluster.begin(); i != end; ++i) - (i->second)->markAsModified(); -} - -template -bool ClusterList::remove(const Data::ClusterName& id) -{ - auto i = cluster.find(id); - if (i == cluster.end()) - return false; - - // Getting the pointer on the cluster - SharedPtr c = i->second; - - // Removing it from the list - cluster.erase(i); - // Invalidating the parent area - c->parentArea->forceReload(); - - // Rebuilding the index - rebuildIndex(); - return true; -} - -template -int ClusterList::saveDataSeriesToFolder(const AnyString& folder) const -{ - if (empty()) - return 1; - - int ret = 1; - - auto end = cluster.end(); - for (auto it = cluster.begin(); it != end; ++it) + for (const auto& c: allClusters_) { - auto& cluster = *(it->second); - if (cluster.series) - ret = cluster.saveDataSeriesToFolder(folder) and ret; + c->markAsModified(); } - return ret; } template -int ClusterList::saveDataSeriesToFolder(const AnyString& folder, const String& msg) const +bool ClusterList::remove(const Data::ClusterName& id) { - if (empty()) - return 1; + auto nbDeletion = std::erase_if(allClusters_, + [&id](const SharedPtr& c) { return c->id() == id; }); - int ret = 1; - uint ticks = 0; + // Invalidating the parent area + forceReload(); - auto end = cluster.end(); - for (auto it = cluster.begin(); it != end; ++it) - { - auto& cluster = *(it->second); - if (cluster.series) - { - logs.info() << msg << " " << (ticks * 100 / (1 + this->cluster.size())) - << "% complete"; - ret = cluster.saveDataSeriesToFolder(folder) and ret; - } - ++ticks; - } - return ret; + return nbDeletion > 0; } template -int ClusterList::loadDataSeriesFromFolder(Study& s, - const StudyLoadOptions& options, - const AnyString& folder) +bool ClusterList::saveDataSeriesToFolder(const AnyString& folder) const { - if (empty()) - return 1; - - int ret = 1; - - each([&](ClusterT& c) { - if (c.series) - ret = c.loadDataSeriesFromFolder(s, folder) and ret; - - ++options.progressTicks; - options.pushProgressLogs(); - }); - return ret; + return std::ranges::all_of(allClusters_, + [&folder](const auto c) + { return c->saveDataSeriesToFolder(folder); }); } template -void ClusterList::ensureDataTimeSeries() +bool ClusterList::loadDataSeriesFromFolder(Study& s, const AnyString& folder) { - auto end = cluster.end(); - for (auto it = cluster.begin(); it != end; ++it) - { - SharedPtr cluster = it->second; - if (not cluster->series) - cluster->series = new DataSeriesCommon(); - } + return std::ranges::all_of(allClusters_, + [&s, &folder](auto c) + { return c->loadDataSeriesFromFolder(s, folder); }); } template @@ -406,19 +274,10 @@ void ClusterList::retrieveTotalCapacityAndUnitCount(double& total, uin total = 0.; unitCount = 0; - if (not cluster.empty()) + for (const auto& c: all()) { - auto end = cluster.cend(); - for (auto i = cluster.cbegin(); i != end; ++i) - { - if (not i->second) - return; - - // Reference to the thermal cluster - auto& cluster = *(i->second); - unitCount += cluster.unitCount; - total += cluster.unitCount * cluster.nominalCapacity; - } + unitCount += c->unitCount; + total += c->unitCount * c->nominalCapacity; } } @@ -427,4 +286,3 @@ template class ClusterList; template class ClusterList; } // namespace Antares::Data - diff --git a/src/libs/antares/study/parts/common/cluster_list.h b/src/libs/antares/study/parts/common/cluster_list.h deleted file mode 100644 index 584140bded..0000000000 --- a/src/libs/antares/study/parts/common/cluster_list.h +++ /dev/null @@ -1,268 +0,0 @@ -#ifndef __ANTARES_LIBS_STUDY_PARTS_COMMON_CLUSTER_LIST_H__ -#define __ANTARES_LIBS_STUDY_PARTS_COMMON_CLUSTER_LIST_H__ - -#include -#include "../../fwd.h" - -#include - -#include -#include - -namespace Antares -{ -namespace Data -{ -/*! -** \brief List of clusters -** \ingroup renewableclusters -*/ -template -class ClusterList -{ -public: - // Shared pointer - using SharedPtr = typename std::shared_ptr; - // Map container - using Map = typename std::map; - //! iterator - using iterator = typename Map::iterator; - //! const iterator - using const_iterator = typename Map::const_iterator; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - ClusterList(); - /*! - ** \brief Destructor - */ - virtual ~ClusterList(); - //@} - - //! \name Iterating - //@{ - /*! - ** \brief Iterate through all clusters - */ - template - void each(const PredicateT& predicate) - { - auto end = cluster.cend(); - for (auto i = cluster.cbegin(); i != end; ++i) - { - auto& it = *(i->second); - predicate(it); - } - } - /*! - ** \brief Iterate through all clusters (const) - */ - template - void each(const PredicateT& predicate) const - { - auto end = cluster.end(); - for (auto i = cluster.begin(); i != end; ++i) - { - const auto& it = *(i->second); - predicate(it); - } - } - - //! \name Cluster management - //@{ - /*! - ** \brief Destroy all clusters - */ - void clear(); - - /*! - ** \brief Add a cluster in the list - ** - ** \param t The cluster to add - ** \return True if the cluster has been added, false otherwise - */ - - SharedPtr add(const SharedPtr& t); - /*! - ** \brief Detach a cluster represented by an iterator - ** - ** The cluster will be removed from the list but _not_ - ** destroyed. - ** The iterator should considered as invalid after using this method. - ** \return A pointer to the cluster, NULL if an error has occured - */ - SharedPtr detach(iterator i); - - /*! - ** \brief Remove a cluster represented by an iterator - ** - ** The cluster will be removed from the list but _not_ - ** destroyed. - ** The iterator should considered as invalid after using this method. - ** \return void - */ - virtual void remove(iterator i); - - /*! - ** \brief Try to find a cluster from its id - ** - ** \param id ID of the cluster to find - ** \return A pointer to a cluster. nullptr if not found - */ - ClusterT* find(const Data::ClusterName& id); - /*! - ** \brief Try to find a cluster from its id (const) - ** - ** \param id ID of the cluster to find - ** \return A pointer to a cluster. nullptr if not found - */ - const ClusterT* find(const Data::ClusterName& id) const; - - /*! - ** \brief Try to find a cluster from its pointer - ** - ** \param p Pointer of the cluster to find - ** \return A pointer to a cluster. nullptr if not found - */ - ClusterT* find(const ClusterT* p); - /*! - ** \brief Try to find a cluster from its pointer (const) - ** - ** \param p Pointer of the cluster to find - ** \return A pointer to a cluster. nullptr if not found - */ - const ClusterT* find(const ClusterT* p) const; - - /*! - ** \brief Get if a cluster exists - ** - ** \param id ID of the cluster to find - ** \return True if the cluster exists - */ - bool exists(const Data::ClusterName& id) const; - - /*! - ** \brief Rename a cluster - ** - ** \param idToFind ID of the cluster to rename - ** \param newName The new name for the cluster - ** \return True if the operation succeeded (the cluster has been renamed) - ** false otherwise (not found or if another cluster has the same name) - ** - ** The indexes for clusters will be rebuilt. - */ - bool rename(Data::ClusterName idToFind, Data::ClusterName newName); - - /*! - ** \brief Remove properly a cluster - */ - virtual bool remove(const Data::ClusterName& id); - - //! Get the number of items in the list - uint size() const; - - //! Get if the list is empty - bool empty() const; - //@} - - //! iterator to the begining of the list - iterator begin(); - //! iterator to the begining of the list - const_iterator begin() const; - - //! iterator to the end of the list - iterator end(); - //! iterator to the end of the list - const_iterator end() const; - - /*! - ** \brief Resize all matrices dedicated to the sampled timeseries numbers - ** - ** \param n A number of years - */ - void resizeAllTimeseriesNumbers(uint n); - - void storeTimeseriesNumbers(Solver::IResultWriter& writer) const; - - //@} - - //! \name Memory management - //@{ - /*! - ** \brief Invalidate all clusters - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark the cluster as modified - */ - void markAsModified() const; - - /*! - ** \brief Rebuild the index of clusters - ** - ** As a list of clusters is a hash table, it is not - ** possible to directly accees to a cluster from its index. - ** However an index can be built but it must be re-built when - ** the hash table is modified. - */ - void rebuildIndex(); - - /*! - ** \brief Get the size (bytes) occupied in memory by a `ClusterList` structure - ** \return A size (in bytes) - */ - uint64_t memoryUsage() const; - -public: - //! All clusters by their index - ClusterT** byIndex; - //! All clusters - Map cluster; - - // thermal, renewable, etc. - virtual YString typeID() const = 0; - - /*! - ** \brief Number of dispatchable cluster per group - ** - ** You should rely on these values only after the loading of the study - ** and until the study is not modified. - ** These values are modified by 'ClusterListAdd()' - */ - std::vector groupCount; - - int loadDataSeriesFromFolder(Study& study, - const StudyLoadOptions& options, - const AnyString& folder); - - int saveDataSeriesToFolder(const AnyString& folder) const; - - int saveDataSeriesToFolder(const AnyString& folder, const YString& msg) const; - - virtual bool saveToFolder(const AnyString& folder) const = 0; - - void ensureDataTimeSeries(); - - //! \name Informations - //@{ - /*! - ** \brief Retrieve the total capacity and the total unit count - ** - ** Pseudo code: - ** \code - ** each thermal cluster do - ** total += cluster{unit count} * cluster{nominal capacity} - ** unit += cluster{unit count} - ** \endcode - */ - void retrieveTotalCapacityAndUnitCount(double& total, uint& unitCount) const; - //@} -}; // class ClusterList -} // namespace Data -} // namespace Antares -#endif /* __ANTARES_LIBS_STUDY_PARTS_COMMON_CLUSTER_LIST_H__ */ diff --git a/src/libs/antares/study/parts/common/series.cpp b/src/libs/antares/study/parts/common/series.cpp deleted file mode 100644 index cfbf5e372a..0000000000 --- a/src/libs/antares/study/parts/common/series.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include -#include "../../study.h" -#include "series.h" - -using namespace Yuni; - -#define SEP IO::Separator - - -namespace Antares::Data -{ -bool DataSeriesCommon::forceReload(bool reload) const -{ - return timeSeries.forceReload(reload); -} - -void DataSeriesCommon::markAsModified() const -{ - timeSeries.markAsModified(); -} - -uint64_t DataSeriesCommon::memoryUsage() const -{ - return timeSeries.memoryUsage(); -} - -double DataSeriesCommon::getAvailablePower(unsigned int hour, unsigned int year) const -{ - return timeSeries[getSeriesIndex(year)][hour]; -} - -const DataSeriesCommon::SingleYear& DataSeriesCommon::getAvailablePowerYearly(unsigned int year) const -{ - return timeSeries[getSeriesIndex(year)]; -} - -uint DataSeriesCommon::getSeriesIndex(unsigned int year) const -{ - if (timeSeries.width == 1) - return 0; - else - return timeseriesNumbers[0][year]; -} - -} // namespace Antares::Data - diff --git a/src/libs/antares/study/parts/common/series.h b/src/libs/antares/study/parts/common/series.h deleted file mode 100644 index 94ca55db35..0000000000 --- a/src/libs/antares/study/parts/common/series.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_COMMON_TIMESERIES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_COMMON_TIMESERIES_H__ - -#include -#include -#include "../../fwd.h" - -namespace Antares::Data -{ -/*! -** \brief Data series (Common) -*/ -class DataSeriesCommon -{ -public: - using AllYears = Matrix; - using SingleYear = AllYears::ColumnType; - - bool forceReload(bool reload = false) const; - - void markAsModified() const; - - uint64_t memoryUsage() const; - - double getAvailablePower(unsigned int hour, unsigned int year) const; - const SingleYear& getAvailablePowerYearly(unsigned int year) const; - - /*! - ** \brief Series (MW) - ** - ** Merely a matrix of TimeSeriesCount * 8760 values - */ - AllYears timeSeries; - - /*! - ** \brief Monte-Carlo - */ - Matrix timeseriesNumbers; - -private: - uint getSeriesIndex(unsigned int year) const; - -}; // class DataSeriesCommon - -} // namespace Antares::Data -#endif /* __ANTARES_LIBS_STUDY_PARTS_COMMON_TIMESERIES_H__ */ diff --git a/src/libs/antares/study/parts/hydro/allocation.cpp b/src/libs/antares/study/parts/hydro/allocation.cpp index a4afa2b4cc..052bc3411d 100644 --- a/src/libs/antares/study/parts/hydro/allocation.cpp +++ b/src/libs/antares/study/parts/hydro/allocation.cpp @@ -1,36 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "allocation.h" -#include "../../study.h" -#include -#include +#include "antares/study/parts/hydro/allocation.h" + +#include +#include "antares/study/study.h" -using namespace Yuni; +namespace fs = std::filesystem; namespace Antares { @@ -42,7 +36,9 @@ static const Area* FindMappedAreaName(const AreaName& id, { auto i = mapping.find(id); if (i != mapping.end()) + { return study.areas.findFromName(i->second); + } return study.areas.findFromName(id); } @@ -62,7 +58,9 @@ void HydroAllocation::remove(const AreaName& areaid) assert(!pMustUseValuesFromAreaID); auto i = pValues.find(areaid); if (i != pValues.end()) + { pValues.erase(i); + } } void HydroAllocation::rename(const AreaName& oldid, const AreaName& newid) @@ -109,7 +107,9 @@ void HydroAllocation::fromArea(const Area& area, double value) void HydroAllocation::fromArea(const Area* area, double value) { if (area) + { fromArea(area->id, value); + } } double HydroAllocation::fromArea(const AreaName& areaid) const @@ -122,14 +122,18 @@ double HydroAllocation::fromArea(const AreaName& areaid) const void HydroAllocation::fromArea(const AreaName& areaid, double value) { assert(!pMustUseValuesFromAreaID); - if (Math::Zero(value)) + if (Utils::isZero(value)) { auto i = pValues.find(areaid); if (i != pValues.end()) + { pValues.erase(i); + } } else + { pValues[areaid] = value; + } } void HydroAllocation::prepareForSolver(const AreaList& list) @@ -140,7 +144,9 @@ void HydroAllocation::prepareForSolver(const AreaList& list) { auto* targetarea = list.find(i->first); if (targetarea) + { pValuesFromAreaID[targetarea->index] = i->second; + } } pValues.clear(); @@ -158,34 +164,36 @@ void HydroAllocation::clear() #endif } -bool HydroAllocation::loadFromFile(const AreaName& referencearea, const AnyString& filename) +bool HydroAllocation::loadFromFile(const AreaName& referencearea, const fs::path& filename) { clear(); IniFile ini; - if (IO::File::Exists(filename) && ini.open(filename)) + if (!fs::exists(filename) || !ini.open(filename)) { - if (!ini.empty()) - { - AreaName areaname; - ini.each([&](const IniFile::Section& section) { - for (auto* p = section.firstProperty; p; p = p->next) - { - double coeff = p->value.to(); - if (!Math::Zero(coeff)) - { - areaname = p->key; - areaname.toLower(); - pValues[areaname] = coeff; - } - } - }); - } + pValues[referencearea] = 1.0; + return true; } - else + + if (ini.empty()) { - pValues[referencearea] = 1.0; + return true; } + + ini.each( + [this](const IniFile::Section& section) + { + for (auto* p = section.firstProperty; p; p = p->next) + { + double coeff = p->value.to(); + if (!Utils::isZero(coeff)) + { + AreaName areaname = p->key; + areaname.toLower(); + pValues[areaname] = coeff; + } + } + }); return true; } @@ -193,7 +201,7 @@ bool HydroAllocation::saveToFile(const AnyString& filename) const { if (pValues.empty()) { - IO::File::CreateEmptyFile(filename); + Yuni::IO::File::CreateEmptyFile(filename); return true; } else @@ -201,11 +209,11 @@ bool HydroAllocation::saveToFile(const AnyString& filename) const IniFile ini; auto* s = ini.addSection("[allocation]"); auto end = pValues.end(); - CString<64, false> str; + Yuni::CString<64, false> str; for (auto i = pValues.begin(); i != end; ++i) { double v = i->second; - if (not Math::Zero(v)) + if (!Utils::isZero(v)) { str = v; if (str.contains('.')) diff --git a/src/libs/antares/study/parts/hydro/allocation.hxx b/src/libs/antares/study/parts/hydro/allocation.hxx deleted file mode 100644 index b8a071d281..0000000000 --- a/src/libs/antares/study/parts/hydro/allocation.hxx +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_HXX__ -#define __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_HXX__ - -namespace Antares -{ -namespace Data -{ -template -inline void HydroAllocation::eachNonNull(const CallbackT& callback) const -{ - assert(pMustUseValuesFromAreaID); - auto end = pValuesFromAreaID.end(); - for (auto i = pValuesFromAreaID.begin(); i != end; ++i) - callback(i->first, i->second); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIB_STUDY_AREA_HYDRO_ALLOCATION_HXX__ diff --git a/src/libs/antares/study/parts/hydro/container.cpp b/src/libs/antares/study/parts/hydro/container.cpp index 288ec58a44..92d13a586e 100644 --- a/src/libs/antares/study/parts/hydro/container.cpp +++ b/src/libs/antares/study/parts/hydro/container.cpp @@ -1,62 +1,55 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../../study.h" -#include "container.h" +#include "antares/study/parts/hydro/container.h" + #include +#include "antares/study/parts/hydro/hydromaxtimeseriesreader.h" +#include "antares/study/study.h" using namespace Antares; using namespace Yuni; #define SEP IO::Separator -namespace Antares +namespace Antares::Data { -namespace Data -{ -PartHydro::PartHydro() : - interDailyBreakdown(0.), - intraDailyModulation(2.), - intermonthlyBreakdown(0), - reservoirManagement(false), - followLoadModulations(true), - useWaterValue(false), - hardBoundsOnRuleCurves(false), - useHeuristicTarget(true), - reservoirCapacity(0.), - initializeReservoirLevelDate(0), - useLeeway(false), - powerToLevel(false), - leewayLowerBound(1.), - leewayUpperBound(1.), - pumpingEfficiency(1.), - hydroModulable(false), - prepro(nullptr), - series(nullptr) +PartHydro::PartHydro(): + interDailyBreakdown(0.), + intraDailyModulation(2.), + intermonthlyBreakdown(0), + reservoirManagement(false), + followLoadModulations(true), + useWaterValue(false), + hardBoundsOnRuleCurves(false), + useHeuristicTarget(true), + reservoirCapacity(0.), + initializeReservoirLevelDate(0), + useLeeway(false), + powerToLevel(false), + leewayLowerBound(1.), + leewayUpperBound(1.), + pumpingEfficiency(1.), + prepro(nullptr), + series(nullptr) { } @@ -91,9 +84,10 @@ void PartHydro::reset() reservoirLevel.fillColumn(average, 0.5); reservoirLevel.fillColumn(maximum, 1.); waterValues.reset(101, DAYS_PER_YEAR, true); - maxPower.reset(4, DAYS_PER_YEAR, true); - maxPower.fillColumn(genMaxE, 24.); - maxPower.fillColumn(pumpMaxE, 24.); + dailyNbHoursAtGenPmax.reset(1, DAYS_PER_YEAR, true); + dailyNbHoursAtGenPmax.fillColumn(0, 24.); + dailyNbHoursAtPumpPmax.reset(1, DAYS_PER_YEAR, true); + dailyNbHoursAtPumpPmax.fillColumn(0, 24.); creditModulation.reset(101, 2, true); creditModulation.fill(1); // reset of the hydro allocation - however we don't have any information @@ -103,533 +97,387 @@ void PartHydro::reset() // allocation.fromArea(, 1.); // Area::reset() if (prepro) + { prepro->reset(); + } if (series) + { series->reset(); + } } -bool PartHydro::LoadFromFolder(Study& study, const AnyString& folder) +template +static bool loadProperties(Study& study, + IniFile::Property* property, + const std::string& filename, + T PartHydro::*ptr) { - auto& buffer = study.bufferLoadingTS; + if (!property) + { + return false; + } + bool ret = true; - // Initialize all alpha values to 0 - study.areas.each([&](Data::Area& area) { - area.hydro.interDailyBreakdown = 1.; - area.hydro.intraDailyModulation = 24.; - area.hydro.intermonthlyBreakdown = 1.; - area.hydro.reservoirManagement = false; - area.hydro.followLoadModulations = true; - area.hydro.useWaterValue = false; - area.hydro.hardBoundsOnRuleCurves = false; - area.hydro.useHeuristicTarget = true; - area.hydro.useLeeway = false; - area.hydro.powerToLevel = false; - area.hydro.leewayLowerBound = 1.; - area.hydro.leewayUpperBound = 1.; - area.hydro.initializeReservoirLevelDate = 0; - area.hydro.reservoirCapacity = 0.; - area.hydro.pumpingEfficiency = 1.; - - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "maxpower_" - << area.id << '.' << study.inputExtension; - - // GUI part patch : - // We need to know, when estimating the RAM required by the solver, if the current area - // is hydro modulable. Therefore, reading the area's daily max power at this stage is - // necessary. + // Browse all properties + for (; property; property = property->next) + { + AreaName id = property->key; + id.toLower(); - if (!study.usedByTheSolver) + Area* area = study.areas.find(id); + if (area) { - bool enabledModeIsChanged = false; - if (JIT::enabled) - { - JIT::enabled = false; // Allowing to read the area's daily max power - enabledModeIsChanged = true; - } - - ret = area.hydro.maxPower.loadFromCSVFile( - buffer, 4, DAYS_PER_YEAR, Matrix<>::optFixedSize, &study.dataBuffer) - && ret; - - if (enabledModeIsChanged) - JIT::enabled = true; // Back to the previous loading mode. + ret = property->value.to(area->hydro.*ptr) && ret; } else { - ret = area.hydro.maxPower.loadFromCSVFile( - buffer, 4, DAYS_PER_YEAR, Matrix<>::optFixedSize, &study.dataBuffer) - && ret; + logs.warning() << filename << ": `" << id << "`: Unknown area"; + return false; } + } + return ret; +} - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP - << "creditmodulations_" << area.id << '.' << study.inputExtension; - ret = area.hydro.creditModulation.loadFromCSVFile( - buffer, 101, 2, Matrix<>::optFixedSize, &study.dataBuffer) - && ret; - - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "reservoir_" - << area.id << '.' << study.inputExtension; - ret = area.hydro.reservoirLevel.loadFromCSVFile( - buffer, 3, DAYS_PER_YEAR, Matrix<>::optFixedSize, &study.dataBuffer) - && ret; - +bool PartHydro::LoadFromFolder(Study& study, const AnyString& folder) +{ + auto& buffer = study.bufferLoadingTS; + bool ret = true; - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP - << "waterValues_" << area.id << '.' << study.inputExtension; - ret = area.hydro.waterValues.loadFromCSVFile( - buffer, 101, DAYS_PER_YEAR, Matrix<>::optFixedSize, &study.dataBuffer) - && ret; + // Initialize all alpha values to 0 + study.areas.each( + [&ret, &buffer, &study, &folder](Data::Area& area) + { + area.hydro.interDailyBreakdown = 1.; + area.hydro.intraDailyModulation = 24.; + area.hydro.intermonthlyBreakdown = 1.; + area.hydro.reservoirManagement = false; + area.hydro.followLoadModulations = true; + area.hydro.useWaterValue = false; + area.hydro.hardBoundsOnRuleCurves = false; + area.hydro.useHeuristicTarget = true; + area.hydro.useLeeway = false; + area.hydro.powerToLevel = false; + area.hydro.leewayLowerBound = 1.; + area.hydro.leewayUpperBound = 1.; + area.hydro.initializeReservoirLevelDate = 0; + area.hydro.reservoirCapacity = 0.; + area.hydro.pumpingEfficiency = 1.; + area.hydro.deltaBetweenFinalAndInitialLevels.resize(study.parameters.nbYears); + + if (study.header.version >= StudyVersion(9, 1)) + { + // GUI part patch : + // We need to know, when estimating the RAM required by the solver, if the current + // area is hydro modulable. Therefore, reading the area's daily max power at this + // stage is necessary. + + if (!study.usedByTheSolver) + { + bool enabledModeIsChanged = false; + if (JIT::enabled) + { + JIT::enabled = false; // Allowing to read the area's daily max power + enabledModeIsChanged = true; + } + + ret = area.hydro.LoadDailyMaxEnergy(folder, area.id) && ret; + + if (enabledModeIsChanged) + { + JIT::enabled = true; // Back to the previous loading mode. + } + } + else + { + ret = area.hydro.LoadDailyMaxEnergy(folder, area.id) && ret; + + // Check is moved here, because in case of old study + // dailyNbHoursAtGenPmax and dailyNbHoursAtPumpPmax are not yet initialized. + + ret = area.hydro.CheckDailyMaxEnergy(area.name) && ret; + } + } + + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "creditmodulations_" << area.id << '.' << study.inputExtension; + ret = area.hydro.creditModulation.loadFromCSVFile(buffer, + 101, + 2, + Matrix<>::optFixedSize, + &study.dataBuffer) + && ret; - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP - << "inflowPattern_" << area.id << '.' << study.inputExtension; - ret = area.hydro.inflowPattern.loadFromCSVFile( - buffer, 1, DAYS_PER_YEAR, Matrix<>::optFixedSize, &study.dataBuffer) - && ret; + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "reservoir_" + << area.id << '.' << study.inputExtension; + ret = area.hydro.reservoirLevel.loadFromCSVFile(buffer, + 3, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &study.dataBuffer) + && ret; - if (study.usedByTheSolver) - { - auto& col = area.hydro.inflowPattern[0]; - bool errorInflow = false; - for (int day = 0; day < DAYS_PER_YEAR; day++) - { - if (col[day] < 0 && !errorInflow) - { - logs.error() << area.name << ": invalid inflow value"; - errorInflow = true; - ret = false; - } - } - bool errorLevels = false; - auto& colMin = area.hydro.reservoirLevel[minimum]; - auto& colAvg = area.hydro.reservoirLevel[average]; - auto& colMax = area.hydro.reservoirLevel[maximum]; - for (int day = 0; day < DAYS_PER_YEAR; day++) - { - if (!errorLevels - && (colMin[day] < 0 || colAvg[day] < 0 || colMin[day] > colMax[day] - || colAvg[day] > 100 || colMax[day] > 100)) - { - logs.error() << area.name << ": invalid reservoir level value"; - errorLevels = true; - ret = false; - } - } - bool errorPowers = false; - for (int i = 0; i < 4; i++) - { - auto& col = area.hydro.maxPower[i]; - for (int day = 0; day < DAYS_PER_YEAR; day++) - { - if (!errorPowers && (col[day] < 0 || (i % 2 /*column hours*/ && col[day] > 24))) - { - logs.error() << area.name << ": invalid power or energy value"; - errorPowers = true; - ret = false; - } - } - } - for (int i = 0; i < 101; i++) - { - if ((area.hydro.creditModulation[i][0] < 0) - || (area.hydro.creditModulation[i][1] < 0)) - { - logs.error() << area.name << ": invalid credit modulation value"; - ret = false; - } - } - } - else - { - // Is area hydro modulable ? - auto& max = area.hydro.maxPower[area.hydro.genMaxP]; + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "waterValues_" + << area.id << '.' << study.inputExtension; + ret = area.hydro.waterValues.loadFromCSVFile(buffer, + 101, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &study.dataBuffer) + && ret; - for (uint y = 0; y != area.hydro.maxPower.height; ++y) - { - if (max[y] > 0.) - { - area.hydro.hydroModulable = true; - break; - } - } - } - }); + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "inflowPattern_" << area.id << '.' << study.inputExtension; + ret = area.hydro.inflowPattern.loadFromCSVFile(buffer, + 1, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &study.dataBuffer) + && ret; + }); IniFile ini; if (not ini.open(buffer.clear() << folder << SEP << "hydro.ini")) + { return false; + } - const char* const sectionName = "inter-daily-breakdown"; - - IniFile::Section* section; - IniFile::Property* property; + if (IniFile::Section* section = ini.find("inter-daily-breakdown")) + { + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::interDailyBreakdown) + && ret; + } - if ((section = ini.find(sectionName))) + if (IniFile::Section* section = ini.find("intra-daily-modulation")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - Area* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.interDailyBreakdown) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, + section->firstProperty, + buffer, + &PartHydro::intraDailyModulation) + && ret; } - if ((section = ini.find("intra-daily-modulation"))) + if (IniFile::Section* section = ini.find("reservoir")) { - if ((property = section->firstProperty)) - { - AreaName id; + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::reservoirManagement) + && ret; + } - // Browse all properties - for (; property; property = property->next) - { - id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.intraDailyModulation) && ret; - if (area->hydro.intraDailyModulation < 1.) - { - logs.error() - << area->id << ": Invalid intra-daily modulation. It must be >= 1.0, Got " - << area->hydro.intraDailyModulation << " (truncated to 1)"; - area->hydro.intraDailyModulation = 1.; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + if (IniFile::Section* section = ini.find("reservoir capacity")) + { + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::reservoirCapacity) + && ret; } - if ((section = ini.find("reservoir"))) + if (IniFile::Section* section = ini.find("follow load")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.reservoirManagement) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, + section->firstProperty, + buffer, + &PartHydro::followLoadModulations) + && ret; } - if ((section = ini.find("reservoir capacity"))) + if (IniFile::Section* section = ini.find("use water")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.reservoirCapacity) && ret; - if (area->hydro.reservoirCapacity < 1e-6) - { - logs.error() << area->id << ": Invalid reservoir capacity."; - area->hydro.reservoirCapacity = 0.; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::useWaterValue) + && ret; } - // Check on reservoir capacity (has to be done after reservoir management and capacity reading, - // not before). Some areas reservoir capacities may not be printed in hydro ini file when saving - // the study, because they are too small (< 1e-6). We cannot have reservoir management = yes and - // capacity = 0 because of further division by capacity. reservoir management = no and capacity - // = 0 is possible (no use of capacity further) - study.areas.each([&](Data::Area& area) { - if (area.hydro.reservoirCapacity < 1e-3 && area.hydro.reservoirManagement) - { - logs.error() << area.name << ": reservoir capacity not defined. Impossible to manage."; - ret = false && ret; - } - }); + if (IniFile::Section* section = ini.find("hard bounds")) + { + ret = loadProperties(study, + section->firstProperty, + buffer, + &PartHydro::hardBoundsOnRuleCurves) + && ret; + } - if ((section = ini.find("inter-monthly-breakdown"))) + if (IniFile::Section* section = ini.find("use heuristic")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.intermonthlyBreakdown) && ret; - if (area->hydro.intermonthlyBreakdown < 0) - { - logs.error() << area->id << ": Invalid intermonthly breakdown"; - area->hydro.intermonthlyBreakdown = 0.; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::useHeuristicTarget) + && ret; } - if ((section = ini.find("follow load"))) + + if (IniFile::Section* section = ini.find("power to level")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.followLoadModulations) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::powerToLevel) + && ret; } - if ((section = ini.find("use water"))) + + if (IniFile::Section* section = ini.find("initialize reservoir date")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.useWaterValue) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, + section->firstProperty, + buffer, + &PartHydro::initializeReservoirLevelDate) + && ret; } - if ((section = ini.find("hard bounds"))) + + if (IniFile::Section* section = ini.find("use leeway")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.hardBoundsOnRuleCurves) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::useLeeway) && ret; } - if ((section = ini.find("use heuristic"))) + + if (IniFile::Section* section = ini.find("leeway low")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.useHeuristicTarget) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::leewayLowerBound) + && ret; } - if ((section = ini.find("power to level"))) + + if (IniFile::Section* section = ini.find("leeway up")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.powerToLevel) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::leewayUpperBound) + && ret; } - if ((section = ini.find("initialize reservoir date"))) + + if (IniFile::Section* section = ini.find("pumping efficiency")) { - if ((property = section->firstProperty)) - { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.initializeReservoirLevelDate) && ret; - if (area->hydro.initializeReservoirLevelDate < 0) - { - logs.error() << area->id << ": Invalid initialize reservoir date"; - area->hydro.initializeReservoirLevelDate = 0; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } - } + ret = loadProperties(study, section->firstProperty, buffer, &PartHydro::pumpingEfficiency) + && ret; } - // Leeways : use leeway bounds (upper and lower) - if ((section = ini.find("use leeway"))) + + return ret; +} + +bool PartHydro::checkReservoirLevels(const Study& study) +{ + bool ret = true; + + for (const auto& [areaName, area]: study.areas) { - if ((property = section->firstProperty)) + if (!study.usedByTheSolver) { - // Browse all properties - for (; property; property = property->next) - { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - ret = property->value.to(area->hydro.useLeeway) && ret; - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; - } + return true; } - } - if ((section = ini.find("leeway low"))) - { - if ((property = section->firstProperty)) + + auto& col = area->hydro.inflowPattern[0]; + bool errorInflow = false; + for (unsigned int day = 0; day < DAYS_PER_YEAR; day++) { - // Browse all properties - for (; property; property = property->next) + if (col[day] < 0 && !errorInflow) { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.leewayLowerBound) && ret; - if (area->hydro.leewayLowerBound < 0.) - { - logs.error() - << area->id << ": Invalid leeway lower bound. It must be >= 0.0, Got " - << area->hydro.leewayLowerBound; - area->hydro.leewayLowerBound = 0.; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; + logs.error() << areaName << ": invalid inflow value"; + errorInflow = true; + ret = false; } } - } - if ((section = ini.find("leeway up"))) - { - if ((property = section->firstProperty)) + bool errorLevels = false; + auto& colMin = area->hydro.reservoirLevel[minimum]; + auto& colAvg = area->hydro.reservoirLevel[average]; + auto& colMax = area->hydro.reservoirLevel[maximum]; + for (unsigned int day = 0; day < DAYS_PER_YEAR; day++) { - // Browse all properties - for (; property; property = property->next) + if (!errorLevels + && (colMin[day] < 0 || colAvg[day] < 0 || colMin[day] > colMax[day] + || colAvg[day] > 100 || colMax[day] > 100)) { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.leewayUpperBound) && ret; - if (area->hydro.leewayUpperBound < 0.) - { - logs.error() - << area->id << ": Invalid leeway upper bound. It must be >= 0.0, Got " - << area->hydro.leewayUpperBound; - area->hydro.leewayUpperBound = 0.; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; + logs.error() << areaName << ": invalid reservoir level value"; + errorLevels = true; + ret = false; } } - } - - // they are too small (< 1e-6). We cannot allow these areas to have reservoir management = - // true. - study.areas.each([&](Data::Area& area) { - if (area.hydro.leewayLowerBound > area.hydro.leewayUpperBound) - logs.error() << area.id << ": Leeway lower bound greater than leeway upper bound."; - }); - if ((section = ini.find("pumping efficiency"))) - { - if ((property = section->firstProperty)) + for (int i = 0; i < 101; i++) { - // Browse all properties - for (; property; property = property->next) + if ((area->hydro.creditModulation[i][0] < 0) + || (area->hydro.creditModulation[i][1] < 0)) { - AreaName id = property->key; - id.toLower(); - - auto* area = study.areas.find(id); - if (area) - { - ret = property->value.to(area->hydro.pumpingEfficiency) && ret; - if (area->hydro.pumpingEfficiency < 0) - { - logs.error() << area->id << ": Invalid pumping efficiency"; - area->hydro.pumpingEfficiency = 0.; - } - } - else - logs.warning() << buffer << ": `" << id << "`: Unknown area"; + logs.error() << areaName << ": invalid credit modulation value"; + ret = false; } } } - study.areas.each([&](Data::Area& area) { - if (not area.hydro.useHeuristicTarget && not area.hydro.useWaterValue) - { - logs.error() << area.name - << " : use water value = no conflicts with use heuristic target = no"; - ret = false && ret; - } - }); + return ret; +} + +bool PartHydro::checkProperties(Study& study) +{ + bool ret = true; + + // Check on reservoir capacity (has to be done after reservoir management and capacity reading, + // not before). Some areas reservoir capacities may not be printed in hydro ini file when saving + // the study, because they are too small (< 1e-6). We cannot have reservoir management = yes and + // capacity = 0 because of further division by capacity. reservoir management = no and capacity + // = 0 is possible (no use of capacity further) + study.areas.each( + [&ret](Data::Area& area) + { + if (area.hydro.reservoirCapacity < 1e-3 && area.hydro.reservoirManagement) + { + logs.error() << area.name + << ": reservoir capacity not defined. Impossible to manage."; + ret = false; + } + + if (!area.hydro.useHeuristicTarget && !area.hydro.useWaterValue) + { + logs.error() << area.name + << " : use water value = no conflicts with use heuristic target = no"; + ret = false; + } + + if (area.hydro.intraDailyModulation < 1.) + { + logs.error() << area.id << ": Invalid intra-daily modulation. It must be >= 1.0, Got " + << area.hydro.intraDailyModulation << " (truncated to 1)"; + area.hydro.intraDailyModulation = 1.; + } + + if (area.hydro.reservoirCapacity < 0) + { + logs.error() << area.id << ": Invalid reservoir capacity."; + area.hydro.reservoirCapacity = 0.; + } + + if (area.hydro.intermonthlyBreakdown < 0) + { + logs.error() << area.id << ": Invalid intermonthly breakdown"; + area.hydro.intermonthlyBreakdown = 0.; + } + + if (area.hydro.initializeReservoirLevelDate < 0) + { + logs.error() << area.id << ": Invalid initialize reservoir date"; + area.hydro.initializeReservoirLevelDate = 0; + } + + if (area.hydro.leewayLowerBound < 0.) + { + logs.error() << area.id << ": Invalid leeway lower bound. It must be >= 0.0, Got " + << area.hydro.leewayLowerBound; + area.hydro.leewayLowerBound = 0.; + } + + if (area.hydro.leewayUpperBound < 0.) + { + logs.error() << area.id << ": Invalid leeway upper bound. It must be >= 0.0, Got " + << area.hydro.leewayUpperBound; + area.hydro.leewayUpperBound = 0.; + } + + if (area.hydro.leewayLowerBound > area.hydro.leewayUpperBound) + { + logs.error() << area.id << ": Leeway lower bound greater than leeway upper bound."; + } + + if (area.hydro.pumpingEfficiency < 0) + { + logs.error() << area.id << ": Invalid pumping efficiency"; + area.hydro.pumpingEfficiency = 0.; + } + }); return ret; } +bool PartHydro::validate(Study& study) +{ + bool ret = checkReservoirLevels(study); + return checkProperties(study) && ret; +} + bool PartHydro::SaveToFolder(const AreaList& areas, const AnyString& folder) { if (!folder) @@ -642,72 +490,120 @@ bool PartHydro::SaveToFolder(const AreaList& areas, const AnyString& folder) String buffer; buffer.clear() << folder << SEP << "common" << SEP << "capacity"; + struct AllSections + { + IniFile::Section* s; + IniFile::Section* smod; + IniFile::Section* sIMB; + IniFile::Section* sreservoir; + IniFile::Section* sreservoirCapacity; + IniFile::Section* sFollowLoad; + IniFile::Section* sUseWater; + IniFile::Section* sHardBounds; + IniFile::Section* sInitializeReservoirDate; + IniFile::Section* sUseHeuristic; + IniFile::Section* sUseLeeway; + IniFile::Section* sPowerToLevel; + IniFile::Section* sLeewayLow; + IniFile::Section* sLeewayUp; + IniFile::Section* spumpingEfficiency; + + AllSections(IniFile& ini): + s(ini.addSection("inter-daily-breakdown")), + smod(ini.addSection("intra-daily-modulation")), + sIMB(ini.addSection("inter-monthly-breakdown")), + sreservoir(ini.addSection("reservoir")), + sreservoirCapacity(ini.addSection("reservoir capacity")), + sFollowLoad(ini.addSection("follow load")), + sUseWater(ini.addSection("use water")), + sHardBounds(ini.addSection("hard bounds")), + sInitializeReservoirDate(ini.addSection("initialize reservoir date")), + sUseHeuristic(ini.addSection("use heuristic")), + sUseLeeway(ini.addSection("use leeway")), + sPowerToLevel(ini.addSection("power to level")), + sLeewayLow(ini.addSection("leeway low")), + sLeewayUp(ini.addSection("leeway up")), + spumpingEfficiency(ini.addSection("pumping efficiency")) + { + } + }; + // Init IniFile ini; - auto* s = ini.addSection("inter-daily-breakdown"); - auto* smod = ini.addSection("intra-daily-modulation"); - auto* sIMB = ini.addSection("inter-monthly-breakdown"); - auto* sreservoir = ini.addSection("reservoir"); - auto* sreservoirCapacity = ini.addSection("reservoir capacity"); - auto* sFollowLoad = ini.addSection("follow load"); - auto* sUseWater = ini.addSection("use water"); - auto* sHardBounds = ini.addSection("hard bounds"); - auto* sInitializeReservoirDate = ini.addSection("initialize reservoir date"); - auto* sUseHeuristic = ini.addSection("use heuristic"); - auto* sUseLeeway = ini.addSection("use leeway"); - auto* sPowerToLevel = ini.addSection("power to level"); - auto* sLeewayLow = ini.addSection("leeway low"); - auto* sLeewayUp = ini.addSection("leeway up"); - auto* spumpingEfficiency = ini.addSection("pumping efficiency"); + AllSections allSections(ini); // return status bool ret = true; // Add all alpha values for each area - areas.each([&](const Data::Area& area) { - s->add(area.id, area.hydro.interDailyBreakdown); - smod->add(area.id, area.hydro.intraDailyModulation); - sIMB->add(area.id, area.hydro.intermonthlyBreakdown); - sInitializeReservoirDate->add(area.id, area.hydro.initializeReservoirLevelDate); - sLeewayLow->add(area.id, area.hydro.leewayLowerBound); - sLeewayUp->add(area.id, area.hydro.leewayUpperBound); - spumpingEfficiency->add(area.id, area.hydro.pumpingEfficiency); - if (area.hydro.reservoirCapacity > 1e-6) - sreservoirCapacity->add(area.id, area.hydro.reservoirCapacity); - if (area.hydro.reservoirManagement) - sreservoir->add(area.id, true); - if (!area.hydro.followLoadModulations) - sFollowLoad->add(area.id, false); - if (area.hydro.useWaterValue) - sUseWater->add(area.id, true); - if (area.hydro.hardBoundsOnRuleCurves) - sHardBounds->add(area.id, true); - if (!area.hydro.useHeuristicTarget) - sUseHeuristic->add(area.id, false); - if (area.hydro.useLeeway) - sUseLeeway->add(area.id, true); - if (area.hydro.powerToLevel) - sPowerToLevel->add(area.id, true); - // max power - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "maxpower_" - << area.id << ".txt"; - ret = area.hydro.maxPower.saveToCSVFile(buffer, /*decimal*/ 2) && ret; - // credit modulations - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP - << "creditmodulations_" << area.id << ".txt"; - ret = area.hydro.creditModulation.saveToCSVFile(buffer, /*decimal*/ 2) && ret; - // inflow pattern - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "inflowPattern_" - << area.id << ".txt"; - ret = area.hydro.inflowPattern.saveToCSVFile(buffer, /*decimal*/ 3) && ret; - // reservoir - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "reservoir_" - << area.id << ".txt"; - ret = area.hydro.reservoirLevel.saveToCSVFile(buffer, /*decimal*/ 3) && ret; - buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "waterValues_" - << area.id << ".txt"; - ret = area.hydro.waterValues.saveToCSVFile(buffer, /*decimal*/ 2) && ret; - }); + areas.each( + [&allSections, &buffer, &folder, &ret](const Data::Area& area) + { + allSections.s->add(area.id, area.hydro.interDailyBreakdown); + allSections.smod->add(area.id, area.hydro.intraDailyModulation); + allSections.sIMB->add(area.id, area.hydro.intermonthlyBreakdown); + allSections.sInitializeReservoirDate->add(area.id, + area.hydro.initializeReservoirLevelDate); + allSections.sLeewayLow->add(area.id, area.hydro.leewayLowerBound); + allSections.sLeewayUp->add(area.id, area.hydro.leewayUpperBound); + allSections.spumpingEfficiency->add(area.id, area.hydro.pumpingEfficiency); + if (area.hydro.reservoirCapacity > 1e-6) + { + allSections.sreservoirCapacity->add(area.id, area.hydro.reservoirCapacity); + } + if (area.hydro.reservoirManagement) + { + allSections.sreservoir->add(area.id, true); + } + if (!area.hydro.followLoadModulations) + { + allSections.sFollowLoad->add(area.id, false); + } + if (area.hydro.useWaterValue) + { + allSections.sUseWater->add(area.id, true); + } + if (area.hydro.hardBoundsOnRuleCurves) + { + allSections.sHardBounds->add(area.id, true); + } + if (!area.hydro.useHeuristicTarget) + { + allSections.sUseHeuristic->add(area.id, false); + } + if (area.hydro.useLeeway) + { + allSections.sUseLeeway->add(area.id, true); + } + if (area.hydro.powerToLevel) + { + allSections.sPowerToLevel->add(area.id, true); + } + + // max hours gen + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "maxDailyGenEnergy_" << area.id << ".txt"; + ret = area.hydro.dailyNbHoursAtGenPmax.saveToCSVFile(buffer, /*decimal*/ 2) && ret; + // max hours pump + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "maxDailyPumpEnergy_" << area.id << ".txt"; + ret = area.hydro.dailyNbHoursAtPumpPmax.saveToCSVFile(buffer, /*decimal*/ 2) && ret; + // credit modulations + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "creditmodulations_" << area.id << ".txt"; + ret = area.hydro.creditModulation.saveToCSVFile(buffer, /*decimal*/ 2) && ret; + // inflow pattern + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "inflowPattern_" << area.id << ".txt"; + ret = area.hydro.inflowPattern.saveToCSVFile(buffer, /*decimal*/ 3) && ret; + // reservoir + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "reservoir_" + << area.id << ".txt"; + ret = area.hydro.reservoirLevel.saveToCSVFile(buffer, /*decimal*/ 3) && ret; + buffer.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "waterValues_" + << area.id << ".txt"; + ret = area.hydro.waterValues.saveToCSVFile(buffer, /*decimal*/ 2) && ret; + }); // Write the ini file buffer.clear() << folder << SEP << "hydro.ini"; @@ -717,42 +613,46 @@ bool PartHydro::SaveToFolder(const AreaList& areas, const AnyString& folder) bool PartHydro::forceReload(bool reload) const { bool ret = true; - ret = maxPower.forceReload(reload) && ret; ret = creditModulation.forceReload(reload) && ret; ret = inflowPattern.forceReload(reload) && ret; ret = reservoirLevel.forceReload(reload) && ret; ret = waterValues.forceReload(reload) && ret; + ret = dailyNbHoursAtGenPmax.forceReload(reload) && ret; + ret = dailyNbHoursAtPumpPmax.forceReload(reload) && ret; if (series) + { ret = series->forceReload(reload) && ret; + } if (prepro) + { ret = prepro->forceReload(reload) && ret; + } return ret; } void PartHydro::markAsModified() const { - maxPower.markAsModified(); inflowPattern.markAsModified(); reservoirLevel.markAsModified(); waterValues.markAsModified(); creditModulation.markAsModified(); + dailyNbHoursAtGenPmax.markAsModified(); + dailyNbHoursAtPumpPmax.markAsModified(); if (series) + { series->markAsModified(); + } if (prepro) + { prepro->markAsModified(); + } } void PartHydro::copyFrom(const PartHydro& rhs) { - // max power - { - maxPower = rhs.maxPower; - maxPower.unloadFromMemory(); - rhs.maxPower.unloadFromMemory(); - } // credit modulations { creditModulation = rhs.creditModulation; @@ -795,23 +695,92 @@ void PartHydro::copyFrom(const PartHydro& rhs) leewayLowerBound = rhs.leewayLowerBound; pumpingEfficiency = rhs.pumpingEfficiency; } + + // max daily gen + { + dailyNbHoursAtGenPmax = rhs.dailyNbHoursAtGenPmax; + dailyNbHoursAtGenPmax.unloadFromMemory(); + rhs.dailyNbHoursAtGenPmax.unloadFromMemory(); + } + + // max daily pump + { + dailyNbHoursAtPumpPmax = rhs.dailyNbHoursAtPumpPmax; + dailyNbHoursAtPumpPmax.unloadFromMemory(); + rhs.dailyNbHoursAtPumpPmax.unloadFromMemory(); + } } -void getWaterValue(const double& level /* format : in % of reservoir capacity */, - const Matrix& waterValues, - const uint day, - double& waterValueToReturn) +bool PartHydro::LoadDailyMaxEnergy(const AnyString& folder, const AnyString& areaid) +{ + YString filePath; + Matrix<>::BufferType fileContent; + bool ret = true; + + filePath.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "maxDailyGenEnergy_" << areaid << ".txt"; + + ret = dailyNbHoursAtGenPmax.loadFromCSVFile(filePath, + 1, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &fileContent) + && ret; + + filePath.clear() << folder << SEP << "common" << SEP << "capacity" << SEP + << "maxDailyPumpEnergy_" << areaid << ".txt"; + + ret = dailyNbHoursAtPumpPmax.loadFromCSVFile(filePath, + 1, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &fileContent) + && ret; + + return ret; +} + +bool PartHydro::CheckDailyMaxEnergy(const AnyString& areaName) +{ + bool ret = true; + bool errorEnergy = false; + auto& colGen = dailyNbHoursAtGenPmax[0]; + auto& colPump = dailyNbHoursAtPumpPmax[0]; + + for (unsigned int day = 0; day < DAYS_PER_YEAR; day++) + { + if (!errorEnergy && (colGen[day] < 0 || (colGen[day] > 24))) + { + logs.error() << areaName << ": invalid maximum generation energy value"; + errorEnergy = true; + ret = false; + } + + if (!errorEnergy && (colPump[day] < 0 || (colPump[day] > 24))) + { + logs.error() << areaName << ": invalid maximum pumping energy value"; + errorEnergy = true; + ret = false; + } + } + + return ret; +} + +double getWaterValue(const double& level /* format : in % of reservoir capacity */, + const Matrix& waterValues, + const uint day) { assert((level >= 0. && level <= 100.) && "getWaterValue function : invalid level"); double levelUp = ceil(level); double levelDown = floor(level); if ((int)(levelUp) == (int)(levelDown)) - waterValueToReturn = waterValues[(int)(levelUp)][day]; - else - waterValueToReturn - = waterValues[(int)(levelUp)][day] * (level - levelDown) - + waterValues[(int)(levelDown)][day] * (levelUp - level); + { + return waterValues[(int)(levelUp)][day]; + } + return waterValues[(int)(levelUp)][day] * (level - levelDown) + + waterValues[(int)(levelDown)][day] * (levelUp - level); } double getWeeklyModulation(const double& level /* format : in % of reservoir capacity */, @@ -823,13 +792,16 @@ double getWeeklyModulation(const double& level /* format : in % of reservoir cap double levelUp = ceil(level); double levelDown = floor(level); if ((int)(levelUp) == (int)(levelDown)) + { valueToReturn = creditMod[(int)(levelUp)][modType]; + } else + { valueToReturn = creditMod[(int)(levelUp)][modType] * (level - levelDown) + creditMod[(int)(levelDown)][modType] * (levelUp - level); + } return valueToReturn; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h deleted file mode 100644 index 84f9f4cc8f..0000000000 --- a/src/libs/antares/study/parts/hydro/container.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ - -#include "prepro.h" -#include "series.h" -#include "../../fwd.h" -#include "allocation.h" - -namespace Antares::Data -{ -/*! -** \brief Hydro for a single area -*/ -class PartHydro -{ -public: - enum - { - //! The minimum value - minimum = 0, - //! The average value - average, - //! The maximum value - maximum, - }; - - enum powerDailyE - { - //! Generated max power - genMaxP = 0, - //! Generated max energy - genMaxE, - //! Pumping max Power - pumpMaxP, - // Pumping max Energy - pumpMaxE, - }; - - enum weeklyHydroMod - { - //! Weekly generating modulation - genMod = 0, - //! Weekly pumping modulation - pumpMod, - }; - -public: - /*! - ** \brief Load data for hydro container from a folder - ** - ** \param folder The targer folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - static bool LoadFromFolder(Study& study, const AnyString& folder); - - /*! - ** \brief Save data from several containers to a folder (except data for the prepro and - *time-series) - ** - ** \param l List of areas - ** \param folder The targer folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - static bool SaveToFolder(const AreaList& areas, const AnyString& folder); - -public: - /*! - ** \brief Default Constructor - */ - PartHydro(); - //! Destructor - ~PartHydro(); - - /*! - ** \brief Reset internal data - */ - void reset(); - - void copyFrom(const PartHydro& rhs); - - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark all data as modified - */ - void markAsModified() const; - -public: - //! Inter-daily breakdown (previously called Smoothing Factor or alpha) - double interDailyBreakdown; - //! Intra-daily modulation - double intraDailyModulation; - - //! Intermonthly breakdown - double intermonthlyBreakdown; - - //! Enabled reservoir management - bool reservoirManagement; - - //! Following load modulation - bool followLoadModulations; - //! Use water values - bool useWaterValue; - //! Hard bound on rule curves - bool hardBoundsOnRuleCurves; - //! Use heuristic target - bool useHeuristicTarget; - //! Reservoir capacity (MWh) - double reservoirCapacity; - // gp : pb - initializeReservoirLevelDate must be an enum from january (= 0) to december (= 11) - //! Initialize reservoir level date (month) - int initializeReservoirLevelDate; - //! Use Leeway - bool useLeeway; - //! Power to level modulations - bool powerToLevel; - //! Leeway low bound - double leewayLowerBound; - //! Leeway upper bound - double leewayUpperBound; - //! Puming efficiency - double pumpingEfficiency; - //! Daily max power ({generating max Power, generating max energy, pumping max power, pumping - //! max energy}x365) - Matrix maxPower; - //! Credit Modulation (default 0, 101 * 2) - Matrix creditModulation; - - //! Daily Inflow Patern ([default 1, 0 inflowPattern; - - // Useful for solver RAM estimation - bool hydroModulable; - - //! Daily reservoir level ({min,avg,max}x365) - Matrix reservoirLevel; - - //! Daily water value ({0,1,2%...100%}x365) - Matrix waterValues; - - //! Hydro allocation, from other areas - HydroAllocation allocation; - - //! Data for the pre-processor - PreproHydro* prepro; - //! Data for time-series - DataSeriesHydro* series; - -}; // class PartHydro - - -// Interpolates a water value from a table according to a level and a day. -// As this function can be called a lot of times, we pass working variables and returned variables -// as arguments, so that we don't have to create them locally (as in a classical function) each -// time. -void getWaterValue(const double& level, - const Matrix& waterValues, - const uint day, - double& waterValueToReturn); - -// Interpolates a rate from the credit modulation table according to a level -double getWeeklyModulation(const double& level /* format : in % of reservoir capacity */, - Matrix& creditMod, - int modType); - -} // namespace Antares::Data - -#include - -#endif /* __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ */ diff --git a/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp b/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp new file mode 100644 index 0000000000..c0834441a1 --- /dev/null +++ b/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp @@ -0,0 +1,171 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ + +#include "antares/study/parts/hydro/finalLevelValidator.h" + +namespace Antares::Data +{ + +FinalLevelValidator::FinalLevelValidator(PartHydro& hydro, + unsigned int areaIndex, + const AreaName areaName, // gp : to std::string + double initialLevel, + double finalLevel, + const unsigned int year, + const unsigned int lastSimulationDay, + const unsigned int firstMonthOfSimulation): + year_(year), + lastSimulationDay_(lastSimulationDay), + firstMonthOfSimulation_(firstMonthOfSimulation), + hydro_(hydro), + areaIndex_(areaIndex), + areaName_(areaName), + initialLevel_(initialLevel), + finalLevel_(finalLevel) +{ +} + +bool FinalLevelValidator::check() +{ + if (skippingFinalLevelUse()) + { + return true; + } + if (!checkForInfeasibility()) + { + return false; + } + finalLevelFineForUse_ = true; + return true; +} + +bool FinalLevelValidator::skippingFinalLevelUse() +{ + if (!wasSetInScenarioBuilder()) + { + return true; + } + if (!compatibleWithReservoirProperties()) + { + return true; + } + return false; +} + +bool FinalLevelValidator::wasSetInScenarioBuilder() +{ + return !isnan(finalLevel_); +} + +bool FinalLevelValidator::compatibleWithReservoirProperties() +{ + if (hydro_.reservoirManagement && !hydro_.useWaterValue) + { + return true; + } + + logs.warning() + << "Final reservoir level not applicable! Year:" << year_ + 1 << ", Area:" << areaName_ + << ". Check: Reservoir management = Yes, Use water values = No and proper initial " + "reservoir level is provided "; + return false; +} + +bool FinalLevelValidator::checkForInfeasibility() +{ + bool checksOk = hydroAllocationStartMatchesSimulation(); + checksOk = isFinalLevelReachable() && checksOk; + checksOk = isBetweenRuleCurves() && checksOk; + + return checksOk; +} + +bool FinalLevelValidator::hydroAllocationStartMatchesSimulation() const +{ + unsigned initReservoirLvlMonth = hydro_.initializeReservoirLevelDate; // month [0-11] + if (lastSimulationDay_ == DAYS_PER_YEAR && initReservoirLvlMonth == firstMonthOfSimulation_) + { + return true; + } + + logs.error() << "Year " << year_ + 1 << ", area '" << areaName_ + << "' : " << "Hydro allocation must start on the 1st simulation month and " + << "simulation last a whole year"; + return false; +} + +bool FinalLevelValidator::isFinalLevelReachable() const +{ + double reservoirCapacity = hydro_.reservoirCapacity; + double totalYearInflows = calculateTotalInflows(); + + if ((finalLevel_ - initialLevel_) * reservoirCapacity > totalYearInflows) + { + logs.error() << "Year: " << year_ + 1 << ". Area: " << areaName_ + << ". Incompatible total inflows: " << totalYearInflows + << " with initial: " << initialLevel_ << " and final: " << finalLevel_ + << " reservoir levels."; + return false; + } + return true; +} + +double FinalLevelValidator::calculateTotalInflows() const +{ + // calculate yearly inflows + const auto& srcinflows = hydro_.series->storage.getColumn(year_); + + double totalYearInflows = 0.0; + for (unsigned int day = 0; day < DAYS_PER_YEAR; ++day) + { + totalYearInflows += srcinflows[day]; + } + return totalYearInflows; +} + +bool FinalLevelValidator::isBetweenRuleCurves() const +{ + double lowLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + double highLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + + if (finalLevel_ < lowLevelLastDay || finalLevel_ > highLevelLastDay) + { + logs.error() << "Year: " << year_ + 1 << ". Area: " << areaName_ + << ". Specifed final reservoir level: " << finalLevel_ + << " is incompatible with reservoir level rule curve [" << lowLevelLastDay + << " , " << highLevelLastDay << "]"; + return false; + } + return true; +} + +bool FinalLevelValidator::finalLevelFineForUse() +{ + return finalLevelFineForUse_; +} + +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/hydro/hydromaxtimeseriesreader.cpp b/src/libs/antares/study/parts/hydro/hydromaxtimeseriesreader.cpp new file mode 100644 index 0000000000..fa2827fc88 --- /dev/null +++ b/src/libs/antares/study/parts/hydro/hydromaxtimeseriesreader.cpp @@ -0,0 +1,152 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ + +#include "antares/study/parts/hydro/hydromaxtimeseriesreader.h" + +#include +#include "antares/study/study.h" + +using namespace Yuni; + +#define SEP IO::Separator + +namespace Antares::Data +{ + +HydroMaxTimeSeriesReader::HydroMaxTimeSeriesReader(PartHydro& hydro, + std::string areaID, + std::string areaName): + hydro_(hydro), + areaID_(areaID), + areaName_(areaName) +{ + dailyMaxPumpAndGen.reset(4U, DAYS_PER_YEAR, true); +} + +static bool checkPower(const Matrix<>& dailyMaxPumpAndGen, const std::string& areaName) +{ + for (uint i = 0; i < 4U; ++i) + { + auto& col = dailyMaxPumpAndGen[i]; + for (uint day = 0; day < DAYS_PER_YEAR; ++day) + { + if (col[day] < 0. || (i % 2U /*column hours*/ && col[day] > 24.)) + { + logs.error() << areaName << ": invalid power or energy value"; + return false; + } + } + } + + return true; +} + +bool HydroMaxTimeSeriesReader::loadDailyMaxPowersAndEnergies(const AnyString& folder, + bool usedBySolver) +{ + YString filePath; + Matrix<>::BufferType fileContent; + bool ret = true; + + filePath.clear() << folder << SEP << "common" << SEP << "capacity" << SEP << "maxpower_" + << areaID_ << ".txt"; + + // It is necessary to load maxpower_ txt file, whether loading is called from old GUI + // or from solver. + + if (!usedBySolver) + { + bool enabledModeIsChanged = false; + + if (JIT::enabled) + { + JIT::enabled = false; // Allowing to read the area's daily max power and energy + enabledModeIsChanged = true; + } + + ret = dailyMaxPumpAndGen.loadFromCSVFile(filePath, + 4U, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &fileContent) + && ret; + + if (enabledModeIsChanged) + { + JIT::enabled = true; // Back to the previous loading mode. + } + } + else + { + ret = dailyMaxPumpAndGen.loadFromCSVFile(filePath, + 4U, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &fileContent) + && ret; + } + return ret; +} + +void HydroMaxTimeSeriesReader::copyDailyMaxEnergy() const +{ + copyDailyMaxGenerationEnergy(); + copyDailyMaxPumpingEnergy(); +} + +void HydroMaxTimeSeriesReader::copyDailyMaxGenerationEnergy() const +{ + auto& dailyNbHoursAtGenPmax = hydro_.dailyNbHoursAtGenPmax; + const auto& dailyMaxGenE = dailyMaxPumpAndGen[genMaxE]; + + dailyNbHoursAtGenPmax.reset(1U, DAYS_PER_YEAR, true); + + dailyNbHoursAtGenPmax.pasteToColumn(0, dailyMaxGenE); +} + +void HydroMaxTimeSeriesReader::copyDailyMaxPumpingEnergy() const +{ + auto& dailyNbHoursAtPumpPmax = hydro_.dailyNbHoursAtPumpPmax; + const auto& dailyMaxPumpE = dailyMaxPumpAndGen[pumpMaxE]; + + dailyNbHoursAtPumpPmax.reset(1U, DAYS_PER_YEAR, true); + + dailyNbHoursAtPumpPmax.pasteToColumn(0, dailyMaxPumpE); +} + +bool HydroMaxTimeSeriesReader::read(const AnyString& folder, bool usedBySolver) +{ + bool ret = loadDailyMaxPowersAndEnergies(folder, usedBySolver); + ret = checkPower(dailyMaxPumpAndGen, areaName_) && ret; + copyDailyMaxEnergy(); + hydro_.series->buildHourlyMaxPowerFromDailyTS(dailyMaxPumpAndGen[genMaxP], + dailyMaxPumpAndGen[pumpMaxP]); + + return ret; +} + +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/hydro/prepro.cpp b/src/libs/antares/study/parts/hydro/prepro.cpp index 42efe5d048..13711759f4 100644 --- a/src/libs/antares/study/parts/hydro/prepro.cpp +++ b/src/libs/antares/study/parts/hydro/prepro.cpp @@ -1,37 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/hydro/prepro.h" + #include -#include #include -#include "../../study.h" -#include "prepro.h" +#include + #include #include +#include "antares/study/study.h" using namespace Antares; using namespace Yuni; @@ -50,7 +46,7 @@ static bool PreproHydroSaveSettings(PreproHydro* h, const char* filename) return ini.save(filename); } -static bool PreproHydroLoadSettings(PreproHydro* h, const char* filename) +static bool PreproHydroLoadSettings(PreproHydro* h, const std::string& filename) { IniFile ini; IniFile::Section* s; @@ -72,16 +68,22 @@ static bool PreproHydroLoadSettings(PreproHydro* h, const char* filename) ret = t.to(h->intermonthlyCorrelation); } else + { logs.error() << filename << ": prepro/intermonthlyCorrelation: The property is missing"; + } } else + { logs.error() << filename << ": [prepro]: The section is missing"; + } return ret; } else + { logs.error() << filename << ": Impossible to open the file"; + } return false; } @@ -103,7 +105,9 @@ void PreproHydro::reset() // Expectation auto& col = data[expectation]; for (uint i = 0; i != 12; ++i) + { col[i] = 0.; + } } void PreproHydro::copyFrom(const PreproHydro& rhs) @@ -141,99 +145,98 @@ bool PreproHydro::saveToFolder(const AreaName& areaID, const char* folder) return false; } -bool PreproHydro::loadFromFolder(Study& s, const AreaName& areaID, const char* folder) +bool PreproHydro::loadFromFolder(Study& s, const AreaName& areaID, const std::string& folder) { - /* Asserts */ - assert(folder); - assert('\0' != *folder); - enum { mtrxOption = Matrix<>::optFixedSize | Matrix<>::optImmediate, }; + constexpr int maxNbOfLineToLoad = 12; + data.resize(hydroPreproMax, 12, true); String& buffer = s.bufferLoadingTS; buffer.clear() << folder << SEP << areaID << SEP << "prepro.ini"; - bool ret = (PreproHydroLoadSettings(this, buffer.c_str()) ? true : false); + bool ret = PreproHydroLoadSettings(this, buffer); + + buffer.clear() << folder << SEP << areaID << SEP << "energy.txt"; + ret = data.loadFromCSVFile(buffer, hydroPreproMax, maxNbOfLineToLoad, mtrxOption, &s.dataBuffer) + && ret; + + return ret; +} + +bool PreproHydro::validate(const std::string& areaID) +{ + bool ret = true; + if (intermonthlyCorrelation < 0. || intermonthlyCorrelation > 1.) { logs.error() << "Hydro: Prepro: `" << areaID << "`: Intermonthly correlation value: The value must be between 0 and 1"; if (intermonthlyCorrelation < 0.) + { intermonthlyCorrelation = 0.; + } else + { intermonthlyCorrelation = 1.; + } } - buffer.clear() << folder << SEP << areaID << SEP << "energy.txt"; - ret = data.loadFromCSVFile(buffer, hydroPreproMax, 12, mtrxOption, &s.dataBuffer) && ret; - - if (JIT::enabled) - return ret; - - // Checks + const auto& col = data[powerOverWater]; + for (unsigned i = 0; i != data.height; ++i) { - auto& col = data[powerOverWater]; - for (uint i = 0; i != data.height; ++i) + const double d = col[i]; + if (d < 0. || d > 1.) { - const double d = col[i]; - if (d < 0. || d > 1.) - logs.error() << "Hydro: Prepro: " << areaID - << ": invalid value for ROR (line: " << (i + 1) << ")"; + logs.error() << "Hydro: Prepro: " << areaID + << ": invalid value for ROR (line: " << (i + 1) << ")"; } } - { - auto& colMin = data[minimumEnergy]; - auto& colMax = data[maximumEnergy]; + const auto& colMin = data[minimumEnergy]; + const auto& colMax = data[maximumEnergy]; - for (uint i = 0; i != data.height; ++i) + for (unsigned i = 0; i != data.height; ++i) + { + if (colMin[i] < 0.) { - if (colMin[i] < 0.) - { - ret = false; - logs.error() << "Hydro: Prepro: `" << areaID - << "`: minimum energy: At least one value is negative (line: " - << (i + 1) << ')'; - continue; - } - if (colMin[i] > colMax[i]) - { - ret = false; - logs.error() << "Hydro: Prepro: `" << areaID - << "`: the minimum energy must be less than the maximum energy (line: " - << (i + 1) << ')'; - } + ret = false; + logs.error() << "Hydro: Prepro: `" << areaID + << "`: minimum energy: At least one value is negative (line: " << (i + 1) + << ')'; + continue; + } + if (colMin[i] > colMax[i]) + { + ret = false; + logs.error() << "Hydro: Prepro: `" << areaID + << "`: the minimum energy must be less than the maximum energy (line: " + << (i + 1) << ')'; } } + const auto& colExp = data[expectation]; + for (unsigned i = 0; i != data.height; i++) { - auto& colExp = data[expectation]; - - for (uint i = 0; i != data.height; i++) + if (colExp[i] < 0.) { - if (colExp[i] < 0.) - { - ret = false; - logs.error() << "Hydro: Prepro: `" << areaID - << "`: invalid value for expectation (line: " << (i + 1) << ")"; - } + ret = false; + logs.error() << "Hydro: Prepro: `" << areaID + << "`: invalid value for expectation (line: " << (i + 1) << ")"; } } + const auto& colStdDev = data[stdDeviation]; + for (unsigned i = 0; i != data.height; i++) { - auto& colStdDev = data[stdDeviation]; - - for (uint i = 0; i != data.height; i++) + if (colStdDev[i] < 0.) { - if (colStdDev[i] < 0.) - { - ret = false; - logs.error() << "Hydro: Prepro: `" << areaID - << "`: invalid value for standard deviation (line: " << (i + 1) << ")"; - } + ret = false; + logs.error() << "Hydro: Prepro: `" << areaID + << "`: invalid value for standard deviation (line: " << (i + 1) << ")"; } } diff --git a/src/libs/antares/study/parts/hydro/prepro.h b/src/libs/antares/study/parts/hydro/prepro.h deleted file mode 100644 index 978a3c1f01..0000000000 --- a/src/libs/antares/study/parts/hydro/prepro.h +++ /dev/null @@ -1,141 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_PREPRO_H__ -#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_PREPRO_H__ - -#include -#include "../../fwd.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Data for the hydro preprocessor -** \ingroup hydroprepro -*/ -class PreproHydro -{ -public: - enum - { - /*! - ** \brief The expectation of the total capacity (Espérance du logarithme de 'energie totale) - ** - ** These values will be modified before launching a simulation. - ** The solver requires log(expectaction) and log(stddeviation) - */ - expectation = 0, - /*! - ** \brief The standard deviation of the total capacity (ecart-type du logarithme de - *l'energie totale) - ** - ** These values will be modified before launching a simulation. - ** The solver requires log(expectaction) and log(stddeviation) - */ - stdDeviation, - //! Minimum capacity per month - minimumEnergy, - //! Maximum capacity per month - maximumEnergy, - /*! - ** \brief Power over water - ** - ** Proportion du fil de l'eau : l'hydraulique est representee au travers de son - ** energie totale mensuelle; cette proportion est donc une proportion en énergie - ** La valeur peut varier entre 0 (pas de fil de l'eau) et 1 (pas d'hydraulique modulable) - */ - powerOverWater, - //! The maximum number of item - hydroPreproMax - - }; // anonymous enum - -public: - //! \name Constructor - //@{ - /*! - ** \brief Default constructor - */ - PreproHydro(); - //@} - - - - /*! - ** \brief Reset all data to their default values - */ - void reset(); - - /*! - ** \brief Copy data from another PreproHydro structure - */ - void copyFrom(const PreproHydro& rhs); - - /*! - ** \brief Load hydro settings for the prepro from a folder - ** - ** \param folder The source folder (ex: `input/hydro/prepro`) - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool loadFromFolder(Study& s, const AreaName& areaID, const char folder[]); - - /*! - ** \brief Save hydro settings for the prepro into a folder - ** - ** \param folder The target folder (ex: `input/hydro/prepro`) - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool saveToFolder(const AreaName& areaID, const char* folder); - - bool forceReload(bool reload = false) const; - - void markAsModified() const; - -public: - //! The intermonthly correlation value - double intermonthlyCorrelation; - //! data - Matrix<> data; - -}; // class PreproHydro - -int PreproHydroLoadFromFolder(Study& s, - PreproHydro* h, - const AreaName& areaID, - const char folder[]); - -/*! -** \brief Get the size (bytes) occupied in memory by a `PreproHydro` structure -** \ingroup hydroprepro -*/ -uint64_t PreproHydroMemoryUsage(PreproHydro* h); - -} // namespace Data -} // namespace Antares - -#endif /* __ANTARES_LIBS_STUDY_PARTS_HYDRO_PREPRO_H__ */ diff --git a/src/libs/antares/study/parts/hydro/series.cpp b/src/libs/antares/study/parts/hydro/series.cpp index d9b1c488b8..8c73772565 100644 --- a/src/libs/antares/study/parts/hydro/series.cpp +++ b/src/libs/antares/study/parts/hydro/series.cpp @@ -1,196 +1,122 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include + #include #include -#include -#include "series.h" + +#include #include #include -#include "../../study.h" +#include +#include "antares/study/study.h" using namespace Yuni; #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data { -DataSeriesHydro::DataSeriesHydro() : count(0) + +static bool loadTSfromFile(Matrix& ts, + const AreaName& areaID, + const AnyString& folder, + const std::string& filename, + unsigned int height) { - // Pmin was introduced in v8.6 - // The previous behavior was Pmin=0 - // For compatibility reasons with existing studies, mingen is set to one column of zeros - // by default - mingen.reset(1, HOURS_PER_YEAR); + YString filePath; + Matrix<>::BufferType fileContent; + filePath.clear() << folder << SEP << areaID << SEP << filename; + return ts.loadFromCSVFile(filePath, 1, height, &fileContent); } -bool DataSeriesHydro::saveToFolder(const AreaName& areaID, const AnyString& folder) const +static void ConvertDailyTSintoHourlyTS(const Matrix::ColumnType& dailyColumn, + Matrix::ColumnType& hourlyColumn) { - String buffer; - buffer.clear() << folder << SEP << areaID; - /* Make sure the folder is created */ - if (IO::Directory::Create(buffer)) - { - bool ret = true; + uint hour = 0; + uint day = 0; - // Saving data - buffer.clear() << folder << SEP << areaID << SEP << "ror.txt"; - ret = ror.saveToCSVFile(buffer, 0) && ret; - buffer.clear() << folder << SEP << areaID << SEP << "mod.txt"; - ret = storage.saveToCSVFile(buffer, 0) && ret; - buffer.clear() << folder << SEP << areaID << SEP << "mingen.txt"; - ret = mingen.saveToCSVFile(buffer, 0) && ret; - return ret; + while (hour < HOURS_PER_YEAR && day < DAYS_PER_YEAR) + { + for (uint i = 0; i < HOURS_PER_DAY; ++i) + { + hourlyColumn[hour] = dailyColumn[day]; + ++hour; + } + ++day; } - return false; } -bool DataSeriesHydro::loadFromFolder(Study& study, const AreaName& areaID, const AnyString& folder) +DataSeriesHydro::DataSeriesHydro(): + ror(timeseriesNumbers), + storage(timeseriesNumbers), + mingen(timeseriesNumbers), + maxHourlyGenPower(timeseriesNumbers), + maxHourlyPumpPower(timeseriesNumbers) { - bool ret = true; - auto& buffer = study.bufferLoadingTS; - - buffer.clear() << folder << SEP << areaID << SEP << "ror." << study.inputExtension; + timeseriesNumbers.registerSeries(&ror, "ror"); + timeseriesNumbers.registerSeries(&storage, "storage"); + timeseriesNumbers.registerSeries(&mingen, "mingen"); + timeseriesNumbers.registerSeries(&maxHourlyGenPower, "max-geneneration-power"); + timeseriesNumbers.registerSeries(&maxHourlyPumpPower, "max-pumping-power"); - ret = ror.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &study.dataBuffer) && ret; - - buffer.clear() << folder << SEP << areaID << SEP << "mod." << study.inputExtension; - ret = storage.loadFromCSVFile(buffer, 1, DAYS_PER_YEAR, &study.dataBuffer) && ret; - - // The number of time-series - count = storage.width; - - if (ror.width > count) - count = ror.width; + // Pmin was introduced in v8.6 + // The previous behavior was Pmin=0 + // For compatibility reasons with existing studies, mingen, maxHourlyGenPower and + // maxHourlyPumpPower are set to one column of zeros by default + mingen.reset(); + maxHourlyGenPower.reset(); + maxHourlyPumpPower.reset(); +} - if (study.header.version >= 860) - { - buffer.clear() << folder << SEP << areaID << SEP << "mingen." << study.inputExtension; - ret = mingen.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &study.dataBuffer) && ret; - } +void DataSeriesHydro::copyGenerationTS(const DataSeriesHydro& source) +{ + ror.timeSeries = source.ror.timeSeries; + storage.timeSeries = source.storage.timeSeries; + mingen.timeSeries = source.mingen.timeSeries; - if (study.usedByTheSolver) - { - if (0 == count) - { - logs.error() << "Hydro: `" << areaID - << "`: empty matrix detected. Fixing it with default values"; - ror.reset(1, HOURS_PER_YEAR); - storage.reset(1, DAYS_PER_YEAR); - mingen.reset(1, HOURS_PER_YEAR); - } - else - { - if (count > 1 && storage.width != ror.width) - { - if (ror.width != 1 && storage.width != 1) - { - logs.fatal() << "Hydro: `" << areaID - << "`: The matrices ROR (run-of-the-river) and hydro-storage must " - "have the same number of time-series."; - study.gotFatalError = true; - } - else - { - if (ror.width == 1) - { - ror.resizeWithoutDataLost(count, ror.height); - for (uint x = 1; x < count; ++x) - ror.pasteToColumn(x, ror[0]); - } - else - { - if (storage.width == 1) - { - storage.resizeWithoutDataLost(count, storage.height); - for (uint x = 1; x < count; ++x) - storage.pasteToColumn(x, storage[0]); - } - } - Area* areaToInvalidate = study.areas.find(areaID); - if (areaToInvalidate) - { - areaToInvalidate->invalidateJIT = true; - logs.info() - << " '" << areaID << "': The hydro data have been normalized to " - << count << " timeseries"; - } - else - logs.error() - << "Impossible to find the area `" << areaID << "` to invalidate it"; - } - } - checkMinGenTsNumber(study, areaID); - } + source.ror.unloadFromMemory(); + source.storage.unloadFromMemory(); + source.mingen.unloadFromMemory(); +} - if (study.parameters.derated) - { - ror.averageTimeseries(); - storage.averageTimeseries(); - mingen.averageTimeseries(); - count = 1; - } - } +void DataSeriesHydro::copyMaxPowerTS(const DataSeriesHydro& source) +{ + maxHourlyGenPower.timeSeries = source.maxHourlyGenPower.timeSeries; + maxHourlyPumpPower.timeSeries = source.maxHourlyPumpPower.timeSeries; - timeseriesNumbers.clear(); + source.maxHourlyGenPower.unloadFromMemory(); + source.maxHourlyPumpPower.unloadFromMemory(); +} - return ret; +void DataSeriesHydro::reset() +{ + resizeTS(1); } -void DataSeriesHydro::checkMinGenTsNumber(Study& study, const AreaName& areaID) +void DataSeriesHydro::resizeTS(uint nbSeries) { - if (mingen.width != storage.width) - { - if (mingen.width > 1) - { - logs.fatal() << "Hydro: `" << areaID - << "`: The matrices Minimum Generation must " - "has the same number of time-series as ROR and hydro-storage."; - study.gotFatalError = true; - } - else - { - mingen.resizeWithoutDataLost(count, mingen.height); - for (uint x = 1; x < count; ++x) - mingen.pasteToColumn(x, mingen[0]); - Area* areaToInvalidate = study.areas.find(areaID); - if (areaToInvalidate) - { - areaToInvalidate->invalidateJIT = true; - logs.info() << " '" << areaID - << "': The hydro minimum generation data have been normalized to " - << count << " timeseries"; - } - else - logs.error() << "Impossible to find the area `" << areaID << "` to invalidate it"; - } - } + storage.reset(nbSeries, DAYS_PER_YEAR); + ror.reset(nbSeries, HOURS_PER_YEAR); } bool DataSeriesHydro::forceReload(bool reload) const @@ -199,6 +125,8 @@ bool DataSeriesHydro::forceReload(bool reload) const ret = ror.forceReload(reload) && ret; ret = storage.forceReload(reload) && ret; ret = mingen.forceReload(reload) && ret; + ret = maxHourlyGenPower.forceReload(reload) && ret; + ret = maxHourlyPumpPower.forceReload(reload) && ret; return ret; } @@ -207,25 +135,119 @@ void DataSeriesHydro::markAsModified() const ror.markAsModified(); storage.markAsModified(); mingen.markAsModified(); + maxHourlyGenPower.markAsModified(); + maxHourlyPumpPower.markAsModified(); } -void DataSeriesHydro::reset() +bool DataSeriesHydro::loadGenerationTS(const AreaName& areaID, + const AnyString& folder, + StudyVersion studyVersion) { - ror.reset(1, HOURS_PER_YEAR); - storage.reset(1, DAYS_PER_YEAR); - mingen.reset(1, HOURS_PER_YEAR); - count = 1; + timeseriesNumbers.clear(); + + bool ret = loadTSfromFile(ror.timeSeries, areaID, folder, "ror.txt", HOURS_PER_YEAR); + ret = loadTSfromFile(storage.timeSeries, areaID, folder, "mod.txt", DAYS_PER_YEAR) && ret; + if (studyVersion >= StudyVersion(8, 6)) + { + ret = loadTSfromFile(mingen.timeSeries, areaID, folder, "mingen.txt", HOURS_PER_YEAR) + && ret; + } + return ret; +} + +bool DataSeriesHydro::LoadMaxPower(const AreaName& areaID, const AnyString& folder) +{ + bool ret = true; + YString filepath; + Matrix<>::BufferType fileContent; + + filepath.clear() << folder << SEP << areaID << SEP << "maxHourlyGenPower.txt"; + ret = maxHourlyGenPower.timeSeries.loadFromCSVFile(filepath, 1, HOURS_PER_YEAR, &fileContent) + && ret; + + filepath.clear() << folder << SEP << areaID << SEP << "maxHourlyPumpPower.txt"; + ret = maxHourlyPumpPower.timeSeries.loadFromCSVFile(filepath, 1, HOURS_PER_YEAR, &fileContent) + && ret; + + return ret; +} + +void DataSeriesHydro::buildHourlyMaxPowerFromDailyTS( + const Matrix::ColumnType& DailyMaxGenPower, + const Matrix::ColumnType& DailyMaxPumpPower) +{ + const uint count = 1; + + maxHourlyGenPower.reset(count, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(count, HOURS_PER_YEAR); + + ConvertDailyTSintoHourlyTS(DailyMaxGenPower, maxHourlyGenPower.timeSeries[0]); + ConvertDailyTSintoHourlyTS(DailyMaxPumpPower, maxHourlyPumpPower.timeSeries[0]); +} + +bool DataSeriesHydro::saveToFolder(const AreaName& areaID, const AnyString& folder) const +{ + String buffer; + buffer.clear() << folder << SEP << areaID; + /* Make sure the folder is created */ + if (IO::Directory::Create(buffer)) + { + bool ret = true; + + // Saving data + buffer.clear() << folder << SEP << areaID << SEP << "ror.txt"; + ret = ror.timeSeries.saveToCSVFile(buffer, 0) && ret; + buffer.clear() << folder << SEP << areaID << SEP << "mod.txt"; + ret = storage.timeSeries.saveToCSVFile(buffer, 0) && ret; + buffer.clear() << folder << SEP << areaID << SEP << "mingen.txt"; + ret = mingen.timeSeries.saveToCSVFile(buffer, 0) && ret; + buffer.clear() << folder << SEP << areaID << SEP << "maxHourlyGenPower.txt"; + ret = maxHourlyGenPower.timeSeries.saveToCSVFile(buffer, 0) && ret; + buffer.clear() << folder << SEP << areaID << SEP << "maxHourlyPumpPower.txt"; + ret = maxHourlyPumpPower.timeSeries.saveToCSVFile(buffer, 0) && ret; + + return ret; + } + return false; } uint64_t DataSeriesHydro::memoryUsage() const { - return sizeof(double) + ror.memoryUsage() + storage.memoryUsage() + mingen.memoryUsage(); + return sizeof(double) + ror.memoryUsage() + storage.memoryUsage() + mingen.memoryUsage() + + maxHourlyGenPower.memoryUsage() + maxHourlyPumpPower.memoryUsage(); } -unsigned int DataSeriesHydro::getIndex(unsigned int year) const +uint DataSeriesHydro::TScount() const { - return (count != 1) ? timeseriesNumbers[0][year] : 0; + const std::vector nbColumns({storage.numberOfColumns(), + ror.numberOfColumns(), + mingen.numberOfColumns(), + maxHourlyGenPower.numberOfColumns(), + maxHourlyPumpPower.numberOfColumns()}); + + return *std::max_element(nbColumns.begin(), nbColumns.end()); } -} // namespace Data -} // namespace Antares +void DataSeriesHydro::resizeTSinDeratedMode(bool derated, + StudyVersion studyVersion, + bool usedBySolver) +{ + if (!(derated && usedBySolver)) + { + return; + } + + ror.averageTimeseries(); + storage.averageTimeseries(); + if (studyVersion >= StudyVersion(8, 6)) + { + mingen.averageTimeseries(); + + if (studyVersion >= StudyVersion(9, 1)) + { + maxHourlyGenPower.averageTimeseries(); + maxHourlyPumpPower.averageTimeseries(); + } + } +} +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/hydro/series.h b/src/libs/antares/study/parts/hydro/series.h deleted file mode 100644 index d0e4c768eb..0000000000 --- a/src/libs/antares/study/parts/hydro/series.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_H__ - -#include -#include "../../fwd.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Data series (Hydro) -*/ -class DataSeriesHydro -{ -public: - //! \name Constructor - //@{ - /*! - ** \brief Default constructor - */ - DataSeriesHydro(); - //@} - - //! \name Data - //@{ - /*! - ** \brief Reset all data, as if it were a new area - */ - void reset(); - - /*! - ** \brief Load all data not already loaded - ** - ** If the load-on-demand is enabled, some data might not be loaded (see `Matrix`) - */ - bool forceReload(bool reload = false) const; - - void markAsModified() const; - //@} - - //! \name Save / Load - //@{ - /*! - ** \brief Load data series for hydro from a folder - ** - ** \param d The data series for hydro - ** \param folder The source folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool loadFromFolder(Study& s, const AreaName& areaID, const AnyString& folder); - - /*! - ** \brief Save data series for hydro into a folder (`input/hydro/series`) - ** - ** Nothing will be done if the pointer to the structure is null. - ** - ** \param d The data series for hydro - ** \param folder The target folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool saveToFolder(const AreaName& areaID, const AnyString& folder) const; - //@} - - //! \name Memory - //@{ - /*! - ** \brief Get the size (bytes) in memory occupied by a `DataSeriesHydro` structure - */ - uint64_t memoryUsage() const; - /*! - ** \brief Try to estimate the amount of memory required for launching a simulation - */ - - //@} - - /*! - ** \brief Check TS number for Minimum Generation and logs error if necessary - */ - void checkMinGenTsNumber(Study& s, const AreaName& areaID); - - unsigned int getIndex(unsigned int year) const; - -public: - /*! - ** \brief Run-of-the-river - ROR (MW) - ** - - ** (it was DAYS_PER_YEAR before 3.9) - */ - Matrix ror; - - /*! - ** \brief Mod (MW) - ** - ** Merely a matrix of TimeSeriesCount * 365 values - ** This matrix is not used in `adequation` mode. - */ - Matrix storage; - - /*! - ** \brief Minimum Generation (MW) - ** - ** Merely a matrix of TimeSeriesCount * HOURS_PER_YEAR values - */ - Matrix mingen; - - /*! - ** \brief The number of time-series - ** - ** This value must be the same as the width of the matrices `mod` and `fatal`. - ** It is only provided for convenience to avoid same strange and ambiguous code - ** (for example using `fatal.width` and `mod.width` in the same routine, it might - ** indicate that the two values are not strictly equal) - */ - uint count; - - /*! - ** \brief Monte-Carlo - */ - Matrix timeseriesNumbers; - -}; // class DataSeriesHydro - -} // namespace Data -} // namespace Antares - -#include "series.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_H__ */ diff --git a/src/libs/antares/study/parts/hydro/series.hxx b/src/libs/antares/study/parts/hydro/series.hxx deleted file mode 100644 index 6be220a868..0000000000 --- a/src/libs/antares/study/parts/hydro/series.hxx +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_HXX__ - -namespace Antares -{ -namespace Data -{ -// gp : whole file to be removed - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_HYDRO_TIMESERIES_HXX__ diff --git a/src/libs/antares/study/parts/load/container.cpp b/src/libs/antares/study/parts/load/container.cpp index fcc32a1e8d..b377eb0bf3 100644 --- a/src/libs/antares/study/parts/load/container.cpp +++ b/src/libs/antares/study/parts/load/container.cpp @@ -1,40 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/load/container.h" + #include -#include "../../study.h" -#include "container.h" -#include "prepro.h" + +#include "antares/study/parts/load/prepro.h" +#include "antares/study/study.h" using namespace Yuni; namespace Antares::Data::Load { -Container::Container() : prepro(nullptr), series(nullptr) +Container::Container(): + prepro(nullptr), + series(tsNumbers) { } @@ -42,42 +40,40 @@ Container::~Container() { delete prepro; prepro = nullptr; - delete series; - series = nullptr; } bool Container::forceReload(bool reload) const { bool ret = true; - if (series) - ret = series->forceReload(reload) && ret; + ret = series.forceReload(reload) && ret; if (prepro) + { ret = prepro->forceReload(reload) && ret; + } return ret; } void Container::markAsModified() const { - if (series) - series->markAsModified(); + series.markAsModified(); if (prepro) + { prepro->markAsModified(); + } } uint64_t Container::memoryUsage() const { - return sizeof(Container) + ((!series) ? 0 : DataSeriesLoadMemoryUsage(series)) - + ((!prepro) ? 0 : prepro->memoryUsage()); + return sizeof(Container) + series.memoryUsage() + ((!prepro) ? 0 : prepro->memoryUsage()); } void Container::resetToDefault() { - if (series) - series->timeSeries.reset(1, HOURS_PER_YEAR); + series.reset(); if (prepro) + { prepro->resetToDefault(); + } } } // namespace Antares::Data::Load - - diff --git a/src/libs/antares/study/parts/load/container.h b/src/libs/antares/study/parts/load/container.h deleted file mode 100644 index 4776e3865c..0000000000 --- a/src/libs/antares/study/parts/load/container.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_LOAD_CONTAINER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_LOAD_CONTAINER_H__ - -#include "series.h" -#include - -namespace Antares -{ -namespace Data -{ -namespace Load -{ - -class Prepro; -class Container final : private Yuni::NonCopyable -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Container(); - //! Destructor - ~Container(); - //@} - - /*! - ** \brief Reset to default values - */ - void resetToDefault(); - - /*! - ** \brief Make sure that all data are loaded - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark the load data as modified - */ - void markAsModified() const; - - /*! - ** \brief Get the amount of memory currently used by the class - */ - uint64_t memoryUsage() const; - -public: - //! Data for the pre-processor - Data::Load::Prepro* prepro; - /*! Data for time-series */ - DataSeriesLoad* series; - -}; // class Container - -} // namespace Load -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_LOAD_CONTAINER_H__ diff --git a/src/libs/antares/study/parts/load/prepro.cpp b/src/libs/antares/study/parts/load/prepro.cpp index 6ab41a67f0..68ae63a322 100644 --- a/src/libs/antares/study/parts/load/prepro.cpp +++ b/src/libs/antares/study/parts/load/prepro.cpp @@ -1,41 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include "prepro.h" -#include "../../study.h" +#include "antares/study/parts/load/prepro.h" -using namespace Yuni; +#include +#include "antares/study/study.h" +using namespace Yuni; namespace Antares::Data::Load { -Prepro::Prepro() : xcast(timeSeriesLoad) +Prepro::Prepro(): + xcast(timeSeriesLoad) { } @@ -54,5 +49,3 @@ bool Prepro::saveToFolder(const AnyString& folder) const } } // namespace Antares::Data::Load - - diff --git a/src/libs/antares/study/parts/load/prepro.h b/src/libs/antares/study/parts/load/prepro.h deleted file mode 100644 index e72d11a8e8..0000000000 --- a/src/libs/antares/study/parts/load/prepro.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../../fwd.h" -#include "../../xcast.h" - -namespace Antares -{ -namespace Data -{ -namespace Load -{ -/*! -** \brief Prepro Load -*/ -class Prepro -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - Prepro(); - //! Destructor - ~Prepro(); - //@} - - /*! - ** \brief Try to estimate the amount of memory required by this class for a simulation - */ - - - /*! - ** \brief Load data from a folder - */ - bool loadFromFolder(const AnyString& folder); - - /*! - ** \brief Save data to a folder - */ - bool saveToFolder(const AnyString& folder) const; - - /*! - ** \brief Get the amount of memory currently used - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Make sure that all data are loaded in memory - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark the load data as modified - */ - void markAsModified() const; - - /*! - ** \brief Reset to default all values - */ - void resetToDefault(); - -public: - //! XCast - Data::XCast xcast; - -private: - bool internalLoadFromFolder(Study& study, const char* folder, uint length); - -}; // Prepro - -} // namespace Load -} // namespace Data -} // namespace Antares - -#include "prepro.hxx" diff --git a/src/libs/antares/study/parts/load/prepro.hxx b/src/libs/antares/study/parts/load/prepro.hxx deleted file mode 100644 index c3ff5220e6..0000000000 --- a/src/libs/antares/study/parts/load/prepro.hxx +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_LOAD_PREPRO_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_LOAD_PREPRO_HXX__ - -namespace Antares::Data::Load -{ - -inline uint64_t Prepro::memoryUsage() const -{ - return xcast.memoryUsage(); -} - -inline bool Prepro::forceReload(bool reload) const -{ - return xcast.forceReload(reload); -} - -inline void Prepro::markAsModified() const -{ - xcast.markAsModified(); -} - -inline void Prepro::resetToDefault() -{ - xcast.resetToDefaultValues(); -} - -} // namespace Antares::Data::Load - - - -#endif // __ANTARES_LIBS_STUDY_PARTS_LOAD_PREPRO_H__ diff --git a/src/libs/antares/study/parts/load/series.cpp b/src/libs/antares/study/parts/load/series.cpp deleted file mode 100644 index 35d70cd3a2..0000000000 --- a/src/libs/antares/study/parts/load/series.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include -#include "series.h" -#include "../../study.h" - -using namespace Yuni; - -#define SEP IO::Separator - -namespace Antares -{ -namespace Data -{ -int DataSeriesLoadLoadFromFolder(Study& study, - DataSeriesLoad* s, - const AreaName& areaID, - const char* folder) -{ - /* Assert */ - assert(s); - assert(folder); - assert('\0' != *folder); - - auto& buffer = study.buffer; - - int ret = 1; - /* Load the matrix */ - buffer.clear() << folder << SEP << "load_" << areaID << '.' << study.inputExtension; - ret = s->timeSeries.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &study.dataBuffer) && ret; - - if (study.usedByTheSolver && study.parameters.derated) - s->timeSeries.averageTimeseries(); - - s->timeseriesNumbers.clear(); - - return ret; -} - -int DataSeriesLoadSaveToFolder(DataSeriesLoad* s, const AreaName& areaID, const char folder[]) -{ - if (!s) - return 1; - - /* Assert */ - assert(folder); - assert('\0' != *folder); - - if (IO::Directory::Create(folder)) - { - int res = 1; - - Clob buffer; - buffer.clear() << folder << SEP << "load_" << areaID << ".txt"; - res = s->timeSeries.saveToCSVFile(buffer, /*decimal*/ 0) && res; - - return res; - } - return 0; -} - -double* DataSeriesLoad::getColumn(unsigned int year) const -{ - return timeSeries[getIndex(year)]; -} - -double DataSeriesLoad::getCoefficient(const unsigned int year, const unsigned int hour) const -{ - return timeSeries[getIndex(year)][hour]; -} - -unsigned int DataSeriesLoad::getIndex(unsigned int year) const -{ - return (timeSeries.width != 1) ? timeseriesNumbers[0][year] : 0; -} - -bool DataSeriesLoad::forceReload(bool reload) const -{ - return timeSeries.forceReload(reload); -} - -void DataSeriesLoad::markAsModified() const -{ - return timeSeries.markAsModified(); -} - -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/parts/load/series.h b/src/libs/antares/study/parts/load/series.h deleted file mode 100644 index 477ee71fcc..0000000000 --- a/src/libs/antares/study/parts/load/series.h +++ /dev/null @@ -1,106 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_LOAD_TIMESERIES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_LOAD_TIMESERIES_H__ - -#include -#include "../../fwd.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Data series (Load) -*/ -class DataSeriesLoad -{ -public: - - - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark the load data as modified - */ - void markAsModified() const; - - double* getColumn(unsigned int year) const; - double getCoefficient(const unsigned int year, const unsigned int hour) const; - unsigned int getIndex(unsigned int year) const; - -public: - /*! - ** \brief Time series (MW) - ** - ** Merely a matrix of TimeSeriesCount * 8760 values - */ - Matrix timeSeries; - - /*! - ** \brief Monte-Carlo - */ - Matrix timeseriesNumbers; - -}; /* class DataSeriesLoad */ - -/*! -** \brief Load wind data series from a file -** \ingroup windseries -** -** \param d Data series -** \param areaID The ID of the area associated to the data series -** \param folder The source folder -** \return A non-zero value if the operation succeeded, 0 otherwise -*/ -int DataSeriesLoadLoadFromFolder(Study& s, - DataSeriesLoad* d, - const AreaName& areaID, - const char folder[]); - -/*! -** \brief Save wind data series from a file -** \ingroup windseries -** -** \param d Data series -** \param areaID The ID of the area associated to the data series -** \param folder The target folder -** \return A non-zero value if the operation succeeded, 0 otherwise -*/ -int DataSeriesLoadSaveToFolder(DataSeriesLoad* d, const AreaName& areaID, const char folder[]); - -/*! -** \brief Get the size (bytes) in memory occupied by a `DataSeriesLoad` structure -*/ -uint64_t DataSeriesLoadMemoryUsage(DataSeriesLoad* w); - -} // namespace Data -} // namespace Antares - -#include "series.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_LOAD_TIMESERIES_H__ */ diff --git a/src/libs/antares/study/parts/load/series.hxx b/src/libs/antares/study/parts/load/series.hxx deleted file mode 100644 index ddebe31d35..0000000000 --- a/src/libs/antares/study/parts/load/series.hxx +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_LOAD_TIMESERIES_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_LOAD_TIMESERIES_HXX__ - -namespace Antares -{ -namespace Data -{ -inline uint64_t DataSeriesLoadMemoryUsage(DataSeriesLoad* l) -{ - return (l) ? l->timeSeries.memoryUsage() : 0; -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_LOAD_TIMESERIES_HXX__ diff --git a/src/libs/antares/study/parts/parts.h b/src/libs/antares/study/parts/parts.h deleted file mode 100644 index d59933f179..0000000000 --- a/src/libs/antares/study/parts/parts.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_H__ -#define __ANTARES_LIBS_STUDY_PARTS_H__ - -// Load -#include "load/series.h" -#include "load/container.h" - -// Solar -#include "solar/series.h" -#include "solar/prepro.h" -#include "solar/container.h" - -// Hydro -#include "hydro/prepro.h" -#include "hydro/series.h" -#include "hydro/container.h" - -// Wind -#include "wind/prepro.h" -#include "wind/series.h" -#include "wind/container.h" - -// Thermal -#include "thermal/defines.h" -#include "thermal/prepro.h" -#include "thermal/cluster.h" -#include "thermal/container.h" - -// Renewable -#include "renewable/defines.h" -#include "renewable/cluster.h" -#include "renewable/container.h" - -// Short-term storage -#include "short-term-storage/container.h" - -#endif // __ANTARES_LIBS_STUDY_PARTS_H__ diff --git a/src/libs/antares/study/parts/renewable/cluster.cpp b/src/libs/antares/study/parts/renewable/cluster.cpp index 8a229d6d65..749ed53a57 100644 --- a/src/libs/antares/study/parts/renewable/cluster.cpp +++ b/src/libs/antares/study/parts/renewable/cluster.cpp @@ -1,63 +1,54 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include +#include "antares/study/parts/renewable/cluster.h" + #include #include + #include -#include "../../study.h" -#include "cluster.h" + +#include +#include +#include + #include #include #include +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; #define SEP IO::Separator -namespace Antares +namespace Antares::Data { -namespace Data -{ -Data::RenewableCluster::RenewableCluster(Area* parent) : - Cluster(parent), groupID(renewableOther1), tsMode(powerGeneration) +Data::RenewableCluster::RenewableCluster(Area* parent): + Cluster(parent) { // assert assert(parent and "A parent for a renewable dispatchable cluster can not be null"); } -Data::RenewableCluster::~RenewableCluster() -{ - delete series; -} - uint RenewableCluster::groupId() const { return groupID; @@ -82,33 +73,29 @@ void Data::RenewableCluster::copyFrom(const RenewableCluster& cluster) // ts-mode tsMode = cluster.tsMode; - // Making sure that the data related to the timeseries are present - if (not series) - series = new DataSeriesCommon(); - // timseries - series->timeSeries = cluster.series->timeSeries; - cluster.series->timeSeries.unloadFromMemory(); - series->timeseriesNumbers.clear(); + series.timeSeries = cluster.series.timeSeries; + cluster.series.timeSeries.unloadFromMemory(); + series.timeseriesNumbers.clear(); // The parent must be invalidated to make sure that the clusters are really // re-written at the next 'Save' from the user interface. if (parentArea) + { parentArea->forceReload(); + } } -const std::map < RenewableCluster::RenewableGroup, const char* > groupToName = -{ - {RenewableCluster::thermalSolar, "solar thermal"}, - {RenewableCluster::PVSolar, "solar pv"}, - {RenewableCluster::rooftopSolar, "solar rooftop"}, - {RenewableCluster::windOnShore, "wind onshore"}, - {RenewableCluster::windOffShore,"wind offshore"}, - {RenewableCluster::renewableOther1, "other res 1"}, - {RenewableCluster::renewableOther2, "other res 2"}, - {RenewableCluster::renewableOther3, "other res 3"}, - {RenewableCluster::renewableOther4, "other res 4"} -}; +const std::map groupToName = { + {RenewableCluster::thermalSolar, "solar thermal"}, + {RenewableCluster::PVSolar, "solar pv"}, + {RenewableCluster::rooftopSolar, "solar rooftop"}, + {RenewableCluster::windOnShore, "wind onshore"}, + {RenewableCluster::windOffShore, "wind offshore"}, + {RenewableCluster::renewableOther1, "other res 1"}, + {RenewableCluster::renewableOther2, "other res 2"}, + {RenewableCluster::renewableOther3, "other res 3"}, + {RenewableCluster::renewableOther4, "other res 4"}}; void Data::RenewableCluster::setGroup(Data::ClusterName newgrp) { @@ -121,13 +108,13 @@ void Data::RenewableCluster::setGroup(Data::ClusterName newgrp) pGroup = newgrp; boost::to_lower(newgrp); - for (const auto& [group, name] : groupToName) + for (const auto& [group, name]: groupToName) { if (newgrp == name) { groupID = group; return; - } + } } // assigning a default value @@ -136,16 +123,12 @@ void Data::RenewableCluster::setGroup(Data::ClusterName newgrp) bool Data::RenewableCluster::forceReload(bool reload) const { - bool ret = true; - if (series) - ret = series->forceReload(reload) and ret; - return ret; + return series.forceReload(reload); } void Data::RenewableCluster::markAsModified() const { - if (series) - series->markAsModified(); + series.markAsModified(); } void Data::RenewableCluster::reset() @@ -200,15 +183,14 @@ YString Data::RenewableCluster::getTimeSeriesModeAsString() const return "unknown"; } -double RenewableCluster::valueAtTimeStep(uint hourInYear, uint year) const +double RenewableCluster::valueAtTimeStep(uint year, uint hourInYear) const { if (!enabled) + { return 0.; - uint timeSeriesIndex = (series->timeSeries.width == 1) ? 0 : series->timeseriesNumbers[0][year]; + } - assert(hourInYear < series->timeSeries.height); - assert(timeSeriesIndex < series->timeSeries.width); - const double tsValue = series->timeSeries[timeSeriesIndex][hourInYear]; + const double tsValue = series.getCoefficient(year, hourInYear); switch (tsMode) { case powerGeneration: @@ -222,8 +204,7 @@ double RenewableCluster::valueAtTimeStep(uint hourInYear, uint year) const uint64_t RenewableCluster::memoryUsage() const { uint64_t amount = sizeof(RenewableCluster); - if (series) - amount += series->memoryUsage(); + amount += series.memoryUsage(); return amount; } @@ -231,5 +212,4 @@ unsigned int RenewableCluster::precision() const { return 4; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/renewable/cluster.h b/src/libs/antares/study/parts/renewable/cluster.h deleted file mode 100644 index 61e6df2a8e..0000000000 --- a/src/libs/antares/study/parts/renewable/cluster.h +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_H__ - -#include -#include -#include -#include "defines.h" -#include "../common/cluster.h" -#include "../../fwd.h" - -namespace Antares -{ -namespace Data -{ -/* gp : useless in v8.1, could be useful in a further version -enum RenewableModulation -{ - renewableModulationCost = 0, - renewableModulationCapacity, - renewableMinGenModulation, - renewableModulationMax -}; -*/ - -/* -** \brief A single renewable cluster -*/ -class RenewableCluster final : public Cluster -{ -public: - enum RenewableGroup - { - //! Wind offshore - windOffShore = 0, - //! Wind onshore - windOnShore, - //! Concentration solar - thermalSolar, - //! PV solar - PVSolar, - //! Rooftop solar - rooftopSolar, - //! Other 1 - renewableOther1, - //! Other 2 - renewableOther2, - //! Other 3 - renewableOther3, - //! Other 4 - renewableOther4, - - //! The highest value - groupMax - }; - - enum TimeSeriesMode - { - //! TS contain power generation for each unit - //! Nominal capacity is *ignored* - powerGeneration = 0, - //! TS contain production factor for each unit - //! Nominal capacity is used as a multiplicative factor - productionFactor - }; - - //! Set of renewable clusters - using Set = std::set; -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor, with a parent area - */ - explicit RenewableCluster(Data::Area* parent); - //! Destructor - ~RenewableCluster(); - //@} - - /*! - ** \brief Invalidate all data associated to the renewable cluster - */ - bool forceReload(bool reload) const override; - - /*! - ** \brief Mark the renewable cluster as modified - */ - void markAsModified() const override; - - /*! - ** \brief Reset to default values - ** - ** This method should only be called from the GUI - */ - void reset() override; - - //! Set the group - void setGroup(Data::ClusterName newgrp) override; - //@} - - /*! - ** \brief Check and fix all values of a renewable cluster - ** - ** \return False if an error has been detected and fixed with a default value - */ - bool integrityCheck() override; - - /*! - ** \brief Copy data from another cluster - ** - ** The name and the id will remain untouched. - */ - void copyFrom(const RenewableCluster& cluster); - - /*! - ** \brief Group ID as an uint - */ - uint groupId() const override; - - /*! - ** \brief Get the memory consummed by the renewable cluster (in bytes) - */ - uint64_t memoryUsage() const override; - //@} - - bool setTimeSeriesModeFromString(const YString& value); - - YString getTimeSeriesModeAsString() const; - - /* ! - ** Get production value at time-step ts - */ - double valueAtTimeStep(uint hourInYear, uint year) const; - -public: - /*! - ** \brief The group ID - ** - ** This value is computed from the field 'group' in 'group() - ** \see group() - */ - enum RenewableGroup groupID; - - enum TimeSeriesMode tsMode; - - friend class RenewableClusterList; - -private: - unsigned int precision() const override; -}; // class RenewableCluster - -} // namespace Data -} // namespace Antares - -#endif //__ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_H__ diff --git a/src/libs/antares/study/parts/renewable/cluster.hxx b/src/libs/antares/study/parts/renewable/cluster.hxx deleted file mode 100644 index b949a7b867..0000000000 --- a/src/libs/antares/study/parts/renewable/cluster.hxx +++ /dev/null @@ -1,37 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_HXX__ - -namespace Antares -{ -namespace Data -{ -} // namespace Data -} // namespace Antares - -#endif //__ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_HXX__ diff --git a/src/libs/antares/study/parts/renewable/cluster_list.cpp b/src/libs/antares/study/parts/renewable/cluster_list.cpp index c7c01a00bd..aa1c915a75 100644 --- a/src/libs/antares/study/parts/renewable/cluster_list.cpp +++ b/src/libs/antares/study/parts/renewable/cluster_list.cpp @@ -1,28 +1,49 @@ -#include "cluster_list.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/study/parts/renewable/cluster_list.h" + #include -#include "../../study.h" #include +#include +#include "antares/study/study.h" using namespace Yuni; -namespace Antares -{ -namespace Data -{ -RenewableClusterList::~RenewableClusterList() +namespace Antares::Data { -} -RenewableClusterList::RenewableClusterList() -{ -} +#define SEP IO::Separator -YString RenewableClusterList::typeID() const +std::string RenewableClusterList::typeID() const { return "renewables"; } -#define SEP IO::Separator +uint64_t RenewableClusterList::memoryUsage() const +{ + uint64_t ret = sizeof(RenewableClusterList) + (2 * sizeof(void*)) * enabledCount(); + std::ranges::for_each(each_enabled(), [&ret](const auto c) { ret += c->memoryUsage(); }); + return ret; +} bool RenewableClusterList::saveToFolder(const AnyString& folder) const { @@ -36,27 +57,36 @@ bool RenewableClusterList::saveToFolder(const AnyString& folder) const IniFile ini; // Browse all clusters - each([&](const Data::RenewableCluster& c) { + for (auto& c: all()) + { // Adding a section to the inifile - IniFile::Section* s = ini.addSection(c.name()); + IniFile::Section* s = ini.addSection(c->name()); // The section must not be empty // This key will be silently ignored the next time - s->add("name", c.name()); + s->add("name", c->name()); - if (not c.group().empty()) - s->add("group", c.group()); - if (not c.enabled) + if (!c->group().empty()) + { + s->add("group", c->group()); + } + if (!c->enabled) + { s->add("enabled", "false"); + } - if (not Math::Zero(c.nominalCapacity)) - s->add("nominalCapacity", c.nominalCapacity); + if (!Utils::isZero(c->nominalCapacity)) + { + s->add("nominalCapacity", c->nominalCapacity); + } - if (not Math::Zero(c.unitCount)) - s->add("unitCount", c.unitCount); + if (!Utils::isZero(c->unitCount)) + { + s->add("unitCount", c->unitCount); + } - s->add("ts-interpretation", c.getTimeSeriesModeAsString()); - }); + s->add("ts-interpretation", c->getTimeSeriesModeAsString()); + } // Write the ini file buffer.clear() << folder << SEP << "list.ini"; @@ -74,7 +104,9 @@ bool RenewableClusterList::saveToFolder(const AnyString& folder) const static bool ClusterLoadFromProperty(RenewableCluster& cluster, const IniFile::Property* p) { if (p->key.empty()) + { return false; + } if (p->key == "group") { @@ -83,19 +115,29 @@ static bool ClusterLoadFromProperty(RenewableCluster& cluster, const IniFile::Pr } if (p->key == "name") + { return true; + } if (p->key == "enabled") + { return p->value.to(cluster.enabled); + } if (p->key == "unitcount") + { return p->value.to(cluster.unitCount); + } if (p->key == "nominalcapacity") + { return p->value.to(cluster.nominalCapacity); + } if (p->key == "ts-interpretation") + { return cluster.setTimeSeriesModeFromString(p->value); + } // The property is unknown return false; @@ -106,7 +148,9 @@ static bool ClusterLoadFromSection(const AnyString& filename, const IniFile::Section& section) { if (section.name.empty()) + { return false; + } cluster.setName(section.name); @@ -121,7 +165,7 @@ static bool ClusterLoadFromSection(const AnyString& filename, << "`: Invalid key/value"; continue; } - if (not ClusterLoadFromProperty(cluster, property)) + if (!ClusterLoadFromProperty(cluster, property)) { logs.warning() << '`' << filename << "`: `" << section.name << "`/`" << property->key << "`: The property is unknown and ignored"; @@ -153,36 +197,40 @@ bool RenewableClusterList::loadFromFolder(const AnyString& folder, Area* area) for (auto* section = ini.firstSection; section; section = section->next) { if (section->name.empty()) + { continue; + } auto cluster = std::make_shared(area); // Load data of a renewable cluster from a ini file section - if (not ClusterLoadFromSection(buffer, *cluster, *section)) + if (!ClusterLoadFromSection(buffer, *cluster, *section)) { continue; } - // Check the data integrity of the cluster - cluster->integrityCheck(); - - // adding the renewable cluster - if (not add(cluster)) - { - // This error should never happen - logs.error() << "Impossible to add the renewable cluster '" << cluster->name() - << "'"; - continue; - } + addToCompleteList(cluster); } } + rebuildIndexes(); + return ret; } return false; } +bool RenewableClusterList::validateClusters() const +{ + bool ret = true; + for (const auto& cluster: allClusters_) + { + ret = cluster->integrityCheck() && ret; + } + + return ret; +} + #undef SEP -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/renewable/cluster_list.h b/src/libs/antares/study/parts/renewable/cluster_list.h deleted file mode 100644 index 15746180fc..0000000000 --- a/src/libs/antares/study/parts/renewable/cluster_list.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_LIST_H__ -#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_LIST_H__ - -#include "../../fwd.h" -#include "cluster.h" -#include "../common/cluster_list.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief List of renewable clusters -** \ingroup renewableclusters -*/ -class RenewableClusterList : public ClusterList -{ -public: - RenewableClusterList(); - ~RenewableClusterList(); - // Overriden virtual methods - YString typeID() const override; - bool loadFromFolder(const AnyString& folder, Area* area); - bool saveToFolder(const AnyString& folder) const override; -}; // class RenewableClusterList -} // namespace Data -} // namespace Antares - -#endif /* __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CLUSTER_LIST_H__ */ diff --git a/src/libs/antares/study/parts/renewable/container.cpp b/src/libs/antares/study/parts/renewable/container.cpp index 1fbde6732c..4031d23c98 100644 --- a/src/libs/antares/study/parts/renewable/container.cpp +++ b/src/libs/antares/study/parts/renewable/container.cpp @@ -1,41 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/renewable/container.h" + #include -#include "../../study.h" -#include "container.h" + #include +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; -namespace Antares -{ -namespace Data +namespace Antares::Data { PartRenewable::PartRenewable() { @@ -57,58 +51,9 @@ PartRenewable::~PartRenewable() { } -void PartRenewable::prepareAreaWideIndexes() -{ - // Copy the list with all renewable clusters - // And init the areaWideIndex (unique index for a given area) - if (list.empty()) - { - clusters.clear(); - return; - } - - clusters.assign(list.size(), nullptr); - - auto end = list.end(); - uint idx = 0; - for (auto i = list.begin(); i != end; ++i) - { - RenewableCluster* t = i->second.get(); - t->areaWideIndex = idx; - clusters[idx] = t; - ++idx; - } -} - -uint PartRenewable::removeDisabledClusters() -{ - // nothing to do if there is no cluster available - if (list.empty()) - return 0; - - std::vector disabledClusters; - - for (auto& it : list) - { - if (!it.second->enabled) - disabledClusters.push_back(it.first); - } - - for (auto& cluster : disabledClusters) - list.remove(cluster); - - const auto count = disabledClusters.size(); - if (count) - list.rebuildIndex(); - - return count; -} - void PartRenewable::reset() { - list.clear(); - clusters.clear(); + list.clearAll(); } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/renewable/container.h b/src/libs/antares/study/parts/renewable/container.h deleted file mode 100644 index 11c7489741..0000000000 --- a/src/libs/antares/study/parts/renewable/container.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_H__ - -#include -#include "../../fwd.h" -#include "cluster.h" -#include "cluster_list.h" - -namespace Antares -{ -namespace Data -{ -class PartRenewable -{ -public: - //! \name Constructor - //@{ - /*! - ** \brief Default constructor - */ - PartRenewable(); - //! Destructor - ~PartRenewable(); - //@} - - /*! - ** \brief Reset internal data - */ - void reset(); - - /*! - ** \brief Resize all matrices dedicated to the sampled timeseries numbers - ** - ** \param n A number of years - */ - void resizeAllTimeseriesNumbers(uint n); - - - - /*! - ** \brief Create and initialize the list of all clusters (with the mustrun flag or not) - ** - ** This method must be called before prepareClustersInMustRunMode() - ** to ensure the same order whatever the value of the 'mustrun' flag is. - */ - void prepareAreaWideIndexes(); - - /*! - ** \brief Removes disabled renewable clusters - ** - ** All clusters with the flag 'enabled' turned to false will be removed from 'list'. - ** As a consequence, they will no longer be seen as renewable clusters - ** from the solver's point of view. - ** \warning This method should only be used from the solver - ** - ** \return The number of disabled clusters found - */ - uint removeDisabledClusters(); - - /*! - ** \brief Invalidate all JIT data - */ - bool forceReload(bool reload) const; - - /*! - ** \brief Mark the renewable cluster as modified - */ - void markAsModified() const; - -public: - //! List of all renewable clusters (enabled and disabled) - RenewableClusterList list; - - /*! - ** \brief All clusters for the area - ** - ** This variable is only available at runtime from the solver. - ** It is initialized in the same time that the runtime data. - ** - ** This list is mainly used to ensure the same order of the - ** renewable clusters in the outputs. - */ - std::vector clusters; - //! How many clusters have we got ? - // Only available from the solver - inline size_t clusterCount() const - { - return clusters.size(); - } -}; // class PartRenewable - -} // namespace Data -} // namespace Antares - -#include "container.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_H__ */ diff --git a/src/libs/antares/study/parts/renewable/container.hxx b/src/libs/antares/study/parts/renewable/container.hxx deleted file mode 100644 index 631689c95a..0000000000 --- a/src/libs/antares/study/parts/renewable/container.hxx +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_HXX__ - -namespace Antares -{ -namespace Data -{ -inline void PartRenewable::resizeAllTimeseriesNumbers(uint n) -{ - list.resizeAllTimeseriesNumbers(n); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_CONTAINER_HXX__ diff --git a/src/libs/antares/study/parts/renewable/defines.h b/src/libs/antares/study/parts/renewable/defines.h deleted file mode 100644 index c20593d8f2..0000000000 --- a/src/libs/antares/study/parts/renewable/defines.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_DEFINES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_DEFINES_H__ - -namespace Antares -{ -namespace Data -{ -// Forward declaration -class RenewableCluster; - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_RENEWABLE_DEFINES_H__ diff --git a/src/libs/antares/study/parts/short-term-storage/STStorageOutputCaptions.cpp b/src/libs/antares/study/parts/short-term-storage/STStorageOutputCaptions.cpp deleted file mode 100644 index 65e47bdd6e..0000000000 --- a/src/libs/antares/study/parts/short-term-storage/STStorageOutputCaptions.cpp +++ /dev/null @@ -1,34 +0,0 @@ - -#include -#include "STStorageOutputCaptions.h" - -namespace Antares::Data::ShortTermStorage -{ -static const std::vector groups = {"PSP_open", - "PSP_closed", - "Pondage", - "Battery", - "Other1", - "Other2", - "Other3", - "Other4", - "Other5"}; - -static const std::vector variables = {"injection", "withdrawal", "level"}; - -const unsigned int nb_groups = groups.size(); -const unsigned int nb_variables = variables.size(); - -std::string getVariableCaptionFromColumnIndex(unsigned int col_index) -{ - if (col_index < nb_groups * nb_variables) - { - unsigned int group_index = col_index / nb_variables; - unsigned int variable_index = col_index % nb_variables; - return groups[group_index] + "_" + variables[variable_index]; - } - else - return ""; -} - -} // End namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/parts/short-term-storage/STStorageOutputCaptions.h b/src/libs/antares/study/parts/short-term-storage/STStorageOutputCaptions.h deleted file mode 100644 index dc3befe794..0000000000 --- a/src/libs/antares/study/parts/short-term-storage/STStorageOutputCaptions.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include - -namespace Antares::Data::ShortTermStorage -{ -std::string getVariableCaptionFromColumnIndex(unsigned int index); -} diff --git a/src/libs/antares/study/parts/short-term-storage/cluster.cpp b/src/libs/antares/study/parts/short-term-storage/cluster.cpp index 50789c7435..fe06ace18e 100644 --- a/src/libs/antares/study/parts/short-term-storage/cluster.cpp +++ b/src/libs/antares/study/parts/short-term-storage/cluster.cpp @@ -1,35 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include +#include "antares/study/parts/short-term-storage/cluster.h" + #include #include -#include "cluster.h" +#include +#include namespace Antares::Data::ShortTermStorage { @@ -37,7 +32,9 @@ namespace Antares::Data::ShortTermStorage bool STStorageCluster::loadFromSection(const IniFile::Section& section) { if (!section.firstProperty) + { return false; + } for (auto* property = section.firstProperty; property; property = property->next) { @@ -54,17 +51,27 @@ bool STStorageCluster::loadFromSection(const IniFile::Section& section) } if (properties.name.empty()) + { return false; + } - Yuni::CString<50, false> tmp; - TransformNameIntoID(properties.name, tmp); - id = tmp.to(); + id = transformNameIntoID(properties.name); return true; } -bool STStorageCluster::validate() +bool STStorageCluster::enabled() const { + return properties.enabled; +} + +bool STStorageCluster::validate() const +{ + if (!enabled()) + { + return true; + } + logs.debug() << "Validating properties and series for st storage: " << id; return properties.validate() && series->validate(); } @@ -76,9 +83,9 @@ bool STStorageCluster::loadSeries(const std::string& folder) const return ret; } -bool STStorageCluster::saveProperties(const std::string& path) const +void STStorageCluster::saveProperties(IniFile& ini) const { - return properties.saveToFolder(path); + properties.save(ini); } bool STStorageCluster::saveSeries(const std::string& path) const diff --git a/src/libs/antares/study/parts/short-term-storage/cluster.h b/src/libs/antares/study/parts/short-term-storage/cluster.h deleted file mode 100644 index 4e909962a0..0000000000 --- a/src/libs/antares/study/parts/short-term-storage/cluster.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once -#include -#include -#include -#include "properties.h" -#include "series.h" - -namespace Antares::Data::ShortTermStorage -{ -class STStorageCluster -{ -public: - bool validate(); - bool loadFromSection(const IniFile::Section& section); - - bool loadSeries(const std::string& folder) const; - - bool saveProperties(const std::string& path) const; - bool saveSeries(const std::string& path) const; - - std::string id; - - std::shared_ptr series = std::make_shared(); - Properties properties; - -}; -} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/parts/short-term-storage/container.cpp b/src/libs/antares/study/parts/short-term-storage/container.cpp index 3b0cba2a36..9a27233064 100644 --- a/src/libs/antares/study/parts/short-term-storage/container.cpp +++ b/src/libs/antares/study/parts/short-term-storage/container.cpp @@ -1,57 +1,58 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include +#include "antares/study/parts/short-term-storage/container.h" + +#include #include #include -#include "container.h" +#include + +#include #define SEP Yuni::IO::Separator +namespace fs = std::filesystem; + namespace Antares::Data::ShortTermStorage { bool STStorageInput::validate() const { - return std::all_of(storagesByIndex.cbegin(), storagesByIndex.cend(), [](auto& cluster) { - return cluster->validate(); - }); + return std::ranges::all_of(storagesByIndex, [](auto& cluster) { return cluster.validate(); }); } -bool STStorageInput::createSTStorageClustersFromIniFile(const std::string& path) +bool STStorageInput::createSTStorageClustersFromIniFile(const fs::path& path) { - const std::string pathIni(path + SEP + "list.ini"); + const fs::path pathIni = path / "list.ini"; IniFile ini; if (!ini.open(pathIni)) + { return false; + } if (!ini.firstSection) + { return true; + } logs.debug() << " :: loading `" << pathIni << "`"; @@ -59,14 +60,16 @@ bool STStorageInput::createSTStorageClustersFromIniFile(const std::string& path) { STStorageCluster cluster; if (!cluster.loadFromSection(*section)) + { return false; + } - storagesById.try_emplace(cluster.properties.name, cluster); + storagesByIndex.push_back(cluster); } - storagesByIndex.reserve(storagesById.size()); - for (auto& [id, storage] : storagesById) - storagesByIndex.push_back(&storage); + std::ranges::sort(storagesByIndex, + [](const auto& a, const auto& b) + { return a.properties.name < b.properties.name; }); return true; } @@ -74,14 +77,16 @@ bool STStorageInput::createSTStorageClustersFromIniFile(const std::string& path) bool STStorageInput::loadSeriesFromFolder(const std::string& folder) const { if (folder.empty()) + { return false; + } bool ret = true; - for (auto& cluster : storagesByIndex) + for (auto& cluster: storagesByIndex) { - const std::string buffer(folder + SEP + cluster->id); - ret = cluster->loadSeries(buffer) && ret; + const std::string buffer(folder + SEP + cluster.id); + ret = cluster.loadSeries(buffer) && ret; } return ret; @@ -91,24 +96,33 @@ bool STStorageInput::saveToFolder(const std::string& folder) const { // create empty list.ini if there's no sts in this area Yuni::IO::Directory::Create(folder); - Yuni::IO::File::CreateEmptyFile(folder + SEP + "list.ini"); - logs.notice() << "created empty ini: " << folder + SEP + "list.ini"; + const std::string pathIni(folder + SEP + "list.ini"); + IniFile ini; - return std::all_of(storagesByIndex.cbegin(), storagesByIndex.cend(), [&folder](auto& storage) { - return storage->saveProperties(folder); - }); + logs.debug() << "saving file " << pathIni; + std::ranges::for_each(storagesByIndex, + [&ini](auto& storage) { return storage.saveProperties(ini); }); + + return ini.save(pathIni); } bool STStorageInput::saveDataSeriesToFolder(const std::string& folder) const { Yuni::IO::Directory::Create(folder); - return std::all_of(storagesByIndex.cbegin(), storagesByIndex.cend(), [&folder](auto& storage) { - return storage->saveSeries(folder + SEP + storage->id); - }); + return std::ranges::all_of(storagesByIndex, + [&folder](auto& storage) + { return storage.saveSeries(folder + SEP + storage.id); }); } std::size_t STStorageInput::count() const { - return storagesByIndex.size(); + return std::ranges::count_if(storagesByIndex, + [](const STStorageCluster& st) { return st.properties.enabled; }); } + +uint STStorageInput::removeDisabledClusters() +{ + return std::erase_if(storagesByIndex, [](const auto& c) { return !c.enabled(); }); +} + } // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/parts/short-term-storage/container.h b/src/libs/antares/study/parts/short-term-storage/container.h deleted file mode 100644 index 00673cebcd..0000000000 --- a/src/libs/antares/study/parts/short-term-storage/container.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once -#include -#include -#include "cluster.h" - -namespace Antares::Data::ShortTermStorage -{ -class STStorageInput -{ -public: - bool validate() const; - // 1. Read list.ini - bool createSTStorageClustersFromIniFile(const std::string& path); - // 2. Read ALL series - bool loadSeriesFromFolder(const std::string& folder) const; - // Number of ST storages - std::size_t count() const; - - bool saveToFolder(const std::string& folder) const; - bool saveDataSeriesToFolder(const std::string& folder) const; - - - std::vector storagesByIndex; - std::map storagesById; -}; -} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/parts/short-term-storage/properties.cpp b/src/libs/antares/study/parts/short-term-storage/properties.cpp index 058a8b5f3a..546717588e 100644 --- a/src/libs/antares/study/parts/short-term-storage/properties.cpp +++ b/src/libs/antares/study/parts/short-term-storage/properties.cpp @@ -1,80 +1,41 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/study/parts/short-term-storage/properties.h" + #include -#include "properties.h" +#include + +#include #define SEP Yuni::IO::Separator namespace Antares::Data::ShortTermStorage { -const std::map Properties::ST_STORAGE_PROPERTY_GROUP_ENUM - = {{"PSP_open", Group::PSP_open}, - {"PSP_closed", Group::PSP_closed}, - {"Pondage", Group::Pondage}, - {"Battery", Group::Battery}, - {"Other1", Group::Other1}, - {"Other2", Group::Other2}, - {"Other3", Group::Other3}, - {"Other4", Group::Other4}, - {"Other5", Group::Other5}}; - -unsigned int groupIndex(Group group) -{ - switch (group) - { - case Group::PSP_open: - return 0; - case Group::PSP_closed: - return 1; - case Group::Pondage: - return 2; - case Group::Battery: - return 3; - case Group::Other1: - return 4; - case Group::Other2: - return 5; - case Group::Other3: - return 6; - case Group::Other4: - return 7; - case Group::Other5: - return 8; - default: - throw std::invalid_argument("Group not recognized"); - } -} bool Properties::loadKey(const IniFile::Property* p) { - auto valueForOptional = [p](std::optional& opt) { + auto valueForOptional = [p](std::optional& opt) + { if (double tmp; p->value.to(tmp)) { opt = tmp; @@ -84,62 +45,61 @@ bool Properties::loadKey(const IniFile::Property* p) }; if (p->key == "injectionnominalcapacity") + { return valueForOptional(this->injectionNominalCapacity); + } if (p->key == "withdrawalnominalcapacity") + { return valueForOptional(this->withdrawalNominalCapacity); + } if (p->key == "reservoircapacity") + { return valueForOptional(this->reservoirCapacity); + } if (p->key == "efficiency") + { return p->value.to(this->efficiencyFactor); + } if (p->key == "name") + { return p->value.to(this->name); + } if (p->key == "initiallevel") + { return p->value.to(this->initialLevel); + } if (p->key == "initialleveloptim") + { return p->value.to(this->initialLevelOptim); + } if (p->key == "group") { - if (auto it = Properties::ST_STORAGE_PROPERTY_GROUP_ENUM.find(p->value.c_str()); - it != Properties::ST_STORAGE_PROPERTY_GROUP_ENUM.end()) - { - this->group = it->second; - return true; - } - return false; + this->groupName = p->value.c_str(); + boost::to_upper(this->groupName); + return true; } - return false; -} - -bool Properties::saveToFolder(const std::string& folder) const -{ - const std::string pathIni(folder + SEP + "list.ini"); - - // Make sure the folder is created - if (!Yuni::IO::Directory::Create(folder)) + if (p->key == "enabled") { - logs.warning() << "Couldn't create dir for sts: " << folder; - return false; + return p->value.to(this->enabled); } - logs.debug() << "saving file " << pathIni; + return false; +} - IniFile ini; +void Properties::save(IniFile& ini) const +{ IniFile::Section* s = ini.addSection(this->name); s->add("name", this->name); - - for (const auto& [key, value] : ST_STORAGE_PROPERTY_GROUP_ENUM) - if (value == this->group) - s->add("group", key); - + s->add("group", this->groupName); s->add("reservoircapacity", this->reservoirCapacity); s->add("initiallevel", this->initialLevel); s->add("injectionnominalcapacity", this->injectionNominalCapacity); @@ -147,14 +107,13 @@ bool Properties::saveToFolder(const std::string& folder) const s->add("efficiency", this->efficiencyFactor); s->add("initialleveloptim", this->initialLevelOptim); - - - return ini.save(pathIni); + s->add("enabled", this->enabled); } bool Properties::validate() { - auto checkMandatory = [this](const std::optional& prop, const std::string& label) { + auto checkMandatory = [this](const std::optional& prop, const std::string& label) + { if (!prop.has_value()) { logs.error() << "Property " << label << " is mandatory for short term storage " @@ -165,13 +124,19 @@ bool Properties::validate() }; if (!checkMandatory(injectionNominalCapacity, "injectionnominalcapacity")) + { return false; + } if (!checkMandatory(withdrawalNominalCapacity, "withdrawalnominalcapacity")) + { return false; + } if (!checkMandatory(reservoirCapacity, "reservoircapacity")) + { return false; + } if (injectionNominalCapacity < 0) { @@ -187,37 +152,35 @@ bool Properties::validate() } if (reservoirCapacity < 0) { - logs.error() << "Property reservoircapacity must be >= 0 " - << "for short term storage " << name; + logs.error() << "Property reservoircapacity must be >= 0 " << "for short term storage " + << name; return false; } if (efficiencyFactor < 0) { - logs.warning() << "Property efficiency must be >= 0 " - << "for short term storage " << name; + logs.warning() << "Property efficiency must be >= 0 " << "for short term storage " << name; efficiencyFactor = 0; } if (efficiencyFactor > 1) { - logs.warning() << "Property efficiency must be <= 1 " - << "for short term storage " << name; + logs.warning() << "Property efficiency must be <= 1 " << "for short term storage " << name; efficiencyFactor = 1; } if (initialLevel < 0) { initialLevel = initiallevelDefault; - logs.warning() << "initiallevel for cluster: " << name << " should be positive, value has been set to " << initialLevel; - + logs.warning() << "initiallevel for cluster: " << name + << " should be positive, value has been set to " << initialLevel; } if (initialLevel > 1) { initialLevel = initiallevelDefault; - logs.warning() << "initiallevel for cluster: " << name << " should be inferior to 1, value has been set to " << initialLevel; - + logs.warning() << "initiallevel for cluster: " << name + << " should be inferior to 1, value has been set to " << initialLevel; } return true; diff --git a/src/libs/antares/study/parts/short-term-storage/properties.h b/src/libs/antares/study/parts/short-term-storage/properties.h deleted file mode 100644 index 58e79b1241..0000000000 --- a/src/libs/antares/study/parts/short-term-storage/properties.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include -#include -#include - -#include - -namespace Antares::Data::ShortTermStorage -{ -enum class Group -{ - PSP_open, - PSP_closed, - Pondage, - Battery, - Other1, - Other2, - Other3, - Other4, - Other5 -}; - -unsigned int groupIndex(Group group); - -class Properties -{ -public: - bool validate(); - bool loadKey(const IniFile::Property* p); - bool saveToFolder(const std::string& folder) const; - - // Not optional Injection nominal capacity, >= 0 - std::optional injectionNominalCapacity; - // Not optional Withdrawal nominal capacity, >= 0 - std::optional withdrawalNominalCapacity; - // Not optional Reservoir capacity in MWh, >= 0 - std::optional reservoirCapacity; - // Initial level, <= 1 - double initialLevel = initiallevelDefault; - // Bool to optimise or not initial level - bool initialLevelOptim = false; - // Efficiency factor between 0 and 1 - double efficiencyFactor = 1; - // Used to sort outputs - Group group = Group::Other1; - // cluster name - std::string name; - - static const std::map ST_STORAGE_PROPERTY_GROUP_ENUM; -private: - static constexpr double initiallevelDefault = .5; -}; -} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/parts/short-term-storage/series.cpp b/src/libs/antares/study/parts/short-term-storage/series.cpp index 7f36e35aba..bda3bc0ed2 100644 --- a/src/libs/antares/study/parts/short-term-storage/series.cpp +++ b/src/libs/antares/study/parts/short-term-storage/series.cpp @@ -1,37 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include +#include "antares/study/parts/short-term-storage/series.h" -#include #include +#include -#include "series.h" +#include + +#include +#include "antares/antares/constants.h" #define SEP Yuni::IO::Separator @@ -90,13 +85,13 @@ bool loadFile(const std::string& path, std::vector& vect) catch (const std::invalid_argument& ex) { logs.error() << "Failed reading file: " << path << " conversion to double failed at line " - << lineCount + 1 << " value: " << line; + << lineCount + 1 << " value: " << line; return false; } catch (const std::out_of_range& ex) { logs.error() << "Failed reading file: " << path << " value is out of bounds at line " - << lineCount + 1 << " value: " << line; + << lineCount + 1 << " value: " << line; return false; } return true; @@ -104,9 +99,12 @@ bool loadFile(const std::string& path, std::vector& vect) void Series::fillDefaultSeriesIfEmpty() { - auto fillIfEmpty = [](std::vector& v, double value) { + auto fillIfEmpty = [](std::vector& v, double value) + { if (v.empty()) + { v.resize(HOURS_PER_YEAR, value); + } }; fillIfEmpty(maxInjectionModulation, 1.0); @@ -127,9 +125,8 @@ bool Series::saveToFolder(const std::string& folder) const bool ret = true; - auto checkWrite = [&ret, &folder](const std::string& name, const std::vector& content) { - ret = writeVectorToFile(folder + SEP + name, content) && ret; - }; + auto checkWrite = [&ret, &folder](const std::string& name, const std::vector& content) + { ret = writeVectorToFile(folder + SEP + name, content) && ret; }; checkWrite("PMAX-injection.txt", maxInjectionModulation); checkWrite("PMAX-withdrawal.txt", maxWithdrawalModulation); @@ -147,8 +144,10 @@ bool writeVectorToFile(const std::string& path, const std::vector& vect) std::ofstream fout(path); fout << std::setprecision(14); - for (const auto& x : vect) + for (const auto& x: vect) + { fout << x << '\n'; + } } catch (...) { @@ -162,12 +161,12 @@ bool writeVectorToFile(const std::string& path, const std::vector& vect) bool Series::validate() const { return validateSizes() && validateMaxInjection() && validateMaxWithdrawal() - && validateRuleCurves(); + && validateRuleCurves(); } -static bool checkVectBetweenZeroOne(const std::vector& v, const std::string& name ) +static bool checkVectBetweenZeroOne(const std::vector& v, const std::string& name) { - if(!std::all_of(v.begin(), v.end(), [](double d){ return (d >= 0.0 && d <= 1.0); })) + if (!std::all_of(v.begin(), v.end(), [](double d) { return (d >= 0.0 && d <= 1.0); })) { logs.warning() << "Values for " << name << " series should be between 0 and 1"; return false; @@ -195,15 +194,16 @@ bool Series::validateMaxInjection() const bool Series::validateMaxWithdrawal() const { return checkVectBetweenZeroOne(maxWithdrawalModulation, "PMAX withdrawal"); - } bool Series::validateRuleCurves() const { if (!validateUpperRuleCurve() || !validateLowerRuleCurve()) + { return false; + } - for (int i = 0; i < HOURS_PER_YEAR; i++) + for (unsigned int i = 0; i < HOURS_PER_YEAR; i++) { if (lowerRuleCurve[i] > upperRuleCurve[i]) { diff --git a/src/libs/antares/study/parts/short-term-storage/series.h b/src/libs/antares/study/parts/short-term-storage/series.h deleted file mode 100644 index 8ab2e4f620..0000000000 --- a/src/libs/antares/study/parts/short-term-storage/series.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once -#include -#include - -namespace Antares::Data::ShortTermStorage -{ -class Series -{ -public: - // check if series values are valid - bool validate() const; - - // load all series files with folder path - bool loadFromFolder(const std::string& folder); - void fillDefaultSeriesIfEmpty(); - - bool saveToFolder(const std::string& folder) const; - - std::vector maxInjectionModulation; - std::vector maxWithdrawalModulation; - std::vector inflows; - std::vector lowerRuleCurve; - std::vector upperRuleCurve; -private: - bool validateSizes() const; - bool validateMaxInjection() const; - bool validateMaxWithdrawal() const; - bool validateRuleCurves() const; - bool validateUpperRuleCurve() const; - bool validateLowerRuleCurve() const; -}; - -bool loadFile(const std::string& folder, std::vector& vect); -bool writeVectorToFile(const std::string& path, const std::vector& vect); - -} // namespace Antares::Data::ShortTermStorage diff --git a/src/libs/antares/study/parts/solar/container.cpp b/src/libs/antares/study/parts/solar/container.cpp index 35e15319da..27e96d823c 100644 --- a/src/libs/antares/study/parts/solar/container.cpp +++ b/src/libs/antares/study/parts/solar/container.cpp @@ -1,85 +1,78 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/solar/container.h" + #include -#include "../../study.h" -#include "container.h" + #include "antares/study/parts/parts.h" +#include "antares/study/study.h" using namespace Yuni; -namespace Antares -{ -namespace Data -{ -namespace Solar +namespace Antares::Data::Solar { -Container::Container() : prepro(nullptr), series(nullptr) +Container::Container(): + prepro(nullptr), + series(tsNumbers) { } Container::~Container() { delete prepro; - delete series; } bool Container::forceReload(bool reload) const { bool ret = true; - if (series) - ret = series->forceReload(reload) && ret; + ret = series.forceReload(reload) && ret; if (prepro) + { ret = prepro->forceReload(reload) && ret; + } return ret; } void Container::markAsModified() const { - if (series) - series->markAsModified(); + series.markAsModified(); if (prepro) + { prepro->markAsModified(); + } } uint64_t Container::memoryUsage() const { - return sizeof(Container) + ((!series) ? 0 : DataSeriesSolarMemoryUsage(series)) - + ((!prepro) ? 0 : prepro->memoryUsage()); + return sizeof(Container) + series.memoryUsage() + ((!prepro) ? 0 : prepro->memoryUsage()); } void Container::resetToDefault() { - if (series) - series->timeSeries.reset(1, HOURS_PER_YEAR); + series.reset(); if (prepro) + { prepro->resetToDefault(); + } } -} // namespace Solar -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::Solar diff --git a/src/libs/antares/study/parts/solar/container.h b/src/libs/antares/study/parts/solar/container.h deleted file mode 100644 index ba37906391..0000000000 --- a/src/libs/antares/study/parts/solar/container.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_CONTAINER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_CONTAINER_H__ - -#include "series.h" - -namespace Antares -{ -namespace Data -{ -namespace Solar -{ -class Prepro; -class Container -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Container(); - //! Destructor - ~Container(); - //@} - - /*! - ** \brief Reset to default values - */ - void resetToDefault(); - - /*! - ** \brief Make sure that all data are loaded - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark all data as modified - */ - void markAsModified() const; - - /*! - ** \brief Get the amount of memory currently used by the class - */ - uint64_t memoryUsage() const; - -public: - //! Data for the pre-processor - Data::Solar::Prepro* prepro; - /*! Data for time-series */ - DataSeriesSolar* series; - -}; // class Container - -} // namespace Solar -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_CONTAINER_H__ diff --git a/src/libs/antares/study/parts/solar/prepro.cpp b/src/libs/antares/study/parts/solar/prepro.cpp index db840ddcfb..e11b4e00ea 100644 --- a/src/libs/antares/study/parts/solar/prepro.cpp +++ b/src/libs/antares/study/parts/solar/prepro.cpp @@ -1,33 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/solar/prepro.h" + #include -#include "prepro.h" -#include "../../study.h" + +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; @@ -38,7 +34,8 @@ namespace Data { namespace Solar { -Prepro::Prepro() : xcast(timeSeriesSolar) +Prepro::Prepro(): + xcast(timeSeriesSolar) { } diff --git a/src/libs/antares/study/parts/solar/prepro.h b/src/libs/antares/study/parts/solar/prepro.h deleted file mode 100644 index 836e772f83..0000000000 --- a/src/libs/antares/study/parts/solar/prepro.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ -#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ - -#include "../../xcast.h" - -namespace Antares -{ -namespace Data -{ -namespace Solar -{ -/*! -** \brief Prepro Solar -*/ -class Prepro -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - Prepro(); - //! Destructor - ~Prepro(); - //@} - - /*! - ** \brief Try to estimate the amount of memory required by this class for a simulation - */ - - - /*! - ** \brief Solar data from a folder - */ - bool loadFromFolder(const AnyString& folder); - - /*! - ** \brief Save data to a folder - */ - bool saveToFolder(const AnyString& folder) const; - - /*! - ** \brief Get the amount of memory currently used - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Make sure that all data are loaded in memory - */ - bool forceReload(bool reload = false) const; - - void markAsModified() const; - - /*! - ** \brief Reset to default all values - */ - void resetToDefault(); - -public: - //! XCast - Data::XCast xcast; - -private: - bool internalSolarFromFolder(Study& study, const char* folder, uint length); - bool internalSolarFormatBefore33(Study& study, const YString& folder); - -}; // Prepro - -} // namespace Solar -} // namespace Data -} // namespace Antares - -#include "prepro.hxx" - -#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ diff --git a/src/libs/antares/study/parts/solar/prepro.hxx b/src/libs/antares/study/parts/solar/prepro.hxx deleted file mode 100644 index e0d5c01b7d..0000000000 --- a/src/libs/antares/study/parts/solar/prepro.hxx +++ /dev/null @@ -1,56 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_HXX__ - -namespace Antares::Data::Solar -{ -inline uint64_t Prepro::memoryUsage() const -{ - return xcast.memoryUsage(); -} - -inline bool Prepro::forceReload(bool reload) const -{ - return xcast.forceReload(reload); -} - -inline void Prepro::markAsModified() const -{ - xcast.markAsModified(); -} - -inline void Prepro::resetToDefault() -{ - xcast.resetToDefaultValues(); -} - -} // namespace Antares::Data::Solar - - - -#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_PREPRO_H__ diff --git a/src/libs/antares/study/parts/solar/series.cpp b/src/libs/antares/study/parts/solar/series.cpp deleted file mode 100644 index 2a4b8de360..0000000000 --- a/src/libs/antares/study/parts/solar/series.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include -#include "series.h" -#include "../../study.h" - -using namespace Yuni; - -#define SEP IO::Separator - -namespace Antares -{ -namespace Data -{ -int DataSeriesSolarLoadFromFolder(Study& study, - DataSeriesSolar* s, - const AreaName& areaID, - const char* folder) -{ - /* Assert */ - assert(s); - assert(folder); - assert('\0' != *folder); - - Yuni::String& buffer = study.buffer; - - int ret = 1; - /* Solar the matrix */ - buffer.clear() << folder << SEP << "solar_" << areaID << '.' << study.inputExtension; - ret = s->timeSeries.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &study.dataBuffer) && ret; - - if (study.usedByTheSolver && study.parameters.derated) - s->timeSeries.averageTimeseries(); - - s->timeseriesNumbers.clear(); - - return ret; -} - -int DataSeriesSolarSaveToFolder(DataSeriesSolar* s, const AreaName& areaID, const char folder[]) -{ - if (!s) - return 1; - - /* Assert */ - assert(folder); - assert('\0' != *folder); - - if (IO::Directory::Create(folder)) - { - int res = 1; - - String buffer; - buffer.clear() << folder << SEP << "solar_" << areaID << ".txt"; - res = s->timeSeries.saveToCSVFile(buffer, /*decimal*/ 0) && res; - - return res; - } - return 0; -} - -double* DataSeriesSolar::getColumn(unsigned int year) const -{ - return timeSeries[getIndex(year)]; -} - -double DataSeriesSolar::getCoefficient(const unsigned int year, const unsigned int hour) const -{ - return timeSeries[getIndex(year)][hour]; -} - -unsigned int DataSeriesSolar::getIndex(unsigned int year) const -{ - return (timeSeries.width != 1) ? timeseriesNumbers[0][year] : 0; -} - -bool DataSeriesSolar::forceReload(bool reload) const -{ - return timeSeries.forceReload(reload); -} - -void DataSeriesSolar::markAsModified() const -{ - timeSeries.markAsModified(); -} - -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/parts/solar/series.h b/src/libs/antares/study/parts/solar/series.h deleted file mode 100644 index 1f94c24117..0000000000 --- a/src/libs/antares/study/parts/solar/series.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_TIMESERIES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_TIMESERIES_H__ - -#include -#include "../../fwd.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Data series (Solar) -*/ -class DataSeriesSolar -{ -public: - - bool forceReload(bool reload = false) const; - - void markAsModified() const; - - double* getColumn(unsigned int year) const; - double getCoefficient(const unsigned int year, const unsigned int hour) const; - unsigned int getIndex(unsigned int year) const; - -public: - /*! - ** \brief Time series (MW) - ** - ** Merely a matrix of TimeSeriesCount * 8760 values - */ - Matrix timeSeries; - - /*! - ** \brief Monte-Carlo - */ - Matrix timeseriesNumbers; - -}; /* class DataSeriesSolar */ - -/*! -** \brief Solar wind data series from a file -** \ingroup windseries -** -** \param d Data series -** \param areaID The ID of the area associated to the data series -** \param folder The source folder -** \return A non-zero value if the operation succeeded, 0 otherwise -*/ -int DataSeriesSolarLoadFromFolder(Study& s, - DataSeriesSolar* d, - const AreaName& areaID, - const char folder[]); - -/*! -** \brief Save wind data series from a file -** \ingroup windseries -** -** \param d Data series -** \param areaID The ID of the area associated to the data series -** \param folder The target folder -** \return A non-zero value if the operation succeeded, 0 otherwise -*/ -int DataSeriesSolarSaveToFolder(DataSeriesSolar* d, const AreaName& areaID, const char folder[]); - -/*! -** \brief Get the size (bytes) in memory occupied by a `DataSeriesSolar` structure -*/ -uint64_t DataSeriesSolarMemoryUsage(DataSeriesSolar* w); - -} // namespace Data -} // namespace Antares - -#include "series.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_SOLAR_TIMESERIES_H__ */ diff --git a/src/libs/antares/study/parts/solar/series.hxx b/src/libs/antares/study/parts/solar/series.hxx deleted file mode 100644 index 3654163ae0..0000000000 --- a/src/libs/antares/study/parts/solar/series.hxx +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_SOLAR_TIMESERIES_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_SOLAR_TIMESERIES_HXX__ - -namespace Antares -{ -namespace Data -{ -inline uint64_t DataSeriesSolarMemoryUsage(DataSeriesSolar* l) -{ - return (l) ? l->timeSeries.memoryUsage() : 0; -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_SOLAR_TIMESERIES_HXX__ diff --git a/src/libs/antares/study/parts/thermal/cluster.cpp b/src/libs/antares/study/parts/thermal/cluster.cpp index a6c8c49d6d..da502ac29e 100644 --- a/src/libs/antares/study/parts/thermal/cluster.cpp +++ b/src/libs/antares/study/parts/thermal/cluster.cpp @@ -1,43 +1,41 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/study/parts/thermal/cluster.h" + #include +#include +#include + +#include #include #include -#include -#include -#include -#include "../../study.h" -#include "cluster.h" + #include #include +#include #include +#include "antares/study/parts/thermal/cluster.h" +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; @@ -46,26 +44,24 @@ using namespace Antares; #define SEP IO::Separator -namespace Yuni +namespace Yuni::Extension::CString { -namespace Extension -{ -namespace CString -{ -bool Into::Perform(AnyString string, TargetType& out) +bool Into::Perform(AnyString string, TargetType& out) { string.trim(); if (string.empty()) + { return false; + } if (string.equalsInsensitive("uniform")) { - out = Antares::Data::thermalLawUniform; + out = Antares::Data::LawUniform; return true; } if (string.equalsInsensitive("geometric")) { - out = Antares::Data::thermalLawGeometric; + out = Antares::Data::LawGeometric; return true; } return false; @@ -75,7 +71,9 @@ bool Into::Perform(AnyString string, TargetType& { string.trim(); if (string.empty()) + { return false; + } if (string.equalsInsensitive("setManually")) { @@ -94,7 +92,9 @@ bool Into::Perform(AnyString string, T { string.trim(); if (string.empty()) + { return false; + } if (string.equalsInsensitive("use global")) { @@ -114,39 +114,24 @@ bool Into::Perform(AnyString string, T return false; } -} // namespace CString -} // namespace Extension -} // namespace Yuni +} // namespace Yuni::Extension::CString namespace Antares { namespace Data { -Data::ThermalCluster::ThermalCluster(Area* parent) : +Data::ThermalCluster::ThermalCluster(Area* parent): Cluster(parent), - groupID(thermalDispatchGrpOther1), - mustrun(false), - mustrunOrigin(false), - nominalCapacityWithSpinning(0.), - minStablePower(0.), - minUpTime(1), - minDownTime(1), - spinning(0.), - forcedVolatility(0.), - plannedVolatility(0.), - forcedLaw(thermalLawUniform), - plannedLaw(thermalLawUniform), PthetaInf(HOURS_PER_YEAR, 0), costsTimeSeries(1, CostsTimeSeries()) { // assert - assert(parent and "A parent for a thermal dispatchable cluster can not be null"); + assert(parent && "A parent for a thermal dispatchable cluster can not be null"); } Data::ThermalCluster::~ThermalCluster() { delete prepro; - delete series; } uint ThermalCluster::groupId() const @@ -215,43 +200,45 @@ void Data::ThermalCluster::copyFrom(const ThermalCluster& cluster) // Making sure that the data related to the prepro and timeseries are present // prepro - if (not prepro) - prepro = new PreproThermal(this->weak_from_this()); - if (not series) - series = new DataSeriesCommon(); + if (!prepro) + { + prepro = new PreproAvailability(id(), unitCount); + } prepro->copyFrom(*cluster.prepro); ecoInput.copyFrom(cluster.ecoInput); // timseries - series->timeSeries = cluster.series->timeSeries; - cluster.series->timeSeries.unloadFromMemory(); - series->timeseriesNumbers.clear(); + series.timeSeries = cluster.series.timeSeries; + cluster.series.timeSeries.unloadFromMemory(); + series.timeseriesNumbers.clear(); // The parent must be invalidated to make sure that the clusters are really // re-written at the next 'Save' from the user interface. if (parentArea) + { parentArea->forceReload(); + } } static Data::ThermalCluster::ThermalDispatchableGroup stringToGroup(Data::ClusterName& newgrp) { using namespace Antares::Data; - const static std::map mapping - = {{"nuclear", ThermalCluster::thermalDispatchGrpNuclear}, - {"lignite", ThermalCluster::thermalDispatchGrpLignite}, - {"hard coal", ThermalCluster::thermalDispatchGrpHardCoal}, - {"gas", ThermalCluster::thermalDispatchGrpGas}, - {"oil", ThermalCluster::thermalDispatchGrpOil}, - {"mixed fuel", ThermalCluster::thermalDispatchGrpMixedFuel}, - {"other", ThermalCluster::thermalDispatchGrpOther1}, - {"other 1", ThermalCluster::thermalDispatchGrpOther1}, - {"other 2", ThermalCluster::thermalDispatchGrpOther2}, - {"other 3", ThermalCluster::thermalDispatchGrpOther3}, - {"other 4", ThermalCluster::thermalDispatchGrpOther4}}; + const static std::map mapping = { + {"nuclear", ThermalCluster::thermalDispatchGrpNuclear}, + {"lignite", ThermalCluster::thermalDispatchGrpLignite}, + {"hard coal", ThermalCluster::thermalDispatchGrpHardCoal}, + {"gas", ThermalCluster::thermalDispatchGrpGas}, + {"oil", ThermalCluster::thermalDispatchGrpOil}, + {"mixed fuel", ThermalCluster::thermalDispatchGrpMixedFuel}, + {"other", ThermalCluster::thermalDispatchGrpOther1}, + {"other 1", ThermalCluster::thermalDispatchGrpOther1}, + {"other 2", ThermalCluster::thermalDispatchGrpOther2}, + {"other 3", ThermalCluster::thermalDispatchGrpOther3}, + {"other 4", ThermalCluster::thermalDispatchGrpOther4}}; boost::to_lower(newgrp); - if (auto res = mapping.find(newgrp);res != mapping.end()) + if (auto res = mapping.find(newgrp); res != mapping.end()) { return res->second; } @@ -274,11 +261,12 @@ void Data::ThermalCluster::setGroup(Data::ClusterName newgrp) bool Data::ThermalCluster::forceReload(bool reload) const { bool ret = true; - ret = modulation.forceReload(reload) and ret; - if (series) - ret = series->forceReload(reload) and ret; + ret = modulation.forceReload(reload) && ret; + ret = series.forceReload(reload) && ret; if (prepro) - ret = prepro->forceReload(reload) and ret; + { + ret = prepro->forceReload(reload) && ret; + } ret = ecoInput.forceReload(reload) && ret; return ret; } @@ -286,27 +274,26 @@ bool Data::ThermalCluster::forceReload(bool reload) const void Data::ThermalCluster::markAsModified() const { modulation.markAsModified(); - if (series) - series->markAsModified(); + series.markAsModified(); if (prepro) + { prepro->markAsModified(); + } ecoInput.markAsModified(); } void Data::ThermalCluster::calculationOfSpinning() { - assert(this->series); - // nominal capacity (for solver) nominalCapacityWithSpinning = nominalCapacity; // Nothing to do if the spinning is equal to zero // because it will the same multiply all entries of the matrix by 1. - if (not Math::Zero(spinning)) + if (!Utils::isZero(spinning)) { logs.debug() << " Calculation of spinning... " << parentArea->name << "::" << pName; - auto& ts = series->timeSeries; + auto& ts = series.timeSeries; // The formula // const double s = 1. - cluster.spinning / 100.; */ @@ -384,7 +371,7 @@ void ThermalCluster::ComputeMarketBidTS() void ThermalCluster::MarginalCostEqualsMarketBid() { - for (auto& timeSeries : costsTimeSeries) + for (auto& timeSeries: costsTimeSeries) { auto& source = timeSeries.marketBidCostTS; auto& destination = timeSeries.marginalCostTS; @@ -395,9 +382,11 @@ void ThermalCluster::MarginalCostEqualsMarketBid() void ThermalCluster::ComputeProductionCostTS() { if (modulation.width == 0) + { return; + } - for (auto& timeSeries : costsTimeSeries) + for (auto& timeSeries: costsTimeSeries) { auto& productionCostTS = timeSeries.productionCostTs; auto& marginalCostTS = timeSeries.marginalCostTS; @@ -410,26 +399,23 @@ void ThermalCluster::ComputeProductionCostTS() } } - double Data::ThermalCluster::computeMarketBidCost(double fuelCost, - double co2EmissionFactor, - double co2cost) + double co2EmissionFactor, + double co2cost) { return fuelCost * 360.0 / fuelEfficiency + co2EmissionFactor * co2cost + variableomcost; } void Data::ThermalCluster::reverseCalculationOfSpinning() { - assert(this->series); - // Nothing to do if the spinning is equal to zero // because it will the same multiply all entries of the matrix by 1. - if (not Math::Zero(spinning)) + if (!Utils::isZero(spinning)) { logs.debug() << " Calculation of spinning (reverse)... " << parentArea->name << "::" << pName; - auto& ts = series->timeSeries; + auto& ts = series.timeSeries; // The formula // const double s = 1. - cluster.spinning / 100.; @@ -467,8 +453,8 @@ void Data::ThermalCluster::reset() forcedVolatility = 0.; plannedVolatility = 0.; // laws - plannedLaw = thermalLawUniform; - forcedLaw = thermalLawUniform; + plannedLaw = LawUniform; + forcedLaw = LawUniform; // costs costgeneration = setManually; @@ -489,32 +475,35 @@ void Data::ThermalCluster::reset() // warning: the variables `prepro` and `series` __must__ not be destroyed // since the interface may still have a pointer to them. // we must simply reset their content. - if (not prepro) - prepro = new PreproThermal(this->weak_from_this()); + if (!prepro) + { + prepro = new PreproAvailability(id(), unitCount); + } + prepro->reset(); ecoInput.reset(); } bool Data::ThermalCluster::integrityCheck() { - if (not parentArea) + if (!parentArea) { logs.error() << "Thermal cluster " << pName << ": The parent area is missing"; return false; } - if (Math::NaN(marketBidCost)) + if (std::isnan(marketBidCost)) { logs.error() << "Thermal cluster " << pName << ": NaN detected for market bid cost"; return false; } - if (Math::NaN(marginalCost)) + if (std::isnan(marginalCost)) { logs.error() << "Thermal cluster " << parentArea->name << '/' << pName << ": NaN detected for marginal cost"; return false; } - if (Math::NaN(spreadCost)) + if (std::isnan(spreadCost)) { logs.error() << "Thermal cluster " << parentArea->name << '/' << pName << ": NaN detected for marginal cost"; @@ -523,20 +512,6 @@ bool Data::ThermalCluster::integrityCheck() bool ret = true; - if (minUpTime > 168 or 0 == minUpTime) - { - logs.error() << "Thermal cluster " << parentArea->name << "/" << pName - << ": The min. up time must be between 1 and 168"; - minUpTime = 1; - ret = false; - } - if (minDownTime > 168 or 0 == minDownTime) - { - logs.error() << "Thermal cluster " << parentArea->name << "/" << pName - << ": The min. down time must be between 1 and 168"; - minDownTime = 1; - ret = false; - } if (nominalCapacity < 0.) { logs.error() << "Thermal cluster " << parentArea->name << "/" << pName @@ -548,9 +523,13 @@ bool Data::ThermalCluster::integrityCheck() if (spinning < 0. or spinning > 100.) { if (spinning < 0.) + { spinning = 0; + } else + { spinning = 100.; + } logs.error() << "Thermal cluster: " << parentArea->name << '/' << pName << ": The spinning must be within the range [0,+100] (rounded to " << spinning << ')'; @@ -594,7 +573,7 @@ bool Data::ThermalCluster::integrityCheck() { CString buffer; buffer << "Thermal cluster: " << parentArea->name << '/' << pName << ": Modulation"; - ret = MatrixTestForPositiveValues(buffer.c_str(), &modulation) and ret; + ret = MatrixTestForPositiveValues(buffer.c_str(), &modulation) && ret; } // la valeur minStablePower should not be modified @@ -646,9 +625,10 @@ uint64_t ThermalCluster::memoryUsage() const { uint64_t amount = sizeof(ThermalCluster) + modulation.memoryUsage(); if (prepro) + { amount += prepro->memoryUsage(); - if (series) - amount += series->memoryUsage(); + } + amount += series.memoryUsage(); amount += ecoInput.memoryUsage(); return amount; } @@ -656,7 +636,7 @@ uint64_t ThermalCluster::memoryUsage() const void ThermalCluster::calculatMinDivModulation() { minDivModulation.value = (modulation[thermalModulationCapacity][0] - / Math::Ceil(modulation[thermalModulationCapacity][0])); + / std::ceil(modulation[thermalModulationCapacity][0])); minDivModulation.index = 0; for (uint t = 1; t < modulation.height; t++) @@ -675,8 +655,10 @@ void ThermalCluster::calculatMinDivModulation() bool ThermalCluster::checkMinStablePower() { - if (not minDivModulation.isCalculated) // not has been initialized + if (!minDivModulation.isCalculated) // not has been initialized + { calculatMinDivModulation(); + } if (minDivModulation.value < 0) { @@ -687,11 +669,15 @@ bool ThermalCluster::checkMinStablePower() // calculate nominalCapacityWithSpinning double nomCapacityWithSpinning = nominalCapacity * (1 - spinning / 101); - if (Math::Zero(1 - spinning / 101)) + if (Utils::isZero(1 - spinning / 101)) + { minDivModulation.border = .0; + } else - minDivModulation.border - = Math::Min(nomCapacityWithSpinning, minStablePower) / nomCapacityWithSpinning; + { + minDivModulation.border = std::min(nomCapacityWithSpinning, minStablePower) + / nomCapacityWithSpinning; + } if (minDivModulation.value < minDivModulation.border) { @@ -703,17 +689,19 @@ bool ThermalCluster::checkMinStablePower() return true; } -bool ThermalCluster::checkMinStablePowerWithNewModulation(uint index, double value) +bool ThermalCluster::checkMinStablePowerWithNewModulation(uint idx, double value) { - if (not minDivModulation.isCalculated || index == minDivModulation.index) + if (!minDivModulation.isCalculated || idx == minDivModulation.index) + { calculatMinDivModulation(); + } else { double div = value / ceil(value); if (div < minDivModulation.value) { minDivModulation.value = div; - minDivModulation.index = index; + minDivModulation.index = idx; } } @@ -747,7 +735,7 @@ double ThermalCluster::getOperatingCost(uint serieIndex, uint hourInTheYear) con } else { - const uint tsIndex = Math::Min(serieIndex, costsTimeSeries.size() - 1); + const uint tsIndex = std::min(serieIndex, (uint)costsTimeSeries.size() - 1); return costsTimeSeries[tsIndex].productionCostTs[hourInTheYear]; } } @@ -762,17 +750,17 @@ double ThermalCluster::getMarginalCost(uint serieIndex, uint hourInTheYear) cons } else { - const uint tsIndex = Math::Min(serieIndex, costsTimeSeries.size() - 1); + const uint tsIndex = std::min(serieIndex, (uint)costsTimeSeries.size() - 1); return costsTimeSeries[tsIndex].marginalCostTS[hourInTheYear] * mod; } - /* Math::Min is necessary in case Availability has e.g 10 TS and both FuelCost & Co2Cost have + /* std::min is necessary in case Availability has e.g 10 TS and both FuelCost & Co2Cost have only 1TS. Then - > In order to save memory marginalCostTS vector has only one array inside -> that is used for all (e.g.10) TS*/ } double ThermalCluster::getMarketBidCost(uint hourInTheYear, uint year) const { - uint serieIndex = (series->timeSeries.width == 1) ? 0 : series->timeseriesNumbers[0][year]; + uint serieIndex = series.getSeriesIndex(year); double mod = modulation[thermalModulationMarketBid][serieIndex]; @@ -782,7 +770,7 @@ double ThermalCluster::getMarketBidCost(uint hourInTheYear, uint year) const } else { - const uint tsIndex = Math::Min(serieIndex, costsTimeSeries.size() - 1); + const uint tsIndex = std::min(serieIndex, (uint)costsTimeSeries.size() - 1); return costsTimeSeries[tsIndex].marketBidCostTS[hourInTheYear] * mod; } } @@ -797,28 +785,30 @@ void ThermalCluster::checkAndCorrectAvailability() bool condition = false; bool report = false; - for (uint y = 0; y != series->timeSeries.height; ++y) + for (uint y = 0; y != series.timeSeries.height; ++y) { - for (uint x = 0; x != series->timeSeries.width; ++x) + for (uint x = 0; x != series.timeSeries.width; ++x) { - auto rightpart - = PminDUnGroupeDuPalierThermique - * ceil(series->timeSeries.entry[x][y] / PmaxDUnGroupeDuPalierThermique); - condition = rightpart > series->timeSeries.entry[x][y]; + auto rightpart = PminDUnGroupeDuPalierThermique + * ceil(series.timeSeries.entry[x][y] / PmaxDUnGroupeDuPalierThermique); + condition = rightpart > series.timeSeries.entry[x][y]; if (condition) { - series->timeSeries.entry[x][y] = rightpart; + series.timeSeries.entry[x][y] = rightpart; report = true; } } } if (report) + { logs.warning() << "Area : " << parentArea->name << " cluster name : " << name() << " available power lifted to match Pmin and Pnom requirements"; + } } -bool ThermalCluster::isActive() const { +bool ThermalCluster::isActive() const +{ return enabled && !mustrun; } diff --git a/src/libs/antares/study/parts/thermal/cluster.h b/src/libs/antares/study/parts/thermal/cluster.h deleted file mode 100644 index a75ce10a00..0000000000 --- a/src/libs/antares/study/parts/thermal/cluster.h +++ /dev/null @@ -1,403 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_H__ - -#include -#include -#include -#include "defines.h" -#include "prepro.h" -#include "ecoInput.h" -#include "../common/cluster.h" -#include "../../fwd.h" -#include "pollutant.h" -#include -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -enum ThermalLaw -{ - thermalLawUniform, - thermalLawGeometric -}; - -enum ThermalModulation -{ - thermalModulationCost = 0, - thermalModulationMarketBid, - thermalModulationCapacity, - thermalMinGenModulation, - thermalModulationMax -}; - -enum CostGeneration -{ - setManually = 0, - useCostTimeseries -}; - -enum class LocalTSGenerationBehavior -{ - useGlobalParameter = 0, - forceGen, - forceNoGen -}; - -/*! -** \brief A single thermal cluster -*/ -class ThermalCluster final : public Cluster, public std::enable_shared_from_this -{ -public: - enum ThermalDispatchableGroup - { - //! Nuclear - thermalDispatchGrpNuclear = 0, - //! Lignite - thermalDispatchGrpLignite, - //! Hard Coal - thermalDispatchGrpHardCoal, - //! Gas - thermalDispatchGrpGas, - //! Oil - thermalDispatchGrpOil, - //! Mixed fuel - thermalDispatchGrpMixedFuel, - //! Other 1 - thermalDispatchGrpOther1, - //! Other 2 - thermalDispatchGrpOther2, - //! Other 3 - thermalDispatchGrpOther3, - //! Other 4 - thermalDispatchGrpOther4, - - //! The highest value - groupMax - }; - - Pollutant emissions; - - //! Set of thermal clusters - using Set = std::set; - //! Set of thermal clusters (pointer) - using SetPointer = std::set; - //! Vector of thermal clusters - using Vector = std::vector; - - /*! - ** \brief Get the group name string - ** \return A valid CString - */ - static const char* GroupName(enum ThermalDispatchableGroup grp); - - explicit ThermalCluster(Data::Area* parent); - - ThermalCluster() = delete; - ~ThermalCluster(); - - /*! - ** \brief Invalidate all data associated to the thermal cluster - */ - bool forceReload(bool reload) const override; - - /*! - ** \brief Mark the thermal cluster as modified - */ - void markAsModified() const override; - - /*! - ** \brief Reset to default values - ** - ** This method should only be called from the GUI - */ - void reset() override; - - //! Set the group - void setGroup(Data::ClusterName newgrp) override; - //@} - - //! \name Spinning - //@{ - /*! - ** \brief Calculation of spinning - ** - ** The formula is : TS[i,j] = TS[i,j] * (1 - Spinning / 100) - */ - void calculationOfSpinning(); - - //! \name MarketBid and Marginal Costs - //@{ - /*! - ** \brief Calculation of market bid and marginals costs per hour - */ - void ComputeCostTimeSeries(); - - /*! - ** \brief Calculation of spinning (reverse) - ** - ** The original formula for the calculation of the spinning is : - ** TS[i,j] = TS[i,j] * (1 - Spinning / 100) - ** - ** This method is used to removed the spinning, before exporting the TS matrices - ** into the input. - */ - void reverseCalculationOfSpinning(); - //@} - - /*! - ** \brief Check and fix all values of a thermal cluster - ** - ** \return False if an error has been detected and fixed with a default value - */ - bool integrityCheck() override; - - /*! - ** \brief Copy data from another cluster - ** - ** The name and the id will remain untouched. - */ - void copyFrom(const ThermalCluster& cluster); - - /*! - ** \brief Group ID as an uint - */ - uint groupId() const override; - - /*! - ** \brief Get the memory consummed by the thermal cluster (in bytes) - */ - uint64_t memoryUsage() const override; - //@} - - //! \name validity of Min Stable Power - //@{ - // bool minStablePowerValidity() const; - - /*! - ** \brief Calculte the minimum modulation/ceil(modulation) from 8760 capacity modulation - */ - void calculatMinDivModulation(); - - /*! - ** \brief Check the validity of Min Stable Power - */ - bool checkMinStablePower(); - - /*! - ** \brief Check the validity of Min Stable Power with a new modulation value - */ - bool checkMinStablePowerWithNewModulation(uint index, double value); - //@} - - bool doWeGenerateTS(bool globalTSgeneration) const; - - double getOperatingCost(uint tsIndex, uint hourInTheYear) const; - double getMarginalCost(uint tsIndex, uint hourInTheYear) const; - double getMarketBidCost(uint hourInTheYear, uint year) const; - - // Check & correct availability timeseries for thermal availability - // Only applies if time-series are ready-made - void checkAndCorrectAvailability(); - - bool isActive() const; - - /*! - ** \brief The group ID - ** - ** This value is computed from the field 'group' in 'group() - ** \see group() - */ - ThermalDispatchableGroup groupID; - - //! Mustrun - bool mustrun; - //! Mustrun (as it were at the loading of the data) - // - // This value might differ from mustrun, because `mustrun` might be - // modified for different reasons. - // Only used by the solver in adequacy mode - bool mustrunOrigin; - - //! Nominal capacity - spinning (solver only) - double nominalCapacityWithSpinning; - - //! \name PMin - //@{ - //! Min. Stable Power (MW) - double minStablePower; - - struct DivModulation - { - DivModulation() : value(0.0), isCalculated(false), isValidated(false) - { - } - - double value; - double border; - uint index; - bool isCalculated; - bool isValidated; - } minDivModulation; - - //! Min. Up time (1..168) - uint minUpTime; - //! Min. Down time (1..168) - uint minDownTime; - //! Max entre . minUp/minDown time (1..168) - uint minUpDownTime; - //@} - - //! Spinning (%) - double spinning; - - //! Efficiency (%) - double fuelEfficiency = 100; - - //! Forced Volatility - double forcedVolatility; - //! Planned volatility - double plannedVolatility; - - //! Law (ts-generator) - ThermalLaw forcedLaw; - //! Law (ts-generator) - ThermalLaw plannedLaw; - - //! \name Costs - // Marginal (€/MWh) MA - // Spread (€/MWh) SP - // Fixed (€ / hour) FI - // Start-up (€/start) SU - // Market bid (€/ MWh) MB - // - // v3.4: - // O(h) = MB * P(h) - // - // v3.5: - // solver input : MB - // output : - // O(h) = MA * P(h) - // if (P(h) > 0) - // O(h) += FI - // if (N(h) > N(h-1)) - // O(h) += SU* (N(h)-N(h-1)) - // - // \see 101206-antares-couts.doc - // - // v5.0: - // Abs( SU ) = 0 or in [0.005;5000000] - // v4.5: - // Abs( MA ) = 0 or in [0.005;50000] - // Abs( FI ) = 0 or in [0.005;50000] - // Abs( SU ) = 0 or in [0.005;50000] - // Abs( MB ) = 0 or in [0.005;50000] - // SP >=0 or in [0.005;50000] - // - //@{ - - //! Cost generation - CostGeneration costgeneration = setManually; - //! Marginal cost (euros/MWh) - double marginalCost = 0; - //! Spread (euros/MWh) - double spreadCost = 0; - //! Fixed cost (euros/hour) - double fixedCost = 0; - //! Startup cost (euros/startup) - double startupCost = 0; - //! Market bid cost (euros/MWh) - double marketBidCost = 0; - //! Variable O&M cost (euros/MWh) - double variableomcost = 0; - //@} - - /*! - ** \brief thermalMinGenModulation vector used in solver only to store the year values - ** 8760 vector - ** PthetaInf[hour] - */ - std::vector PthetaInf; - - //! Data for the preprocessor - PreproThermal* prepro = nullptr; - - /*! - ** \brief Production Cost, Market Bid Cost and Marginal Cost Matrixes - Per Hour and per Time - *Series - */ - struct CostsTimeSeries - { - std::array productionCostTs; - std::array marketBidCostTS; - std::array marginalCostTS; - }; - std::vector costsTimeSeries; - - EconomicInputData ecoInput; - - LocalTSGenerationBehavior tsGenBehavior = LocalTSGenerationBehavior::useGlobalParameter; - - friend class ThermalClusterList; - - double computeMarketBidCost(double fuelCost, double co2EmissionFactor, double co2cost); - - unsigned int precision() const override; - -private: - // Calculation of marketBid and marginal costs hourly time series - // - // Calculation of market bid and marginals costs per hour - // - // These time series can be set - // Market bid and marginal costs are set manually. - // Or if time series are used the formula is: - // Marginal_Cost[€/MWh] = Market_Bid_Cost[€/MWh] = (Fuel_Cost[€/GJ] * 3.6 * 100 / Efficiency[%]) - // CO2_emission_factor[tons/MWh] * C02_cost[€/tons] + Variable_O&M_cost[€/MWh] - - void fillMarketBidCostTS(); - void fillMarginalCostTS(); - void resizeCostTS(); - void ComputeMarketBidTS(); - void MarginalCostEqualsMarketBid(); - void ComputeProductionCostTS(); - - - -}; // class ThermalCluster -} // namespace Data -} // namespace Antares - -#include "cluster.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_H__ */ diff --git a/src/libs/antares/study/parts/thermal/cluster.hxx b/src/libs/antares/study/parts/thermal/cluster.hxx deleted file mode 100644 index d233cff9df..0000000000 --- a/src/libs/antares/study/parts/thermal/cluster.hxx +++ /dev/null @@ -1,160 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_HXX__ - -namespace Yuni -{ -namespace Extension -{ -namespace CString -{ -template -class Append -{ -public: - static void Perform(CStringT& string, Antares::Data::ThermalLaw law) - { - switch (law) - { - case Antares::Data::thermalLawUniform: - string += "uniform"; - break; - case Antares::Data::thermalLawGeometric: - string += "geometric"; - break; - } - } -}; - -template -class Append -{ -public: - static void Perform(CStringT& string, Antares::Data::CostGeneration costgeneration) - { - switch (costgeneration) - { - case Antares::Data::setManually: - string += "setManually"; - break; - case Antares::Data::useCostTimeseries: - string += "useCostTimeseries"; - break; - } - } -}; - -template -class Append -{ -public: - static void Perform(CStringT& string, Antares::Data::LocalTSGenerationBehavior behavior) - { - switch (behavior) - { - case Antares::Data::LocalTSGenerationBehavior::forceGen: - string += "force generation"; - break; - case Antares::Data::LocalTSGenerationBehavior::forceNoGen: - string += "force no generation"; - break; - default: - string += "use global"; - break; - } - } -}; - -template<> -class Into -{ -public: - using TargetType = Antares::Data::ThermalLaw; - enum - { - valid = 1 - }; - - static bool Perform(AnyString string, TargetType& out); - - template - static TargetType Perform(const StringT& s) - { - TargetType law = Antares::Data::thermalLawUniform; - Perform(s, law); - return law; - } -}; - -template<> -class Into -{ -public: - using TargetType = Antares::Data::CostGeneration; - enum class Validation - { - valid = 1 - }; - - static bool Perform(AnyString string, TargetType& out); - - template - static TargetType Perform(const StringT& s) - { - TargetType costgeneration = Antares::Data::setManually; - Perform(s, costgeneration); - return costgeneration; - } -}; - -template<> -class Into -{ -public: - using TargetType = Antares::Data::LocalTSGenerationBehavior; - enum - { - valid = 1 - }; - - static bool Perform(AnyString string, TargetType& out); - - template - static TargetType Perform(const StringT& s) - { - TargetType behavior = Antares::Data::LocalTSGenerationBehavior::useGlobalParameter; - Perform(s, behavior); - return behavior; - } -}; - -} // namespace CString -} // namespace Extension -} // namespace Yuni - -#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_CLUSTER_HXX__ diff --git a/src/libs/antares/study/parts/thermal/cluster_list.cpp b/src/libs/antares/study/parts/thermal/cluster_list.cpp index 2cd45cfa14..8435870d0a 100644 --- a/src/libs/antares/study/parts/thermal/cluster_list.cpp +++ b/src/libs/antares/study/parts/thermal/cluster_list.cpp @@ -1,6 +1,31 @@ -#include "cluster_list.h" -#include "cluster.h" -#include "../../study.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/study/parts/thermal/cluster_list.h" + +#include + +#include +#include "antares/study/parts/common/cluster.h" +#include "antares/study/study.h" namespace // anonymous { @@ -26,19 +51,52 @@ ThermalClusterList::ThermalClusterList() ThermalClusterList::~ThermalClusterList() { - // deleting all thermal clusters - clear(); + clearAll(); } #define SEP IO::Separator +std::string ThermalClusterList::typeID() const +{ + return "thermal"; +} + +uint64_t ThermalClusterList::memoryUsage() const +{ + uint64_t ret = sizeof(ThermalClusterList) + (2 * sizeof(void*)) * enabledAndMustRunCount(); + std::ranges::for_each(each_enabled_and_not_mustrun(), + [&ret](const auto c) { ret += c->memoryUsage(); }); + return ret; +} + static bool ThermalClusterLoadFromSection(const AnyString& filename, ThermalCluster& cluster, const IniFile::Section& section); +void ThermalClusterList::rebuildIndex() const +{ + uint indx = 0; + for (auto& c: each_enabled_and_not_mustrun()) + { + c->index = indx++; + } +} + +unsigned int ThermalClusterList::enabledAndNotMustRunCount() const +{ + return std::ranges::count_if(allClusters_, + [](auto c) { return c->isEnabled() && !c->isMustRun(); }); +} + +unsigned int ThermalClusterList::enabledAndMustRunCount() const +{ + return std::ranges::count_if(allClusters_, + [](auto c) { return c->isEnabled() && c->isMustRun(); }); +} + bool ThermalClusterList::loadFromFolder(Study& study, const AnyString& folder, Area* area) { - assert(area and "A parent area is required"); + assert(area && "A parent area is required"); // logs logs.info() << "Loading thermal configuration for the area " << area->name; @@ -47,24 +105,30 @@ bool ThermalClusterList::loadFromFolder(Study& study, const AnyString& folder, A study.buffer.clear() << folder << SEP << "list.ini"; IniFile ini; if (!ini.open(study.buffer)) + { return false; + } bool ret = true; if (!ini.firstSection) + { return ret; + } String modulationFile; for (auto* section = ini.firstSection; section; section = section->next) { if (section->name.empty()) + { continue; + } auto cluster = std::make_shared(area); // Load data of a thermal cluster from a ini file section - if (not ThermalClusterLoadFromSection(study.buffer, *cluster, *section)) + if (!ThermalClusterLoadFromSection(study.buffer, *cluster, *section)) { continue; } @@ -86,82 +150,89 @@ bool ThermalClusterList::loadFromFolder(Study& study, const AnyString& folder, A // allow startup cost between [-5 000 000 ;-5 000 000] (was [-50 000;50 000]) // Modulation - modulationFile.clear() << folder << SEP << ".." << SEP << ".." << SEP << "prepro" - << SEP << cluster->parentArea->id << SEP << cluster->id() - << SEP << "modulation." << study.inputExtension; - + modulationFile.clear() << folder << SEP << ".." << SEP << ".." << SEP << "prepro" << SEP + << cluster->parentArea->id << SEP << cluster->id() << SEP + << "modulation." << study.inputExtension; enum { options = Matrix<>::optFixedSize, }; - bool r = cluster->modulation.loadFromCSVFile( - modulationFile, thermalModulationMax, HOURS_PER_YEAR, options); - if (not r and study.usedByTheSolver) - { - cluster->modulation.reset(thermalModulationMax, HOURS_PER_YEAR); - cluster->modulation.fill(1.); - cluster->modulation.fillColumn(thermalMinGenModulation, 0.); - } - ret = ret and r; - // Special operations when not ran from the interface (aka solver) - if (study.usedByTheSolver) - { - if (not study.parameters.include.thermal.minStablePower) - cluster->minStablePower = 0.; - if (not study.parameters.include.thermal.minUPTime) - { - cluster->minUpDownTime = 1; - cluster->minUpTime = 1; - cluster->minDownTime = 1; - } - else - cluster->minUpDownTime - = Math::Max(cluster->minUpTime, cluster->minDownTime); + ret = cluster->modulation.loadFromCSVFile(modulationFile, + thermalModulationMax, + HOURS_PER_YEAR, + options) + && ret; - if (not study.parameters.include.reserve.spinning) - cluster->spinning = 0; + // Check the data integrity of the cluster + addToCompleteList(cluster); + } - cluster->nominalCapacityWithSpinning = cluster->nominalCapacity; - } + rebuildIndexes(); + rebuildIndex(); - // Check the data integrity of the cluster - cluster->integrityCheck(); + return ret; +} - // adding the thermal cluster - auto added = add(cluster); - if (not added) +bool ThermalClusterList::validateClusters(const Parameters& parameters) const +{ + bool ret = true; + + for (const auto& cluster: allClusters_) + { + cluster->minUpTime = std::clamp(cluster->minUpTime, 1u, 168u); + cluster->minDownTime = std::clamp(cluster->minDownTime, 1u, 168u); + + // update the minUpDownTime + cluster->minUpDownTime = std::max(cluster->minUpTime, cluster->minDownTime); + + if (!parameters.include.thermal.minStablePower) { - // This error should never happen - logs.error() << "Impossible to add the thermal cluster '" << cluster->name() - << "'"; - continue; + cluster->minStablePower = 0.; } - // keeping track of the cluster - mapping[cluster->id()] = added; + if (!parameters.include.thermal.minUPTime) + { + cluster->minUpDownTime = 1; + cluster->minUpTime = 1; + cluster->minDownTime = 1; + } + + if (!parameters.include.reserve.spinning) + { + cluster->spinning = 0; + } + + cluster->nominalCapacityWithSpinning = cluster->nominalCapacity; + + ret = cluster->integrityCheck() && ret; } return ret; } -YString ThermalClusterList::typeID() const -{ - return "thermal"; -} - static bool ThermalClusterLoadFromProperty(ThermalCluster& cluster, const IniFile::Property* p) { if (p->key.empty()) + { return false; + } if (p->key == "costgeneration") + { return p->value.to(cluster.costgeneration); + } if (p->key == "enabled") + { return p->value.to(cluster.enabled); + } if (p->key == "efficiency") + { return p->value.to(cluster.fuelEfficiency); + } if (p->key == "fixed-cost") + { return p->value.to(cluster.fixedCost); + } if (p->key == "group") { @@ -173,67 +244,83 @@ static bool ThermalClusterLoadFromProperty(ThermalCluster& cluster, const IniFil return p->value.to(cluster.tsGenBehavior); } if (p->key == "law.planned") + { return p->value.to(cluster.plannedLaw); + } if (p->key == "law.forced") + { return p->value.to(cluster.forcedLaw); + } if (p->key == "market-bid-cost") + { return p->value.to(cluster.marketBidCost); + } if (p->key == "marginal-cost") + { return p->value.to(cluster.marginalCost); + } if (p->key == "must-run") + { // mustrunOrigin will be initialized later, after LoadFromSection return p->value.to(cluster.mustrun); + } if (p->key == "min-stable-power") + { return p->value.to(cluster.minStablePower); + } if (p->key == "min-up-time") { - if (p->value.to(cluster.minUpTime)) - { - if (cluster.minUpTime < 1) - cluster.minUpTime = 1; - if (cluster.minUpTime > 168) - cluster.minUpTime = 168; - return true; - } - return false; + return p->value.to(cluster.minUpTime); } if (p->key == "min-down-time") { - if (p->value.to(cluster.minDownTime)) - { - if (cluster.minDownTime < 1) - cluster.minDownTime = 1; - if (cluster.minDownTime > 168) - cluster.minDownTime = 168; - return true; - } - return false; + return p->value.to(cluster.minDownTime); } if (p->key == "name") + { return true; // silently ignore it + } if (p->key == "nominalcapacity") + { return p->value.to(cluster.nominalCapacity); + } if (p->key == "spread-cost") + { return p->value.to(cluster.spreadCost); + } if (p->key == "spinning") + { return p->value.to(cluster.spinning); + } if (p->key == "startup-cost") + { return p->value.to(cluster.startupCost); + } if (p->key == "unitcount") + { return p->value.to(cluster.unitCount); + } if (p->key == "volatility.planned") + { return p->value.to(cluster.plannedVolatility); + } if (p->key == "volatility.forced") + { return p->value.to(cluster.forcedVolatility); + } if (p->key == "variableomcost") + { return p->value.to(cluster.variableomcost); + } - //pollutant + // pollutant if (auto it = Pollutant::namesToEnum.find(p->key.c_str()); it != Pollutant::namesToEnum.end()) - return p->value.to (cluster.emissions.factors[it->second]); + { + return p->value.to(cluster.emissions.factors[it->second]); + } // The property is unknown return false; @@ -244,7 +331,9 @@ bool ThermalClusterLoadFromSection(const AnyString& filename, const IniFile::Section& section) { if (section.name.empty()) + { return false; + } cluster.setName(section.name); @@ -265,270 +354,290 @@ bool ThermalClusterLoadFromSection(const AnyString& filename, << property->key << "`: The property is unknown and ignored"; } } - // update the minUpDownTime - cluster.minUpDownTime = Math::Max(cluster.minUpTime, cluster.minDownTime); } return true; } void ThermalClusterList::calculationOfSpinning() { - each([&](ThermalCluster& cluster) { cluster.calculationOfSpinning(); }); + for (auto& cluster: each_enabled()) + { + cluster->calculationOfSpinning(); + } } void ThermalClusterList::reverseCalculationOfSpinning() { - auto end = cluster.end(); - for (auto it = cluster.begin(); it != end; ++it) + for (auto& cluster: each_enabled()) { - auto& cluster = *(it->second); - cluster.reverseCalculationOfSpinning(); + cluster->reverseCalculationOfSpinning(); } } -bool ThermalClusterList::remove(const ClusterName& id) -{ - auto i = cluster.find(id); - if (i == cluster.end()) - return false; - - // Getting the pointer on the cluster - SharedPtr c = i->second; - - // Removing it from the list - cluster.erase(i); - // Invalidating the parent area - c->parentArea->forceReload(); - - // Rebuilding the index - rebuildIndex(); - return true; -} - void ThermalClusterList::enableMustrunForEveryone() { - // enabling the mustrun mode - each([&](ThermalCluster& cluster) { cluster.mustrun = true; }); + for (const auto& c: allClusters_) + { + c->mustrun = true; + } } void ThermalClusterList::ensureDataPrepro() { - auto end = cluster.end(); - for (auto it = cluster.begin(); it != end; ++it) + for (const auto& c: all()) { - auto c = it->second; - if (not c->prepro) - c->prepro = new PreproThermal(c); + if (!c->prepro) + { + c->prepro = new PreproAvailability(c->id(), c->unitCount); + } } } bool ThermalClusterList::saveToFolder(const AnyString& folder) const { // Make sure the folder is created - if (IO::Directory::Create(folder)) - { - Clob buffer; - bool ret = true; - - // Allocate the inifile structure - IniFile ini; - - // Browse all clusters - each([&](const Data::ThermalCluster& c) { - // Adding a section to the inifile - IniFile::Section* s = ini.addSection(c.name()); - - // The section must not be empty - // This key will be silently ignored the next time - s->add("name", c.name()); - - if (not c.group().empty()) - s->add("group", c.group()); - if (not c.enabled) - s->add("enabled", "false"); - if (not Math::Zero(c.unitCount)) - s->add("unitCount", c.unitCount); - if (not Math::Zero(c.nominalCapacity)) - s->add("nominalCapacity", c.nominalCapacity); - // TS generation - if (c.tsGenBehavior != LocalTSGenerationBehavior::useGlobalParameter) - { - s->add("gen-ts", c.tsGenBehavior); - } - // Min. Stable Power - if (not Math::Zero(c.minStablePower)) - s->add("min-stable-power", c.minStablePower); - - // Min up and min down time - if (c.minUpTime != 1) - s->add("min-up-time", c.minUpTime); - if (c.minDownTime != 1) - s->add("min-down-time", c.minDownTime); - - // must-run - if (c.mustrun) - s->add("must-run", "true"); - - // spinning - if (not Math::Zero(c.spinning)) - s->add("spinning", c.spinning); - - // efficiency - if (c.fuelEfficiency != 100.0) - s->add("efficiency", c.fuelEfficiency); - - // volatility - if (not Math::Zero(c.forcedVolatility)) - s->add("volatility.forced", Math::Round(c.forcedVolatility, 3)); - if (not Math::Zero(c.plannedVolatility)) - s->add("volatility.planned", Math::Round(c.plannedVolatility, 3)); - - // laws - if (c.forcedLaw != thermalLawUniform) - s->add("law.forced", c.forcedLaw); - if (c.plannedLaw != thermalLawUniform) - s->add("law.planned", c.plannedLaw); - - // costs - if (c.costgeneration != setManually) - s->add("costgeneration", c.costgeneration); - if (not Math::Zero(c.marginalCost)) - s->add("marginal-cost", Math::Round(c.marginalCost, 3)); - if (not Math::Zero(c.spreadCost)) - s->add("spread-cost", c.spreadCost); - if (not Math::Zero(c.fixedCost)) - s->add("fixed-cost", Math::Round(c.fixedCost, 3)); - if (not Math::Zero(c.startupCost)) - s->add("startup-cost", Math::Round(c.startupCost, 3)); - if (not Math::Zero(c.marketBidCost)) - s->add("market-bid-cost", Math::Round(c.marketBidCost, 3)); - if (!Math::Zero(c.variableomcost)) - s->add("variableomcost", Math::Round(c.variableomcost,3)); - - - //pollutant factor - for (auto const& [key, val] : Pollutant::namesToEnum) - s->add(key, c.emissions.factors[val]); + if (!IO::Directory::Create(folder)) + { + logs.error() << "I/O Error: impossible to create '" << folder << "'"; + return false; + } + bool ret = true; + Clob buffer; + // Allocate the inifile structure + IniFile ini; - buffer.clear() << folder << SEP << ".." << SEP << ".." << SEP << "prepro" << SEP - << c.parentArea->id << SEP << c.id(); - if (IO::Directory::Create(buffer)) - { - buffer.clear() << folder << SEP << ".." << SEP << ".." << SEP << "prepro" << SEP - << c.parentArea->id << SEP << c.id() << SEP << "modulation.txt"; + for (auto& c: allClusters_) + { + // Adding a section to the inifile + IniFile::Section* s = ini.addSection(c->name()); - ret = c.modulation.saveToCSVFile(buffer) and ret; - } - else - ret = 0; - }); + // The section must not be empty + // This key will be silently ignored the next time + s->add("name", c->name()); - // Write the ini file - buffer.clear() << folder << SEP << "list.ini"; - ret = ini.save(buffer) and ret; - } - else - { - logs.error() << "I/O Error: impossible to create '" << folder << "'"; - return false; + if (!c->group().empty()) + { + s->add("group", c->group()); + } + if (!c->enabled) + { + s->add("enabled", "false"); + } + if (!Utils::isZero(c->unitCount)) + { + s->add("unitCount", c->unitCount); + } + if (!Utils::isZero(c->nominalCapacity)) + { + s->add("nominalCapacity", c->nominalCapacity); + } + // TS generation + if (c->tsGenBehavior != LocalTSGenerationBehavior::useGlobalParameter) + { + s->add("gen-ts", c->tsGenBehavior); + } + // Min. Stable Power + if (!Utils::isZero(c->minStablePower)) + { + s->add("min-stable-power", c->minStablePower); + } + + // Min up and min down time + if (c->minUpTime != 1) + { + s->add("min-up-time", c->minUpTime); + } + if (c->minDownTime != 1) + { + s->add("min-down-time", c->minDownTime); + } + + // must-run + if (c->mustrun) + { + s->add("must-run", "true"); + } + + // spinning + if (!Utils::isZero(c->spinning)) + { + s->add("spinning", c->spinning); + } + + // efficiency + if (c->fuelEfficiency != 100.0) + { + s->add("efficiency", c->fuelEfficiency); + } + + // volatility + if (!Utils::isZero(c->forcedVolatility)) + { + s->add("volatility.forced", Utils::round(c->forcedVolatility, 3)); + } + if (!Utils::isZero(c->plannedVolatility)) + { + s->add("volatility.planned", Utils::round(c->plannedVolatility, 3)); + } + + // laws + if (c->forcedLaw != LawUniform) + { + s->add("law.forced", c->forcedLaw); + } + if (c->plannedLaw != LawUniform) + { + s->add("law.planned", c->plannedLaw); + } + + // costs + if (c->costgeneration != setManually) + { + s->add("costgeneration", c->costgeneration); + } + if (!Utils::isZero(c->marginalCost)) + { + s->add("marginal-cost", Utils::round(c->marginalCost, 3)); + } + if (!Utils::isZero(c->spreadCost)) + { + s->add("spread-cost", c->spreadCost); + } + if (!Utils::isZero(c->fixedCost)) + { + s->add("fixed-cost", Utils::round(c->fixedCost, 3)); + } + if (!Utils::isZero(c->startupCost)) + { + s->add("startup-cost", Utils::round(c->startupCost, 3)); + } + if (!Utils::isZero(c->marketBidCost)) + { + s->add("market-bid-cost", Utils::round(c->marketBidCost, 3)); + } + if (!Utils::isZero(c->variableomcost)) + { + s->add("variableomcost", Utils::round(c->variableomcost, 3)); + } + + // pollutant factor + for (const auto& [key, val]: Pollutant::namesToEnum) + { + s->add(key, c->emissions.factors[val]); + } + + buffer.clear() << folder << SEP << ".." << SEP << ".." << SEP << "prepro" << SEP + << c->parentArea->id << SEP << c->id(); + if (IO::Directory::Create(buffer)) + { + buffer.clear() << folder << SEP << ".." << SEP << ".." << SEP << "prepro" << SEP + << c->parentArea->id << SEP << c->id() << SEP << "modulation.txt"; + + ret = c->modulation.saveToCSVFile(buffer) && ret; + } + else + { + ret = false; + } } - return true; + // Write the ini file + buffer.clear() << folder << SEP << "list.ini"; + ret = ini.save(buffer) && ret; + + return ret; } bool ThermalClusterList::savePreproToFolder(const AnyString& folder) const { - if (empty()) - return true; - Clob buffer; bool ret = true; - each([&](const ThermalCluster& c) { - if (c.prepro) + for (auto& c: allClusters_) + { + if (c->prepro) { - assert(c.parentArea and "cluster: invalid parent area"); - buffer.clear() << folder << SEP << c.parentArea->id << SEP << c.id(); - ret = c.prepro->saveToFolder(buffer) and ret; + assert(c->parentArea && "cluster: invalid parent area"); + buffer.clear() << folder << SEP << c->parentArea->id << SEP << c->id(); + ret = c->prepro->saveToFolder(buffer) && ret; } - }); + } return ret; } bool ThermalClusterList::saveEconomicCosts(const AnyString& folder) const { - if (empty()) - return true; - Clob buffer; bool ret = true; - each([&](const ThermalCluster& c) { - assert(c.parentArea and "cluster: invalid parent area"); - buffer.clear() << folder << SEP << c.parentArea->id << SEP << c.id(); - ret = c.ecoInput.saveToFolder(buffer) && ret; - }); + for (auto& c: allClusters_) + { + assert(c->parentArea && "cluster: invalid parent area"); + buffer.clear() << folder << SEP << c->parentArea->id << SEP << c->id(); + ret = c->ecoInput.saveToFolder(buffer) && ret; + } return ret; } -bool ThermalClusterList::loadPreproFromFolder(Study& study, - const StudyLoadOptions& options, - const AnyString& folder) +bool ThermalClusterList::loadPreproFromFolder(Study& study, const AnyString& folder) { - if (empty()) - return true; - - const bool globalThermalTSgeneration - = study.parameters.timeSeriesToGenerate & timeSeriesThermal; - Clob buffer; - bool ret = true; + auto hasPrepro = [](auto c) { return (bool)c->prepro; }; - for (auto& [name, c] : cluster) + auto loadPrepro = [&buffer, &folder, &study](auto& c) { - if (c->prepro) - { - assert(c->parentArea and "cluster: invalid parent area"); - buffer.clear() << folder << SEP << c->parentArea->id << SEP << c->id(); + assert(c->parentArea && "cluster: invalid parent area"); + buffer.clear() << folder << SEP << c->parentArea->id << SEP << c->id(); - bool result = c->prepro->loadFromFolder(study, buffer); + return c->prepro->loadFromFolder(study, buffer); + }; - if (result && study.usedByTheSolver && c->doWeGenerateTS(globalThermalTSgeneration)) - { - // checking NPO max - result = c->prepro->normalizeAndCheckNPO(); - } - - ret = result and ret; - } - - ++options.progressTicks; - options.pushProgressLogs(); - } - return ret; + return std::ranges::all_of(allClusters_ | std::views::filter(hasPrepro), loadPrepro); } - -bool ThermalClusterList::loadEconomicCosts(Study& study, const AnyString& folder) +bool ThermalClusterList::validatePrepro(const Study& study) { - if (empty()) - return true; + auto hasPrepro = [](auto c) { return (bool)c->prepro; }; - Clob buffer; - bool ret = true; + const bool globalThermalTSgeneration = study.parameters.timeSeriesToGenerate + & timeSeriesThermal; - for (auto& [name, c] : cluster) + if (!study.usedByTheSolver) { - assert(c->parentArea and "cluster: invalid parent area"); - buffer.clear() << folder << SEP << c->parentArea->id << SEP << c->id(); + return true; + } - bool result = c->ecoInput.loadFromFolder(study, buffer); - c->ComputeCostTimeSeries(); + return std::ranges::all_of(allClusters_ | std::views::filter(hasPrepro), + [&globalThermalTSgeneration](auto& c) + { + if (globalThermalTSgeneration && !c->prepro->validate()) + { + return false; + } + + if (c->doWeGenerateTS(globalThermalTSgeneration)) + { + return c->prepro->normalizeAndCheckNPO(); + } + return true; + }); +} - ret = result && ret; - } - return ret; +bool ThermalClusterList::loadEconomicCosts(Study& study, const AnyString& folder) +{ + return std::ranges::all_of(allClusters_, + [&study, folder](const auto& c) + { + assert(c->parentArea && "cluster: invalid parent area"); + Clob buffer; + buffer.clear() + << folder << SEP << c->parentArea->id << SEP << c->id(); + + bool result = c->ecoInput.loadFromFolder(study, buffer); + c->ComputeCostTimeSeries(); + return result; + }); } } // namespace Data diff --git a/src/libs/antares/study/parts/thermal/cluster_list.h b/src/libs/antares/study/parts/thermal/cluster_list.h deleted file mode 100644 index 1d15b028a9..0000000000 --- a/src/libs/antares/study/parts/thermal/cluster_list.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once - -#include "../common/cluster_list.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief List of clusters -** \ingroup thermalclusters -*/ -class ThermalClusterList : public ClusterList -{ -public: - // Overriden pure virtual methods - YString typeID() const override; - - /*! - ** \brief Get the size (bytes) occupied in memory by a `ThermalClusterList` structure - ** \return A size (in bytes) - */ - bool loadFromFolder(Study& s, const AnyString& folder, Area* area); - - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - ThermalClusterList(); - /*! - ** \brief Destructor - */ - virtual ~ThermalClusterList(); - //@} - - //! \name Spinning - //@{ - /*! - ** \brief Calculation of Spinning for all thermal clusters - */ - void calculationOfSpinning(); - - /*! - ** \brief Calculation of Spinning for all thermal clusters (reverse) - */ - void reverseCalculationOfSpinning(); - //@} - - //! \name Mustrun - //@{ - /*! - ** \brief Enable the 'mustrun' mode for every cluster - ** - ** This method is especially useful for the adequacy mode, where all clusters - ** must be in mustrun mode - */ - void enableMustrunForEveryone(); - //@} - - bool remove(const ClusterName& id) override; - - Map mapping; - - /*! - ** \brief Ensure data for the prepro are initialized - ** \ingroup thermalclusters - ** - ** \todo Remaining of old C-library. this routine should be moved into the appropriate class - ** \param l The list of thermal clusters - */ - void ensureDataPrepro(); - - /*! - ** \brief Load data related to the preprocessor from a list of thermal clusters from a folder - ** \ingroup thermalclusters - ** - ** \todo Remaining of old C-library. this routine should be moved into the appropriate class - ** \param l A list of thermal clusters - ** \param folder The target folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool loadPreproFromFolder(Study& s, const StudyLoadOptions& options, const AnyString& folder); - - bool loadEconomicCosts(Study& s, const AnyString& folder); - - bool savePreproToFolder(const AnyString& folder) const; - bool saveEconomicCosts(const AnyString& folder) const; - - bool saveToFolder(const AnyString& folder) const override; -}; // class ThermalClusterList -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/parts/thermal/container.cpp b/src/libs/antares/study/parts/thermal/container.cpp index 55cebd6440..2d6c878a72 100644 --- a/src/libs/antares/study/parts/thermal/container.cpp +++ b/src/libs/antares/study/parts/thermal/container.cpp @@ -1,38 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include "../../study.h" -#include "container.h" -#include +#include "antares/study/parts/thermal/container.h" #include #include +#include + +#include +#include "antares/study/study.h" + using namespace Yuni; using namespace Antares; @@ -40,9 +36,10 @@ namespace Antares { namespace Data { -using NamedCluster = std::pair; -PartThermal::PartThermal() : unsuppliedEnergyCost(0.), spilledEnergyCost(0.) +PartThermal::PartThermal(): + unsuppliedEnergyCost(0.), + spilledEnergyCost(0.) { } @@ -50,116 +47,12 @@ bool PartThermal::forceReload(bool reload) const { bool ret = true; ret = list.forceReload(reload) && ret; - ret = mustrunList.forceReload(reload) && ret; return ret; } void PartThermal::markAsModified() const { list.markAsModified(); - mustrunList.markAsModified(); -} - -PartThermal::~PartThermal() -{ -} - -void PartThermal::prepareAreaWideIndexes() -{ - // Copy the list with all thermal clusters - // And init the areaWideIndex (unique index for a given area) - if (list.empty()) - { - clusters.clear(); - return; - } - - clusters.assign(list.size(), nullptr); - - auto end = list.end(); - uint idx = 0; - for (auto i = list.begin(); i != end; ++i) - { - ThermalCluster* t = i->second.get(); - t->areaWideIndex = idx; - clusters[idx] = t; - ++idx; - } -} - -uint PartThermal::prepareClustersInMustRunMode() -{ - // nothing to do if there is no cluster available - if (list.empty()) - return 0; - - // the number of clusters in 'must-run' mode - uint count = 0; - bool mustContinue; - do - { - mustContinue = false; - auto end = list.end(); - for (auto i = list.begin(); i != end; ++i) - { - if ((i->second)->mustrun) - { - // Detaching the thermal cluster from the main list... - std::shared_ptr cluster = list.detach(i); - if (!cluster->enabled) - continue; - // ...and attaching it into the second list - if (!mustrunList.add(cluster)) - { - logs.error() << "Impossible to prepare the thermal cluster in 'must-run' mode: " - << cluster->parentArea->name << "::" << cluster->name(); - } - else - { - ++count; - logs.info() << "enabling 'must-run' mode for the cluster " - << cluster->parentArea->name << "::" << cluster->name(); - } - - // the iterator has been invalidated, loop again - mustContinue = true; - break; - } - } - } while (mustContinue); - - // if some thermal cluster has been moved, we must rebuild all the indexes - if (count) - { - list.rebuildIndex(); - mustrunList.rebuildIndex(); - } - - return count; -} - -uint PartThermal::removeDisabledClusters() -{ - // nothing to do if there is no cluster available - if (list.empty()) - return 0; - - std::vector disabledClusters; - - for (auto& it : list) - { - if (!it.second->enabled) - disabledClusters.push_back(it.first); - } - - for (const auto& cluster : disabledClusters) - list.remove(cluster); - - const auto count = disabledClusters.size(); - if (count) - list.rebuildIndex(); - - return count; } void PartThermal::reset() @@ -167,31 +60,33 @@ void PartThermal::reset() unsuppliedEnergyCost = 0.; spilledEnergyCost = 0.; - mustrunList.clear(); - list.clear(); - clusters.clear(); + list.clearAll(); +} + +void PartThermal::resizeAllTimeseriesNumbers(uint n) const +{ + list.resizeAllTimeseriesNumbers(n); } bool PartThermal::hasForcedTimeseriesGeneration() const { using Behavior = LocalTSGenerationBehavior; - return std::any_of(list.begin(), list.end(), [](const NamedCluster& namedCluster) { - return namedCluster.second->tsGenBehavior == Behavior::forceGen; - }); + return std::ranges::any_of(list.all(), + [](const ThermalClusterList::SharedPtr& cluster) + { return cluster->tsGenBehavior == Behavior::forceGen; }); } bool PartThermal::hasForcedNoTimeseriesGeneration() const { using Behavior = LocalTSGenerationBehavior; - return std::any_of(list.begin(), list.end(), [](const NamedCluster& namedCluster) { - return namedCluster.second->tsGenBehavior == Behavior::forceNoGen; - }); + return std::ranges::any_of(list.all(), + [](const ThermalClusterList::SharedPtr& cluster) + { return cluster->tsGenBehavior == Behavior::forceNoGen; }); } -void PartThermal::checkAndCorrectAvailability() +void PartThermal::checkAndCorrectAvailability() const { - std::for_each( - clusters.begin(), clusters.end(), std::mem_fn(&ThermalCluster::checkAndCorrectAvailability)); + std::ranges::for_each(list.each_enabled(), &ThermalCluster::checkAndCorrectAvailability); } } // namespace Data diff --git a/src/libs/antares/study/parts/thermal/container.h b/src/libs/antares/study/parts/thermal/container.h deleted file mode 100644 index 0c860abe53..0000000000 --- a/src/libs/antares/study/parts/thermal/container.h +++ /dev/null @@ -1,157 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_H__ - -#include -#include "cluster_list.h" - -namespace Antares -{ -namespace Data -{ -class PartThermal -{ -public: - //! \name Constructor - //@{ - /*! - ** \brief Default constructor - */ - PartThermal(); - //! Destructor - ~PartThermal(); - //@} - - /*! - ** \brief Reset internal data - */ - void reset(); - - /*! - ** \brief Resize all matrices dedicated to the sampled timeseries numbers - ** - ** \param n A number of years - */ - void resizeAllTimeseriesNumbers(uint n); - - - - /*! - ** \brief Create and initialize the list of all clusters (with the mustrun flag or not) - ** - ** This method must be called before prepareClustersInMustRunMode() - ** to ensure the same order whatever the value of the 'mustrun' flag is. - */ - void prepareAreaWideIndexes(); - - /*! - ** \brief Prepare all thermal clusters in the 'mustrun' mode - ** - ** All clusters with the flag will be moved to the container 'mustrunList'. - ** As a consequence, they will no longer be seen as thermal clusters - ** from the solver's point of view. - ** \warning This method should only be used from the solver - ** - ** \return The number of clusters found in 'must-run' mode - */ - uint prepareClustersInMustRunMode(); - - /*! - ** \brief Removes disabled thermal clusters - ** - ** All clusters with the flag 'enabled' turned to false will be removed from 'list'. - ** As a consequence, they will no longer be seen as thermal clusters - ** from the solver's point of view. - ** \warning This method should only be used from the solver - ** - ** \return The number of disabled clusters found - */ - uint removeDisabledClusters(); - - /*! - ** \brief Invalidate all JIT data - */ - bool forceReload(bool reload) const; - - /*! - ** \brief Mark the thermal cluster as modified - */ - void markAsModified() const; - - /*! - ** \brief Some clusters force the generation of timeseries, - overriding the global (study) parameter. - */ - bool hasForcedTimeseriesGeneration() const; - - /*! - ** \brief Some clusters prevent the generation of timeseries, - overriding the global (study) parameter. - */ - bool hasForcedNoTimeseriesGeneration() const; - - // Check & correct availability timeseries for thermal availability - // Only applies if time-series are ready-made - void checkAndCorrectAvailability(); - -public: - //! The unsupplied energy cost (Euros/MWh) - double unsuppliedEnergyCost; - //! The spilled energy cost - double spilledEnergyCost; - - //! List of all thermal clusters (enabled and disabled) except must-run clusters - ThermalClusterList list; - //! List of all thermal clusters in 'must-run' mode - //! \warning This list must only be used from the solver - ThermalClusterList mustrunList; - - /*! - ** \brief All clusters for the area - ** - ** This variable is only available at runtime from the solver. - ** It is initialized in the same time that the runtime data. - ** - ** This list is mainly used to ensure the same order of the - ** thermal clusters in the outputs. - */ - std::vector clusters; - - // Return unit count - inline size_t clusterCount() const - { - return clusters.size(); - } -}; // class PartThermal - -} // namespace Data -} // namespace Antares - -#include "container.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_H__ */ diff --git a/src/libs/antares/study/parts/thermal/container.hxx b/src/libs/antares/study/parts/thermal/container.hxx deleted file mode 100644 index f4fc746f50..0000000000 --- a/src/libs/antares/study/parts/thermal/container.hxx +++ /dev/null @@ -1,43 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_HXX__ - -namespace Antares -{ -namespace Data -{ -inline void PartThermal::resizeAllTimeseriesNumbers(uint n) -{ - list.resizeAllTimeseriesNumbers(n); - mustrunList.resizeAllTimeseriesNumbers(n); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_CONTAINER_HXX__ diff --git a/src/libs/antares/study/parts/thermal/defines.h b/src/libs/antares/study/parts/thermal/defines.h deleted file mode 100644 index 8a1714b8f0..0000000000 --- a/src/libs/antares/study/parts/thermal/defines.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_DEFINES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_DEFINES_H__ - -namespace Antares -{ -namespace Data -{ -// Forward declaration -class ThermalCluster; -class ThermalClusterList; -class PreproThermal; - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_DEFINES_H__ diff --git a/src/libs/antares/study/parts/thermal/ecoInput.cpp b/src/libs/antares/study/parts/thermal/ecoInput.cpp index d8cfc20621..30904256cd 100644 --- a/src/libs/antares/study/parts/thermal/ecoInput.cpp +++ b/src/libs/antares/study/parts/thermal/ecoInput.cpp @@ -1,40 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/thermal/ecoInput.h" + +#include + #include -#include -#include #include -#include "../../study.h" -#include "ecoInput.h" +#include +#include + #include +#include "antares/study/study.h" using namespace Yuni; +namespace fs = std::filesystem; + #define SEP IO::Separator namespace Antares::Data @@ -64,30 +64,42 @@ bool EconomicInputData::saveToFolder(const AnyString& folder) const return false; } -bool EconomicInputData::loadFromFolder(Study& study, const AnyString& folder) +bool EconomicInputData::loadFromFolder(Study& study, const std::string& folder) { bool ret = true; - if (study.header.version >= 870) + if (study.header.version >= StudyVersion(8, 7)) { - YString filename; Yuni::Clob dataBuffer; - filename << folder << SEP << "fuelCost.txt"; - if (IO::File::Exists(filename)) + fs::path filename = fs::path(folder) / "fuelCost.txt"; + if (fs::exists(filename)) { - ret = fuelcost.loadFromCSVFile(filename, 1, HOURS_PER_YEAR, Matrix<>::optImmediate, &dataBuffer) && ret; + ret = fuelcost.loadFromCSVFile(filename.string(), + 1, + HOURS_PER_YEAR, + Matrix<>::optImmediate, + &dataBuffer) + && ret; if (study.usedByTheSolver && study.parameters.derated) + { fuelcost.averageTimeseries(); + } } - filename.clear() << folder << SEP << "CO2Cost.txt"; - if (IO::File::Exists(filename)) + filename = fs::path(folder) / "CO2Cost.txt"; + if (fs::exists(filename)) { - ret = co2cost.loadFromCSVFile(filename, 1, HOURS_PER_YEAR, Matrix<>::optImmediate, &dataBuffer) + ret = co2cost.loadFromCSVFile(filename.string(), + 1, + HOURS_PER_YEAR, + Matrix<>::optImmediate, + &dataBuffer) && ret; if (study.usedByTheSolver && study.parameters.derated) + { co2cost.averageTimeseries(); + } } } diff --git a/src/libs/antares/study/parts/thermal/ecoInput.h b/src/libs/antares/study/parts/thermal/ecoInput.h deleted file mode 100644 index b275227200..0000000000 --- a/src/libs/antares/study/parts/thermal/ecoInput.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_ECOINPUT_H__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_ECOINPUT_H__ - -#include "cluster.h" -#include -#include "defines.h" -#include "../../fwd.h" -#include - -namespace Antares::Data -{ -/*! -** \brief Thermal -*/ -class EconomicInputData -{ -public: - //! \name Constructor - //@{ - /*! - ** \brief Default constructor - */ - explicit EconomicInputData(); - //@} - - bool forceReload(bool reload) const; - - void markAsModified() const; - - - - /*! - ** \brief Reset all values to their default ones - */ - void reset(); - - //! Copy data from another struct - void copyFrom(const EconomicInputData& rhs); - - /*! - ** \brief Load settings for the thermal prepro from a folder - ** - ** \param folder The source folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool loadFromFolder(Study& study, const AnyString& folder); - - /*! - ** \brief Save settings used by the thermal prepro to a folder - ** - ** \param folder The targer folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool saveToFolder(const AnyString& folder) const; - - /*! - ** \brief Get the amount of memory used by the class - */ - uint64_t memoryUsage() const; - - //! All {FO,PO}{Duration,Rate} annual values - // max x DAYS_PER_YEAR - Matrix fuelcost; - Matrix co2cost; - -}; // class EconomicInputData - -} // namespace Antares::Data -#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_ECOINPUT_H__ diff --git a/src/libs/antares/study/parts/thermal/pollutant.cpp b/src/libs/antares/study/parts/thermal/pollutant.cpp index 416a016e05..fff9e92ca2 100644 --- a/src/libs/antares/study/parts/thermal/pollutant.cpp +++ b/src/libs/antares/study/parts/thermal/pollutant.cpp @@ -1,72 +1,63 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "pollutant.h" +#include "antares/study/parts/thermal/pollutant.h" namespace Antares::Data { -const std::map Pollutant::pollutantNamesOutputVariables = -{ - {CO2, "CO2 EMIS."}, - {NH3, "NH3 EMIS."}, - {SO2, "SO2 EMIS."}, - {NOX, "NOX EMIS."}, - {PM2_5, "PM2_5 EMIS."}, - {PM5, "PM5 EMIS."}, - {PM10, "PM10 EMIS."}, - {NMVOC, "NMVOC EMIS."}, - {OP1, "OP1 EMIS."}, - {OP2, "OP2 EMIS."}, - {OP3, "OP3 EMIS."}, - {OP4, "OP4 EMIS."}, - {OP5, "OP5 EMIS."} -}; +const std::map + Pollutant::pollutantNamesOutputVariables = {{CO2, "CO2 EMIS."}, + {NH3, "NH3 EMIS."}, + {SO2, "SO2 EMIS."}, + {NOX, "NOX EMIS."}, + {PM2_5, "PM2_5 EMIS."}, + {PM5, "PM5 EMIS."}, + {PM10, "PM10 EMIS."}, + {NMVOC, "NMVOC EMIS."}, + {OP1, "OP1 EMIS."}, + {OP2, "OP2 EMIS."}, + {OP3, "OP3 EMIS."}, + {OP4, "OP4 EMIS."}, + {OP5, "OP5 EMIS."}}; const std::string& Pollutant::getPollutantName(int index) { return pollutantNamesOutputVariables.at(PollutantEnum(index)); } -const std::map Pollutant::namesToEnum = -{ - {"co2", CO2}, - {"nh3", NH3}, - {"so2", SO2}, - {"nox", NOX}, - {"pm2_5", PM2_5}, - {"pm5", PM5}, - {"pm10", PM10}, - {"nmvoc", NMVOC}, - {"op1", OP1}, - {"op2", OP2}, - {"op3", OP3}, - {"op4", OP4}, - {"op5", OP5} -}; +const std::map Pollutant::namesToEnum = {{"co2", CO2}, + {"nh3", NH3}, + {"so2", SO2}, + {"nox", NOX}, + {"pm2_5", + PM2_5}, + {"pm5", PM5}, + {"pm10", PM10}, + {"nmvoc", + NMVOC}, + {"op1", OP1}, + {"op2", OP2}, + {"op3", OP3}, + {"op4", OP4}, + {"op5", OP5}}; -} //namespace Antares::Data +} // namespace Antares::Data diff --git a/src/libs/antares/study/parts/thermal/pollutant.h b/src/libs/antares/study/parts/thermal/pollutant.h deleted file mode 100644 index 118c828bb4..0000000000 --- a/src/libs/antares/study/parts/thermal/pollutant.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_POLLUTANT_H__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_POLLUTANT_H__ - -#include -#include -#include - -namespace Antares::Data -{ - -class Pollutant -{ -public: - enum PollutantEnum - { - CO2 = 0, - NH3, - SO2, - NOX, - PM2_5, - PM5, - PM10, - NMVOC, - OP1, - OP2, - OP3, - OP4, - OP5, - POLLUTANT_MAX - }; - - static const std::map pollutantNamesOutputVariables; - static const std::string& getPollutantName(int index); - - static const std::map namesToEnum; - - std::array factors{0}; - -}; //class Pollutant - -} //namespace Antares::Data - -#endif /* __ANTARES_LIBS_STUDY_PARTS_THERMAL_POLLUTANT_H__ */ diff --git a/src/libs/antares/study/parts/thermal/prepro.cpp b/src/libs/antares/study/parts/thermal/prepro.cpp deleted file mode 100644 index d4cb3b654b..0000000000 --- a/src/libs/antares/study/parts/thermal/prepro.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include -#include -#include "../../study.h" -#include "prepro.h" -#include - -using namespace Yuni; - -#define SEP IO::Separator - -namespace Antares -{ -namespace Data -{ -PreproThermal::PreproThermal(std::weak_ptr cluster) : - itsThermalCluster(cluster) -{ -} - -void PreproThermal::copyFrom(const PreproThermal& rhs) -{ - itsThermalCluster = rhs.itsThermalCluster; - data = rhs.data; - rhs.data.unloadFromMemory(); -} - -bool PreproThermal::saveToFolder(const AnyString& folder) -{ - if (IO::Directory::Create(folder)) - { - String buffer; - buffer.clear() << folder << SEP << "data.txt"; - return data.saveToCSVFile(buffer, /*decimal*/ 6); - } - return false; -} - -bool PreproThermal::loadFromFolder(Study& study, const AnyString& folder) -{ - bool ret = true; - auto& buffer = study.bufferLoadingTS; - - auto cluster = itsThermalCluster.lock(); - if (!cluster) - return false; - - auto parentArea = cluster->parentArea; - - buffer.clear() << folder << SEP << "data.txt"; - - // standard loading - ret = data.loadFromCSVFile( - buffer, thermalPreproMax, DAYS_PER_YEAR, Matrix<>::optFixedSize, &study.dataBuffer) - and ret; - - bool thermalTSglobalGeneration = study.parameters.isTSGeneratedByPrepro(timeSeriesThermal); - if (study.usedByTheSolver && cluster->doWeGenerateTS(thermalTSglobalGeneration)) - { - auto& colFoRate = data[foRate]; - auto& colPoRate = data[poRate]; - auto& colFoDuration = data[foDuration]; - auto& colPoDuration = data[poDuration]; - auto& colNPOMin = data[npoMin]; - auto& colNPOMax = data[npoMax]; - uint errors = 0; - - for (uint i = 0; i != DAYS_PER_YEAR; ++i) - { - double foRate = colFoRate[i]; - double poRate = colPoRate[i]; - double foDuration = colFoDuration[i]; - double poDuration = colPoDuration[i]; - double cNPOMin = colNPOMin[i]; - double cNPOMax = colNPOMax[i]; - - if (cNPOMin < 0) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": NPO min can not be negative (line:" << (i + 1) << ")"; - ++errors; - } - if (cNPOMax < 0) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": NPO max can not be negative (line:" << (i + 1) << ")"; - ++errors; - } - if (cNPOMin > cNPOMax) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": NPO max must be greater or equal to NPO min (line:" << (i + 1) - << ")"; - ++errors; - } - - if (foRate < 0. or foRate > 1.) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": invalid value for FO rate (line:" << (i + 1) << ")"; - ++errors; - } - - if (poRate < 0. or poRate > 1.) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": invalid value for PO rate (line:" << (i + 1) << ")"; - ++errors; - } - - if (foDuration < 1. or foDuration > 365.) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": invalid value for FO Duration (line:" << (i + 1) << ")"; - ++errors; - } - if (poDuration < 1. or poDuration > 365.) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": invalid value for PO Duration (line:" << (i + 1) << ")"; - ++errors; - } - - if (errors > 30) - { - logs.error() << "Thermal: Prepro: " << parentArea->id << '/' << cluster->id() - << ": too many errors. skipping"; - break; - } - } - } - - return ret; -} - -bool PreproThermal::forceReload(bool reload) const -{ - return data.forceReload(reload); -} - -void PreproThermal::markAsModified() const -{ - data.markAsModified(); -} - -void PreproThermal::reset() -{ - data.reset(thermalPreproMax, DAYS_PER_YEAR, true); - - auto& colFoDuration = data[foDuration]; - auto& colPoDuration = data[poDuration]; - - for (uint i = 0; i != DAYS_PER_YEAR; ++i) - { - colFoDuration[i] = 1.; - colPoDuration[i] = 1.; - } -} - -bool PreproThermal::normalizeAndCheckNPO() -{ - auto cluster = itsThermalCluster.lock(); - if (!cluster) - return false; - - auto parentArea = cluster->parentArea; - - // alias to our data columns - auto& columnNPOMax = data[npoMax]; - auto& columnNPOMin = data[npoMin]; - // errors management - uint errors = 0; - enum - { - maxErrors = 10 - }; - // Flag to determine whether the column NPO max has been normalized or not - bool normalized = false; - - for (uint y = 0; y != data.height; ++y) - { - if (columnNPOMax[y] > cluster->unitCount) - { - columnNPOMax[y] = cluster->unitCount; - normalized = true; - } - - if (columnNPOMin[y] > columnNPOMax[y]) - { - if (++errors < maxErrors) - { - logs.error() << cluster->id() << " in area " << cluster->parentArea->id - << ": NPO min can not be greater than NPO max (hour: " << (y + 1) - << ", npo-min: " << columnNPOMin[y] << ", npo-max: " << columnNPOMax[y] - << ')'; - } - } - } - - if (errors >= maxErrors) - logs.error() << cluster->id() << " in area " << parentArea->id - << ": too many errors. skipping (total: " << errors << ')'; - - if (normalized) - logs.info() << " NPO max for the thermal cluster '" << parentArea->id - << "' has been normalized"; - - data.markAsModified(); - return (0 == errors); -} - -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/parts/thermal/prepro.h b/src/libs/antares/study/parts/thermal/prepro.h deleted file mode 100644 index ba38601806..0000000000 --- a/src/libs/antares/study/parts/thermal/prepro.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_H__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_H__ - -#include "cluster.h" -#include -#include "defines.h" -#include "../../fwd.h" -#include - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Thermal -*/ -class PreproThermal -{ -public: - enum - { - //! FO Duration (Forced outage Duration - Duree moyenne d'indisponibilite fortuite) - foDuration = 0, - //! PO Duration (Planned outage Duration - Duree moyenne d'indisponibilite programmee) - poDuration, - //! FO Rate (Forced outage Rate - Taux moyen d'indisponibilite fortuite) - foRate, - //! PO Rate (Planned outage Rate - Taux moyen d'indisponibilite programmee) - poRate, - //! NPO min (nombre minimal de groupes en maintenance) - npoMin, - //! NPO max (nombre maximal de groupes en maintenance) - npoMax, - // max - thermalPreproMax, - }; - -public: - //! \name Constructor - //@{ - /*! - ** \brief Default constructor - */ - explicit PreproThermal(std::weak_ptr cluster); - //@} - - bool forceReload(bool reload) const; - - void markAsModified() const; - - - - /*! - ** \brief Reset all values to their default ones - */ - void reset(); - - //! Copy data from another struct - void copyFrom(const PreproThermal& rhs); - - /*! - ** \brief Load settings for the thermal prepro from a folder - ** - ** \param folder The source folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool loadFromFolder(Study& study, const AnyString& folder); - - /*! - ** \brief Save settings used by the thermal prepro to a folder - ** - ** \param folder The targer folder - ** \return A non-zero value if the operation succeeded, 0 otherwise - */ - bool saveToFolder(const AnyString& folder); - - /*! - ** \brief Get the amount of memory used by the class - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Normalize NPO max and check for consistency - ** - ** This method should only be used by the solver - */ - bool normalizeAndCheckNPO(); - - //! All {FO,PO}{Duration,Rate} annual values - // max x DAYS_PER_YEAR - Matrix<> data; - // Parent thermal cluster - std::weak_ptr itsThermalCluster; -}; // class PreproThermal - -} // namespace Data -} // namespace Antares - -#include "prepro.hxx" - -#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_HXX__ diff --git a/src/libs/antares/study/parts/thermal/prepro.hxx b/src/libs/antares/study/parts/thermal/prepro.hxx deleted file mode 100644 index 973075ee8d..0000000000 --- a/src/libs/antares/study/parts/thermal/prepro.hxx +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_HXX__ - -namespace Antares -{ -namespace Data -{ -inline uint64_t PreproThermal::memoryUsage() const -{ - return sizeof(PreproThermal); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_HXX__ diff --git a/src/libs/antares/study/parts/wind/container.cpp b/src/libs/antares/study/parts/wind/container.cpp index c25ce757d8..eff23dff6f 100644 --- a/src/libs/antares/study/parts/wind/container.cpp +++ b/src/libs/antares/study/parts/wind/container.cpp @@ -1,84 +1,77 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/wind/container.h" + #include -#include "../../study.h" -#include "container.h" + +#include "antares/study/study.h" using namespace Yuni; -namespace Antares -{ -namespace Data -{ -namespace Wind +namespace Antares::Data::Wind { -Container::Container() : prepro(nullptr), series(nullptr) +Container::Container(): + prepro(nullptr), + series(tsNumbers) { } Container::~Container() { delete prepro; - delete series; } bool Container::forceReload(bool reload) const { bool ret = true; - if (series) - ret = series->forceReload(reload) and ret; + ret = series.forceReload(reload) && ret; if (prepro) - ret = prepro->forceReload(reload) and ret; + { + ret = prepro->forceReload(reload) && ret; + } return ret; } void Container::markAsModified() const { - if (series) - series->markAsModified(); + series.markAsModified(); if (prepro) + { prepro->markAsModified(); + } } uint64_t Container::memoryUsage() const { - return sizeof(Container) + ((!series) ? 0 : DataSeriesWindMemoryUsage(series)) - + ((!prepro) ? 0 : prepro->memoryUsage()); + return sizeof(Container) + series.memoryUsage() + ((!prepro) ? 0 : prepro->memoryUsage()); } void Container::resetToDefault() { - if (series) - series->timeSeries.reset(1, HOURS_PER_YEAR); + series.reset(); if (prepro) + { prepro->resetToDefault(); + } } -} // namespace Wind -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::Wind diff --git a/src/libs/antares/study/parts/wind/container.h b/src/libs/antares/study/parts/wind/container.h deleted file mode 100644 index 05a696f1d4..0000000000 --- a/src/libs/antares/study/parts/wind/container.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_CONTAINER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_WIND_CONTAINER_H__ - -#include "prepro.h" -#include "series.h" - -namespace Antares -{ -namespace Data -{ -namespace Wind -{ -class Container -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Container(); - //! Destructor - ~Container(); - //@} - - /*! - ** \brief Reset to default values - */ - void resetToDefault(); - - /*! - ** \brief Make sure that all data are loaded - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark all data as modified - */ - void markAsModified() const; - - /*! - ** \brief Get the amount of memory currently used by the class - */ - uint64_t memoryUsage() const; - -public: - //! Data for the pre-processor - Data::Wind::Prepro* prepro; - /*! Data for time-series */ - DataSeriesWind* series; - -}; // class Container - -} // namespace Wind -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_CONTAINER_H__ diff --git a/src/libs/antares/study/parts/wind/prepro.cpp b/src/libs/antares/study/parts/wind/prepro.cpp index 7e0ca5638c..f631a5db81 100644 --- a/src/libs/antares/study/parts/wind/prepro.cpp +++ b/src/libs/antares/study/parts/wind/prepro.cpp @@ -1,48 +1,41 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/parts/wind/prepro.h" + #include -#include "prepro.h" #include -#include "../../study.h" + #include +#include "antares/study/study.h" using namespace Yuni; using namespace Antares; #define SEP IO::Separator -namespace Antares -{ -namespace Data -{ -namespace Wind +namespace Antares::Data::Wind { -Prepro::Prepro() : xcast(timeSeriesWind) +Prepro::Prepro(): + xcast(timeSeriesWind) { } @@ -60,6 +53,4 @@ bool Prepro::saveToFolder(const AnyString& folder) const return xcast.saveToFolder(folder); } -} // namespace Wind -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::Wind diff --git a/src/libs/antares/study/parts/wind/prepro.h b/src/libs/antares/study/parts/wind/prepro.h deleted file mode 100644 index a99ed241b1..0000000000 --- a/src/libs/antares/study/parts/wind/prepro.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ -#define __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ - -#include "../../fwd.h" -#include "../../xcast.h" - -namespace Antares::Data::Wind -{ -/*! -** \brief Prepro Wind -*/ -class Prepro -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - Prepro(); - //! Destructor - ~Prepro(); - //@} - - /*! - ** \brief Try to estimate the amount of memory required by this class for a simulation - */ - - - /*! - ** \brief Load data from a folder - */ - bool loadFromFolder(const AnyString& folder); - - /*! - ** \brief Save data to a folder - */ - bool saveToFolder(const AnyString& folder) const; - - /*! - ** \brief Get the amount of memory currently used - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Make sure that all data are loaded in memory - */ - bool forceReload(bool reload = false) const; - - void markAsModified() const; - - /*! - ** \brief Reset to default all values - */ - void resetToDefault(); - - //! XCast - Data::XCast xcast; - -}; // Prepro - -} // namespace Antares::Data::Wind - - - -#include "prepro.hxx" - -#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ diff --git a/src/libs/antares/study/parts/wind/prepro.hxx b/src/libs/antares/study/parts/wind/prepro.hxx deleted file mode 100644 index c73fcc7537..0000000000 --- a/src/libs/antares/study/parts/wind/prepro.hxx +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_HXX__ - -namespace Antares::Data::Wind -{ - -inline uint64_t Prepro::memoryUsage() const -{ - return xcast.memoryUsage(); -} - -inline bool Prepro::forceReload(bool reload) const -{ - return xcast.forceReload(reload); -} - -inline void Prepro::markAsModified() const -{ - xcast.markAsModified(); -} - -inline void Prepro::resetToDefault() -{ - xcast.resetToDefaultValues(); -} - -} // namespace Antares::Data::Wind - - - -#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_PREPRO_H__ diff --git a/src/libs/antares/study/parts/wind/series.cpp b/src/libs/antares/study/parts/wind/series.cpp deleted file mode 100644 index cf47110941..0000000000 --- a/src/libs/antares/study/parts/wind/series.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include "series.h" -#include "../../study.h" - -using namespace Yuni; - -#define SEP IO::Separator - -namespace Antares -{ -namespace Data -{ -int DataSeriesWindLoadFromFolder(Study& s, - DataSeriesWind* d, - const AreaName& areaID, - const char folder[]) -{ - if (!d) - return 1; - String& buffer = s.bufferLoadingTS; - - int ret = 1; - buffer.clear() << folder << SEP << "wind_" << areaID << '.' << s.inputExtension; - ret = d->timeSeries.loadFromCSVFile(buffer, 1, HOURS_PER_YEAR, &s.dataBuffer) && ret; - - if (s.usedByTheSolver && s.parameters.derated) - d->timeSeries.averageTimeseries(); - - d->timeseriesNumbers.clear(); - - return ret; -} - -int DataSeriesWindSaveToFolder(DataSeriesWind* d, const AreaName& areaID, const char folder[]) -{ - if (!d) - return 1; - - Clob buffer; - int ret = 1; - buffer.clear() << folder << SEP << "wind_" << areaID << ".txt"; - ret = d->timeSeries.saveToCSVFile(buffer, 0) && ret; - - return ret; -} - -double* DataSeriesWind::getColumn(unsigned int year) const -{ - return timeSeries[getIndex(year)]; -} - -double DataSeriesWind::getCoefficient(const unsigned int year, const unsigned int hour) const -{ - return timeSeries[getIndex(year)][hour]; -} - -unsigned int DataSeriesWind::getIndex(unsigned int year) const -{ - return (timeSeries.width != 1) ? timeseriesNumbers[0][year] : 0; -} - -bool DataSeriesWind::forceReload(bool reload) const -{ - return timeSeries.forceReload(reload); -} - -void DataSeriesWind::markAsModified() const -{ - timeSeries.markAsModified(); -} - -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/parts/wind/series.h b/src/libs/antares/study/parts/wind/series.h deleted file mode 100644 index c7f77fc350..0000000000 --- a/src/libs/antares/study/parts/wind/series.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_TIMESERIES_H__ -#define __ANTARES_LIBS_STUDY_PARTS_WIND_TIMESERIES_H__ - -#include -#include "../../fwd.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Data series (Wind) -*/ -class DataSeriesWind -{ -public: - - - bool forceReload(bool reload = false) const; - - void markAsModified() const; - - double* getColumn(unsigned int year) const; - double getCoefficient(const unsigned int year, const unsigned int hour) const; - unsigned int getIndex(unsigned int year) const; - -public: - /*! - ** \brief Time series (MW) - ** - ** Merely a matrix of TimeSeriesCount * 8760 values - */ - Matrix timeSeries; - - /*! - ** \brief Monte-Carlo - */ - Matrix timeseriesNumbers; - -}; /* class DataSeriesWind */ - -/*! -** \brief Load wind data series from a file -** \ingroup windseries -** -** \param d Data series -** \param areaID The ID of the area associated to the data series -** \param folder The source folder -** \return A non-zero value if the operation succeeded, 0 otherwise -*/ -int DataSeriesWindLoadFromFolder(Study& s, - DataSeriesWind* d, - const AreaName& areaID, - const char folder[]); - -/*! -** \brief Save wind data series from a file -** \ingroup windseries -** -** \param d Data series -** \param areaID The ID of the area associated to the data series -** \param folder The target folder -** \return A non-zero value if the operation succeeded, 0 otherwise -*/ -int DataSeriesWindSaveToFolder(DataSeriesWind* d, const AreaName& areaID, const char folder[]); - -/*! -** \brief Get the size (bytes) in memory occupied by a `DataSeriesWind` structure -*/ -uint64_t DataSeriesWindMemoryUsage(DataSeriesWind* w); - -} // namespace Data -} // namespace Antares - -#include "series.hxx" - -#endif /* __ANTARES_LIBS_STUDY_PARTS_WIND_TIMESERIES_H__ */ diff --git a/src/libs/antares/study/parts/wind/series.hxx b/src/libs/antares/study/parts/wind/series.hxx deleted file mode 100644 index f714cbc2e4..0000000000 --- a/src/libs/antares/study/parts/wind/series.hxx +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PARTS_WIND_TIMESERIES_HXX__ -#define __ANTARES_LIBS_STUDY_PARTS_WIND_TIMESERIES_HXX__ - -namespace Antares -{ -namespace Data -{ -inline uint64_t DataSeriesWindMemoryUsage(DataSeriesWind* w) -{ - return (w) ? w->timeSeries.memoryUsage() : 0; -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PARTS_WIND_TIMESERIES_HXX__ diff --git a/src/libs/antares/study/progression/progression.cpp b/src/libs/antares/study/progression/progression.cpp index 49d24facf5..a78c86959f 100644 --- a/src/libs/antares/study/progression/progression.cpp +++ b/src/libs/antares/study/progression/progression.cpp @@ -1,48 +1,43 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "progression.h" -#include "../study.h" +#include "antares/study/progression/progression.h" + #include +#include "antares/study/study.h" using namespace Yuni; -namespace Antares +namespace Antares::Solver { -namespace Solver -{ -Progression::Task::Task(const Antares::Data::Study& study, Section section) : - pProgression(study.progression), pPart(study.progression.begin((uint)-1, section)) +Progression::Task::Task(const Antares::Data::Study& study, Section section): + pProgression(study.progression), + pPart(study.progression.begin((uint)-1, section)) { assert(&pProgression); } -Progression::Task::Task(const Antares::Data::Study& study, uint year, Section section) : - pProgression(study.progression), pPart(study.progression.begin(year, section)) +Progression::Task::Task(const Antares::Data::Study& study, uint year, Section section): + pProgression(study.progression), + pPart(study.progression.begin(year, section)) { assert(&pProgression); } @@ -60,9 +55,13 @@ void Progression::add(uint year, Section section, int nbTicks) // Caption part.caption.clear() << "task 0 " << SectionToCStr(section) << ", "; if (year != (uint)-1) + { part.caption << "year: " << year << ", "; + } else + { part.caption << "post, "; + } } void Progression::end(Part& part) @@ -102,11 +101,15 @@ void Progression::end(Part& part) // Only if started. This variable has no need to be modified because // never modified after the start of the simulation if (pStarted) + { logs.progress() << part.caption << "100"; + } return; } else + { pProgressMeter.mutex.unlock(); + } } bool Progression::Meter::onInterval(uint) @@ -138,13 +141,16 @@ bool Progression::Meter::onInterval(uint) // Print all logs for (uint i = 0; i != count; ++i) + { logs.progress() << logsContainer[i]; + } // True to continue the execution of the timer return true; } -Progression::Progression() : pStarted(false) +Progression::Progression(): + pStarted(false) { } @@ -156,7 +162,7 @@ Progression::~Progression() bool Progression::saveToFile(const Yuni::String& filename, IResultWriter& writer) { Yuni::Clob buffer; - MutexLocker locker(pProgressMeter.mutex); + std::lock_guard locker(pProgressMeter.mutex); { uint year; const Part::Map::const_iterator end = pProgressMeter.parts.end(); @@ -167,9 +173,13 @@ bool Progression::saveToFile(const Yuni::String& filename, IResultWriter& writer for (Part::MapPerSection::const_iterator j = i->second.begin(); j != jend; ++j) { if (year != (uint)-1) + { buffer << year; + } else + { buffer << "post"; + } buffer << ' ' << SectionToCStr(j->first) << '\n'; } } @@ -192,5 +202,4 @@ void Progression::stop() pStarted = false; } -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver diff --git a/src/libs/antares/study/progression/progression.hxx b/src/libs/antares/study/progression/progression.hxx deleted file mode 100644 index 2ae39c82cd..0000000000 --- a/src/libs/antares/study/progression/progression.hxx +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_PROGRESSION_PROGRESSION_HXX__ -#define __ANTARES_LIBS_STUDY_PROGRESSION_PROGRESSION_HXX__ - -namespace Antares -{ -namespace Solver -{ -inline Progression::Meter::Meter() : nbParallelYears(0), logsContainer(nullptr) -{ -} - -inline void Progression::Meter::allocateLogsContainer(uint nb) -{ - logsContainer = new Yuni::CString<256, false>[nb]; -} - -inline void Progression::Meter::taskCount(uint n) -{ - (void)n; -} - -inline void Progression::add(Section section, int nbTicks) -{ - add((uint)-1, section, nbTicks); -} - -inline void Progression::setNumberOfParallelYears(uint nb) -{ - pProgressMeter.nbParallelYears = nb; - pProgressMeter.allocateLogsContainer(nb); -} - -inline Progression::Part& Progression::begin(uint year, Progression::Section section) -{ - // Alias - Part& part = pProgressMeter.parts[year][section]; - // Reset - part.tickCount = 0; - // It is useless to display 0%, so lastTickCount and tickCount can be equals - part.lastTickCount = 0; - pProgressMeter.mutex.lock(); - pProgressMeter.inUse.push_front(&part); - pProgressMeter.mutex.unlock(); - return part; -} - -inline const char* Progression::SectionToCStr(Section section) -{ - static const char* const sectName[sectMax] - = {"mc", "output", "load", "solar", "wind", "hydro", "thermal", "import timeseries"}; - assert((uint)section < (uint)sectMax); - return sectName[section]; -} - -} // namespace Solver -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_PROGRESSION_PROGRESSION_HXX__ diff --git a/src/libs/antares/study/runtime.h b/src/libs/antares/study/runtime.h deleted file mode 100644 index 008b830a86..0000000000 --- a/src/libs/antares/study/runtime.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_ANTARES_STUDY_RUNTIME_H__ -#define __LIBS_ANTARES_STUDY_RUNTIME_H__ - -#include "runtime/runtime.h" - -#endif // __LIBS_ANTARES_STUDY_RUNTIME_H__ diff --git a/src/libs/antares/study/runtime/runtime.cpp b/src/libs/antares/study/runtime/runtime.cpp index 0a8f349847..1bb7e46386 100644 --- a/src/libs/antares/study/runtime/runtime.cpp +++ b/src/libs/antares/study/runtime/runtime.cpp @@ -1,34 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "runtime.h" -#include "antares/fatal-error.h" +#include "antares/study/runtime/runtime.h" -#include "../area/scratchpad.h" +#include +#include "antares/antares/fatal-error.h" +#include "antares/study/area/scratchpad.h" using namespace Yuni; @@ -57,7 +52,7 @@ static void StudyRuntimeInfosInitializeAllAreas(Study& study, StudyRuntimeInfos& double nE, nS; for (uint i = 0; i != 12; ++i) { - if (!Math::Zero(e[i])) + if (!Utils::isZero(e[i])) { // E' = ln(e) - 0.5 * ln(1 + (s*s) / (e*e)) // S' = sqrt(ln(1 + (s*s) / (e*e))) @@ -65,9 +60,9 @@ static void StudyRuntimeInfosInitializeAllAreas(Study& study, StudyRuntimeInfos& nS = sqrt(log(1. + (s[i] * s[i]) / (e[i] * e[i]))); // asserts - assert(!Math::NaN(nE) + assert(!std::isnan(nE) && "Hydro: NaN value detected for hydro prepro expectation"); - assert(!Math::NaN(nS) + assert(!std::isnan(nS) && "Hydro: NaN value detected for hydro prepro expectation"); e[i] = nE; @@ -84,19 +79,18 @@ static void StudyRuntimeInfosInitializeAllAreas(Study& study, StudyRuntimeInfos& // Spinning - Economic Only - If no prepro if (!(timeSeriesThermal & study.parameters.timeSeriesToRefresh)) { - // Calculation of the spinning area.thermal.list.calculationOfSpinning(); - // We should not forget the list of clusters in 'must-run' mode - area.thermal.mustrunList.calculationOfSpinning(); } area.scratchpad.reserve(nbYearsInParallel); for (uint numSpace = 0; numSpace < nbYearsInParallel; numSpace++) + { area.scratchpad.emplace_back(r, area); + } // statistics - r.thermalPlantTotalCount += area.thermal.list.size(); - r.thermalPlantTotalCountMustRun += area.thermal.mustrunList.size(); + r.thermalPlantTotalCount += area.thermal.list.enabledAndNotMustRunCount(); + r.thermalPlantTotalCountMustRun += area.thermal.list.enabledAndMustRunCount(); r.shortTermStorageCount += area.shortTermStorage.count(); } @@ -108,19 +102,21 @@ static void StudyRuntimeInfosInitializeAreaLinks(Study& study, StudyRuntimeInfos uint indx = 0; - study.areas.each([&](Data::Area& area) { - area.buildLinksIndexes(); - - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - { - auto* link = i->second; - - r.areaLink[indx] = link; - link->index = indx; - ++indx; - } - }); + study.areas.each( + [&indx, &r](Data::Area& area) + { + area.buildLinksIndexes(); + + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + auto* link = i->second; + + r.areaLink[indx] = link; + link->index = indx; + ++indx; + } + }); } void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimits& limits) @@ -143,12 +139,14 @@ void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimi // We have here too much hours, the interval will be reduced // Log Entry logs.info() << " Partial week detected. Not allowed in " - << StudyModeToCString(study.parameters.mode); + << SimulationModeToCString(study.parameters.mode); logs.info() << " Time interval that has been requested: " << (1 + a) << ".." << (1 + b); // Reducing while (b > a and 0 != ((b - a + 1) % 168)) + { --b; + } } } @@ -177,6 +175,7 @@ void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimi limits.month[rangeCount] = limits.month[rangeEnd] - limits.month[rangeBegin] + 1; // year limits.year[rangeBegin] = 0; + /// reminder to get rangeLimits.year[Data::rangeEnd] limits.year[rangeEnd] = study.parameters.nbYears - 1; limits.year[rangeCount] = study.parameters.effectiveNbYears; @@ -196,11 +195,15 @@ void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimi << ", years:" << (1 + limits.year[rangeBegin]) << ".." << (1 + limits.year[rangeEnd]); if (study.parameters.leapYear) + { logs.info() << "leap year: enabled"; + } // Number of simulation days per month for (uint i = 0; i != 12; ++i) + { simulationDaysPerMonth[i] = 0; + } if (ca.month == cb.month) { simulationDaysPerMonth[(uint)ca.month] = (uint)(cb.dayYear - ca.dayYear + 1); @@ -211,18 +214,21 @@ void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimi } else { - simulationDaysPerMonth[(uint)ca.month] - = study.calendar.months[(uint)ca.month].days - ca.dayMonth; - simulationDaysPerMonth[(uint)cb.month] = cb.dayMonth + 1; + simulationDaysPerMonth[ca.month] = study.calendar.months[ca.month].days - ca.dayMonth; + simulationDaysPerMonth[cb.month] = cb.dayMonth + 1; for (uint i = ca.month + 1; i < cb.month; ++i) + { simulationDaysPerMonth[i] = study.calendar.months[i].days; + } } { CString<50, false> s; for (uint i = 0; i != 12; ++i) { if (i) + { s << ", "; + } s << simulationDaysPerMonth[i]; } logs.info() << "Simulation days per month : " << s; @@ -230,10 +236,14 @@ void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimi // Number of simulation days per week for (uint i = 0; i != 53; ++i) + { simulationDaysPerWeek[i] = 0; + } for (uint d = limits.day[rangeBegin]; d <= limits.day[rangeEnd]; d++) + { simulationDaysPerWeek[study.calendar.days[d].week]++; + } // We make the test on the field 'hour' because the field 'week' might be equals to 0 // (Example: 1 week: from 0 to 0 and it is valid) @@ -245,7 +255,7 @@ void StudyRuntimeInfos::initializeRangeLimits(const Study& study, StudyRangeLimi } } -StudyRuntimeInfos::StudyRuntimeInfos() : +StudyRuntimeInfos::StudyRuntimeInfos(): nbYears(0), thermalPlantTotalCount(0), thermalPlantTotalCountMustRun(0), @@ -259,13 +269,27 @@ void StudyRuntimeInfos::checkThermalTSGeneration(Study& study) bool globalThermalTSgeneration = gd.timeSeriesToGenerate & timeSeriesThermal; thermalTSRefresh = globalThermalTSgeneration; - study.areas.each([this, globalThermalTSgeneration](Data::Area& area) { - area.thermal.list.each( - [this, globalThermalTSgeneration](const Data::ThermalCluster& cluster) { - thermalTSRefresh - = thermalTSRefresh || cluster.doWeGenerateTS(globalThermalTSgeneration); - }); - }); + study.areas.each( + [this, globalThermalTSgeneration](const Data::Area& area) + { + for (const auto& c: area.thermal.list.each_enabled_and_not_mustrun()) + { + thermalTSRefresh = thermalTSRefresh || c->doWeGenerateTS(globalThermalTSgeneration); + } + }); +} + +void StudyRuntimeInfos::initializeRandomNumberGenerators(const Parameters& parameters) +{ + logs.info() << "Initializing random number generators..."; + for (uint i = 0; i != Data::seedMax; ++i) + { +#ifndef NDEBUG + logs.debug() << " random number generator: " << Data::SeedToCString((Data::SeedIndex)i) + << ", seed: " << parameters.seed[i]; +#endif + random[i].reset(parameters.seed[i]); + } } bool StudyRuntimeInfos::loadFromStudy(Study& study) @@ -284,20 +308,20 @@ bool StudyRuntimeInfos::loadFromStudy(Study& study) } else { - study.calendar.reset({gd.dayOfThe1stJanuary, gd.firstWeekday, gd.firstMonthInYear, gd.leapYear}); + study.calendar.reset( + {gd.dayOfThe1stJanuary, gd.firstWeekday, gd.firstMonthInYear, gd.leapYear}); } logs.debug() << " :: generating calendar dedicated to the output"; - study.calendarOutput.reset({gd.dayOfThe1stJanuary, gd.firstWeekday, gd.firstMonthInYear, gd.leapYear}); + study.calendarOutput.reset( + {gd.dayOfThe1stJanuary, gd.firstWeekday, gd.firstMonthInYear, gd.leapYear}); initializeRangeLimits(study, rangeLimits); - // Removing disabled thermal clusters from solver computations - removeDisabledThermalClustersFromSolverComputations(study); + // Removing disabled short-term storage objects from solver computations + removeDisabledShortTermStorageClustersFromSolverComputations(study); switch (gd.renewableGeneration()) { case rgClusters: - // Removing disabled renewable clusters from solver computations - removeDisabledRenewableClustersFromSolverComputations(study); break; case rgAggregated: // Removing all renewable clusters from solver computations @@ -309,9 +333,6 @@ bool StudyRuntimeInfos::loadFromStudy(Study& study) break; } - // Must-run mode - initializeThermalClustersInMustRunMode(study); - // Areas StudyRuntimeInfosInitializeAllAreas(study, *this); @@ -322,7 +343,11 @@ bool StudyRuntimeInfos::loadFromStudy(Study& study) checkThermalTSGeneration(study); if (not gd.geographicTrimming) + { disableAllFilters(study); + } + + initializeRandomNumberGenerators(study.parameters); logs.info(); logs.info() << "Summary"; @@ -331,7 +356,8 @@ bool StudyRuntimeInfos::loadFromStudy(Study& study) logs.info() << " thermal clusters: " << thermalPlantTotalCount; logs.info() << " thermal clusters (must-run): " << thermalPlantTotalCountMustRun; logs.info() << " short-term storages: " << shortTermStorageCount; - logs.info() << " binding constraints: " << study.bindingConstraints.activeContraints().size(); + logs.info() << " binding constraints: " + << study.bindingConstraints.activeConstraints().size(); logs.info() << " geographic trimming:" << (gd.geographicTrimming ? "true" : "false"); logs.info() << " memory : " << ((study.memoryUsage()) / 1024 / 1024) << "Mo"; logs.info(); @@ -344,37 +370,6 @@ uint StudyRuntimeInfos::interconnectionsCount() const return static_cast(areaLink.size()); } -void StudyRuntimeInfos::initializeThermalClustersInMustRunMode(Study& study) const -{ - logs.info(); - logs.info() << "Optimizing the thermal clusters in 'must-run' mode..."; - - // The number of thermal clusters in 'must-run' mode - uint count = 0; - - // each area... - for (uint a = 0; a != study.areas.size(); ++a) - { - Area& area = *(study.areas.byIndex[a]); - area.thermal.prepareAreaWideIndexes(); - count += area.thermal.prepareClustersInMustRunMode(); - } - - switch (count) - { - case 0: - logs.info() << "No thermal cluster in 'must-run' mode"; - break; - case 1: - logs.info() << "Found 1 thermal cluster in 'must-run' mode"; - break; - default: - logs.info() << "Found " << count << " thermal clusters in 'must-run' mode"; - } - // space - logs.info(); -} - static void removeClusters(Study& study, const char* type, std::function eachArea, @@ -407,20 +402,11 @@ static void removeClusters(Study& study, } } -void StudyRuntimeInfos::removeDisabledThermalClustersFromSolverComputations(Study& study) +void StudyRuntimeInfos::removeDisabledShortTermStorageClustersFromSolverComputations(Study& study) { - removeClusters( - study, "thermal", [](Area& area) { return area.thermal.removeDisabledClusters(); }); -} - -void StudyRuntimeInfos::removeDisabledRenewableClustersFromSolverComputations(Study& study) -{ - removeClusters(study, "renewable", [](Area& area) { - uint ret = area.renewable.removeDisabledClusters(); - if (ret > 0) - area.renewable.prepareAreaWideIndexes(); - return ret; - }); + removeClusters(study, + "short term storage", + [](Area& area) { return area.shortTermStorage.removeDisabledClusters(); }); } void StudyRuntimeInfos::removeAllRenewableClustersFromSolverComputations(Study& study) @@ -428,7 +414,8 @@ void StudyRuntimeInfos::removeAllRenewableClustersFromSolverComputations(Study& removeClusters( study, "renewable", - [](Area& area) { + [](Area& area) + { area.renewable.reset(); return 0; }, @@ -443,7 +430,6 @@ StudyRuntimeInfos::~StudyRuntimeInfos() #ifndef NDEBUG void StudyRangeLimits::checkIntegrity() const { - assert(this != nullptr); assert(hour[rangeBegin] <= hour[rangeEnd]); assert(day[rangeBegin] <= day[rangeEnd]); assert(hour[rangeBegin] < 9000); // arbitrary value @@ -455,18 +441,20 @@ void StudyRangeLimits::checkIntegrity() const void StudyRuntimeInfos::disableAllFilters(Study& study) { - study.areas.each([&](Data::Area& area) { - area.filterSynthesis = filterAll; - area.filterYearByYear = filterAll; - - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - { - auto& link = *(i->second); - link.filterSynthesis = filterAll; - link.filterYearByYear = filterAll; - } - }); + study.areas.each( + [](Data::Area& area) + { + area.filterSynthesis = filterAll; + area.filterYearByYear = filterAll; + + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + auto& link = *(i->second); + link.filterSynthesis = filterAll; + link.filterYearByYear = filterAll; + } + }); } -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/runtime/runtime.h b/src/libs/antares/study/runtime/runtime.h deleted file mode 100644 index a499f47483..0000000000 --- a/src/libs/antares/study/runtime/runtime.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_H__ -#define __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_H__ - -#include -#include -#include "../study.h" -#include - -namespace Antares::Data -{ - -enum RangeLimitsIndex -{ - rangeBegin = 0, - rangeEnd, - rangeCount, - rangeMax -}; - -struct StudyRangeLimits -{ -public: - /*! - ** \brief Dynamic bound-checking (debug only) - */ - void checkIntegrity() const; - - //! Hours - uint hour[rangeMax]; - //! Day - uint day[rangeMax]; - //! Week - uint week[rangeMax]; - //! Month - uint month[rangeMax]; - //! Year - uint year[rangeMax]; - -}; // class StudyRangeLimits - -/*! -** \brief Runtime informations -** \ingroup runtimedata -*/ -class StudyRuntimeInfos -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - StudyRuntimeInfos(); - /*! - ** \brief Destructor - */ - ~StudyRuntimeInfos(); - //@} - - /*! - ** \brief Reset internal data according a given study - */ - bool loadFromStudy(Study& study); - -public: - //! The number of years to process - uint nbYears; - - //! Range limits - StudyRangeLimits rangeLimits; - - //! Mode of the simulation - StudyMode mode; - - //! The number of interconnections - uint interconnectionsCount() const; - //! All interconnections - std::vector areaLink; - - //! Random numbers generators - MersenneTwister random[seedMax]; - - //! Total - uint thermalPlantTotalCount; - uint thermalPlantTotalCountMustRun; - - uint shortTermStorageCount = 0; - - //! Override enable/disable TS generation per cluster - bool thermalTSRefresh = false; - - /*! - ** \brief The number of simulation days per month - */ - uint simulationDaysPerMonth[12]; - - /*! - ** \brief The number of simulation days per week - */ - uint simulationDaysPerWeek[53]; - - /*! - ** \brief Flag to know if at least one error occured during the quadratic optimization - ** - ** In this case, error on NaN should be disabled - */ - bool quadraticOptimizationHasFailed; - -private: - void initializeRangeLimits(const Study& study, StudyRangeLimits& limits); - //! Prepare all thermal clusters in 'must-run' mode - void initializeThermalClustersInMustRunMode(Study& study) const; - void removeDisabledThermalClustersFromSolverComputations(Study& study); - void removeDisabledRenewableClustersFromSolverComputations(Study& study); - void removeAllRenewableClustersFromSolverComputations(Study& study); - void disableAllFilters(Study& study); - void checkThermalTSGeneration(Study& study); -}; // struct StudyRuntimeInfos - -} // namespace Antares::Data - -#include "runtime.hxx" - -#endif // __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_H__ diff --git a/src/libs/antares/study/runtime/runtime.hxx b/src/libs/antares/study/runtime/runtime.hxx deleted file mode 100644 index ff76946efe..0000000000 --- a/src/libs/antares/study/runtime/runtime.hxx +++ /dev/null @@ -1,43 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_HXX__ -#define __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_HXX__ - -namespace Antares -{ -namespace Data -{ -#ifdef NDEBUG -inline void StudyRangeLimits::checkIntegrity() const -{ -} -#endif - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_RUNTIME_RUNTIME_INFOS_HXX__ diff --git a/src/libs/antares/study/save.cpp b/src/libs/antares/study/save.cpp index f8dea51ebd..cd6de7d1b3 100644 --- a/src/libs/antares/study/save.cpp +++ b/src/libs/antares/study/save.cpp @@ -1,43 +1,37 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "study.h" -#include -#include "scenario-builder/sets.h" -#include #include +#include + +#include +#include "antares/study/scenario-builder/sets.h" +#include "antares/study/study.h" + using namespace Yuni; #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data { bool Study::resetFolderIcon() const { @@ -46,12 +40,14 @@ bool Study::resetFolderIcon() const buffer.clear() << folder << SEP << "Desktop.ini"; IO::File::Stream file; if (not file.openRW(buffer)) + { return false; + } buffer.clear() << "[.shellclassinfo]\r\n" << "iconfile = settings/resources/study.ico\r\n" << "iconindex = 0\r\n" - << "infotip = Antares Study" << VersionToCStr((Version)header.version) - << ": " << header.caption << "\r\n"; + << "infotip = Antares Study" << header.version.toString() << ": " + << header.caption << "\r\n"; file << buffer; } @@ -60,7 +56,9 @@ bool Study::resetFolderIcon() const // The file should be closed at this point Yuni::WString wbuffer(folder); if (not wbuffer.empty()) + { SetFileAttributesW(wbuffer.c_str(), FILE_ATTRIBUTE_SYSTEM); + } } #endif @@ -70,7 +68,9 @@ bool Study::resetFolderIcon() const bool Study::saveToFolder(const AnyString& newfolder) { if (newfolder.empty()) + { return false; + } logs.notice() << "Exporting the study..."; const String location = newfolder; @@ -134,8 +134,7 @@ bool Study::saveToFolder(const AnyString& newfolder) // In this case, we have to invalidate all matrices to make sure that all // data will be rewritten to avoid data loss // (if filenames have changed for examples) - bool versionUpgrade = ((uint)header.version != (uint)versionLatest); - if (versionUpgrade) + if (header.version != StudyVersion::latest()) { logs.info() << " performing a format upgrade"; // Invalidate all matrices @@ -143,7 +142,9 @@ bool Study::saveToFolder(const AnyString& newfolder) markAsModified(); // Invalidate the scenario builder data if (not scenarioRules) + { scenarioRulesCreate(); + } } buffer.clear() << folder << Yuni::IO::Separator << "ConstraintBuilder" << Yuni::IO::Separator @@ -265,5 +266,4 @@ bool Study::saveToFolder(const AnyString& newfolder) return ret; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.cpp b/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.cpp index 72dd81503a..5ffef13e98 100644 --- a/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.cpp +++ b/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 22/03/23. // @@ -8,8 +28,8 @@ ** This file is part of Antares_Simulator. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** ** There are special exceptions to the terms and conditions of the @@ -20,48 +40,52 @@ ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** SPDX-License-Identifier: MPL-2.0 */ -#include +#include "antares/study/scenario-builder/BindingConstraintsTSNumbersData.h" + #include -#include "BindingConstraintsTSNumbersData.h" -#include "applyToMatrix.hxx" +#include + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { bool BindingConstraintsTSNumberData::apply(Study& study) { - return std::all_of(rules_.begin(), rules_.end(), [&study, this](const std::pair& args){ - const auto& [groupName, tsNumbers] = args; - auto group = study.bindingConstraintsGroups[groupName]; - if (group == nullptr) { - logs.error("Group with name '" + groupName + "' does not exists"); - } - uint errors = 0; - CString<512, false> logprefix; - logprefix.clear() << "Binding constraints: group '" << groupName <<"': "; - return ApplyToMatrix(errors, - logprefix, - *group, - tsNumbers[0], - get_tsGenCount(study)); - }); + return std::all_of( + rules_.begin(), + rules_.end(), + [&study, this](const auto& args) + { + const auto& [groupName, tsNumbers] = args; + auto group = study.bindingConstraintsGroups[groupName]; + if (group == nullptr) + { + logs.error("Group with name '" + groupName + "' does not exists"); + } + uint errors = 0; + CString<512, false> logprefix; + logprefix.clear() << "Binding constraints: group '" << groupName << "': "; + return ApplyToMatrix(errors, logprefix, *group, tsNumbers[0], get_tsGenCount(study)); + }); } bool BindingConstraintsTSNumberData::reset(const Study& study) { const uint nbYears = study.parameters.nbYears; - std::for_each(study.bindingConstraintsGroups.begin(), study.bindingConstraintsGroups.end(), [&](const auto& group) { - MatrixType& ts_numbers = rules_[group->name()]; - ts_numbers.resize(1, nbYears); - ts_numbers.fillColumn(0, 0); - }); + std::ranges::for_each(study.bindingConstraintsGroups, + [this, &nbYears](const auto& group) + { + auto& ts_numbers = rules_[group->name()]; + ts_numbers.reset(1, nbYears); + }); return true; } @@ -71,19 +95,25 @@ void BindingConstraintsTSNumberData::saveToINIFile(const Study&, Yuni::IO::File: std::ostringstream value_into_string; value_into_string << std::setprecision(4); - for (const auto& [group_name, ts_numbers]: rules_) { - for (unsigned year = 0; year < ts_numbers.height; ++year) { + for (const auto& [group_name, ts_numbers]: rules_) + { + for (unsigned year = 0; year < ts_numbers.height; ++year) + { auto value = ts_numbers[0][year]; - if (value != 0) { + if (value != 0) + { file << get_prefix() << group_name << "," << year << "=" << value << "\n"; } } } } -void BindingConstraintsTSNumberData::setTSnumber(const std::string& group_name, const uint year, uint value) { +void BindingConstraintsTSNumberData::setTSnumber(const std::string& group_name, + const uint year, + uint value) +{ auto& group_ts_numbers = rules_[group_name]; group_ts_numbers[0][year] = value; } -} // namespace Antares +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h b/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h deleted file mode 100644 index e4fbbe9f96..0000000000 --- a/src/libs/antares/study/scenario-builder/BindingConstraintsTSNumbersData.h +++ /dev/null @@ -1,46 +0,0 @@ -// -// Created by marechaljas on 03/07/23. -// - -#pragma once - -#include "TSnumberData.h" - -namespace Antares::Data::ScenarioBuilder -{ -class BindingConstraintsTSNumberData : public TSNumberData -{ -public: - BindingConstraintsTSNumberData() = default; - virtual ~BindingConstraintsTSNumberData() = default; - - bool reset(const Study& study) override; - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; - - void setTSnumber(const std::string& group_name, unsigned year, unsigned value); - unsigned get(const std::string& group_name, unsigned year) const; - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - unsigned get_tsGenCount(const Study& study) const override; -private: - std::map rules_; -}; - -inline unsigned BindingConstraintsTSNumberData::get(const std::string& group_name, const unsigned year) const -{ - auto it = rules_.find(group_name); - if (it == rules_.end()) { - return 0; - } - return it->second[0][year]; -} - -inline CString<512, false> BindingConstraintsTSNumberData::get_prefix() const -{ - return "bc,"; -} - -inline unsigned BindingConstraintsTSNumberData::get_tsGenCount(const Study&) const { - return 0; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/HydroTSNumberData.cpp b/src/libs/antares/study/scenario-builder/HydroTSNumberData.cpp index c39073f587..869971fdba 100644 --- a/src/libs/antares/study/scenario-builder/HydroTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/HydroTSNumberData.cpp @@ -1,9 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 04/07/23. // -#include "HydroTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/HydroTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -42,4 +63,4 @@ bool hydroTSNumberData::apply(Study& study) return ret; } -} \ No newline at end of file +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/HydroTSNumberData.h b/src/libs/antares/study/scenario-builder/HydroTSNumberData.h deleted file mode 100644 index 7000c91507..0000000000 --- a/src/libs/antares/study/scenario-builder/HydroTSNumberData.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// Created by marechaljas on 04/07/23. -// - -#pragma once - -#include "TSnumberData.h" -namespace Antares::Data::ScenarioBuilder -{ -class hydroTSNumberData : public TSNumberData -{ -public: - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; -}; - -inline CString<512, false> hydroTSNumberData::get_prefix() const -{ - return "h,"; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/LoadTSNumberData.cpp b/src/libs/antares/study/scenario-builder/LoadTSNumberData.cpp index 142d411429..d86bb00581 100644 --- a/src/libs/antares/study/scenario-builder/LoadTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/LoadTSNumberData.cpp @@ -1,9 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 04/07/23. // -#include "LoadTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/LoadTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -37,8 +58,8 @@ bool loadTSNumberData::apply(Study& study) const MatrixType::ColumnType& col = pTSNumberRules[areaIndex]; logprefix.clear() << "Load: Area '" << area.name << "': "; - ret = ApplyToMatrix(errors, logprefix, *area.load.series, col, tsGenCountLoad) && ret; + ret = ApplyToMatrix(errors, logprefix, area.load.series, col, tsGenCountLoad) && ret; } return ret; } -} \ No newline at end of file +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/LoadTSNumberData.h b/src/libs/antares/study/scenario-builder/LoadTSNumberData.h deleted file mode 100644 index 09ee2de81f..0000000000 --- a/src/libs/antares/study/scenario-builder/LoadTSNumberData.h +++ /dev/null @@ -1,23 +0,0 @@ -// -// Created by marechaljas on 04/07/23. -// - -#pragma once - -#include "TSnumberData.h" -namespace Antares::Data::ScenarioBuilder -{ -class loadTSNumberData : public TSNumberData -{ -public: - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; -}; - -inline CString<512, false> loadTSNumberData::get_prefix() const -{ - return "l,"; -} - -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/NTCTSNumberData.cpp b/src/libs/antares/study/scenario-builder/NTCTSNumberData.cpp index 492189b57b..779e5ee4ec 100644 --- a/src/libs/antares/study/scenario-builder/NTCTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/NTCTSNumberData.cpp @@ -1,9 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 03/07/23. // -#include "NTCTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/NTCTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -22,7 +43,9 @@ bool ntcTSNumberData::reset(const Study& study) void ntcTSNumberData::saveToINIFile(const Study& /* study */, Yuni::IO::File::Stream& file) const { if (!pArea) + { return; + } // Prefix CString<512, false> prefix; @@ -35,7 +58,7 @@ void ntcTSNumberData::saveToINIFile(const Study& /* study */, Yuni::IO::File::St } #endif - for (const auto& i : pArea->links) + for (const auto& i: pArea->links) { const Data::AreaLink* link = i.second; /* @@ -49,7 +72,9 @@ void ntcTSNumberData::saveToINIFile(const Study& /* study */, Yuni::IO::File::St const uint val = pTSNumberRules[link->indexForArea][y]; // Equals to zero means 'auto', which is the default mode if (!val) + { continue; + } file << prefix << fromID << "," << withID << "," << y << " = " << val << "\n"; } } @@ -61,7 +86,9 @@ void ntcTSNumberData::setDataForLink(const Antares::Data::AreaLink* link, { assert(link != nullptr); if (year < pTSNumberRules.height && link->indexForArea < pTSNumberRules.width) + { pTSNumberRules[link->indexForArea][year] = value; + } } bool ntcTSNumberData::apply(Study& study) @@ -78,7 +105,7 @@ bool ntcTSNumberData::apply(Study& study) const uint ntcGeneratedTScount = get_tsGenCount(study); - for (const auto& i : pArea->links) + for (const auto& i: pArea->links) { auto* link = i.second; uint linkIndex = link->indexForArea; @@ -94,4 +121,4 @@ uint ntcTSNumberData::get_tsGenCount(const Study& /* study */) const { return 0; } -} +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/NTCTSNumberData.h b/src/libs/antares/study/scenario-builder/NTCTSNumberData.h deleted file mode 100644 index d2b48a83d5..0000000000 --- a/src/libs/antares/study/scenario-builder/NTCTSNumberData.h +++ /dev/null @@ -1,50 +0,0 @@ -// -// Created by marechaljas on 03/07/23. -// - -#pragma once -#include "TSnumberData.h" - -namespace Antares::Data::ScenarioBuilder -{ -class ntcTSNumberData : public TSNumberData -{ -public: - ntcTSNumberData() = default; - virtual ~ntcTSNumberData() = default; - - bool reset(const Study& study) override; - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; - - void attachArea(const Area* area) - { - pArea = area; - } - - void setDataForLink(const Antares::Data::AreaLink* link, const uint year, uint value); - uint get(const Antares::Data::AreaLink* link, const uint year) const; - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; - -private: - //! The attached area, if any - const Area* pArea = nullptr; -}; - -inline uint ntcTSNumberData::get(const Antares::Data::AreaLink* link, const uint year) const -{ - assert(link != nullptr); - if (year < pTSNumberRules.height && link->indexForArea < pTSNumberRules.width) - { - const uint index = link->indexForArea; - return pTSNumberRules[index][year]; - } - return 0; -} - -inline CString<512, false> ntcTSNumberData::get_prefix() const -{ - return "ntc,"; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/RenewableTSNumberData.cpp b/src/libs/antares/study/scenario-builder/RenewableTSNumberData.cpp index 24d356ad03..516ae91cb4 100644 --- a/src/libs/antares/study/scenario-builder/RenewableTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/RenewableTSNumberData.cpp @@ -1,9 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 03/07/23. // -#include "RenewableTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/RenewableTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -13,7 +34,9 @@ void renewableTSNumberData::setTSnumber(const Antares::Data::RenewableCluster* c { assert(cluster != nullptr); if (year < pTSNumberRules.height && cluster->areaWideIndex < pTSNumberRules.width) + { pTSNumberRules[cluster->areaWideIndex][year] = value; + } } bool renewableTSNumberData::apply(Study& study) @@ -29,20 +52,18 @@ bool renewableTSNumberData::apply(Study& study) Area& area = *(study.areas.byIndex[pArea->index]); // The total number of clusters for the area // WARNING: We may have some renewable clusters with the `mustrun` option - auto clusterCount = (uint)area.renewable.clusterCount(); const uint tsGenCountRenewable = get_tsGenCount(study); - for (uint clusterIndex = 0; clusterIndex != clusterCount; ++clusterIndex) + for (const auto& cluster: area.renewable.list.each_enabled()) { - auto& cluster = *(area.renewable.clusters[clusterIndex]); // alias to the current column - assert(clusterIndex < pTSNumberRules.width); - const auto& col = pTSNumberRules[clusterIndex]; + assert(cluster->areaWideIndex < pTSNumberRules.width); + const auto& col = pTSNumberRules[cluster->areaWideIndex]; - logprefix.clear() << "Renewable: area '" << area.name << "', cluster: '" << cluster.name() + logprefix.clear() << "Renewable: area '" << area.name << "', cluster: '" << cluster->name() << "': "; - ret = ApplyToMatrix(errors, logprefix, *cluster.series, col, tsGenCountRenewable) && ret; + ret = ApplyToMatrix(errors, logprefix, cluster->series, col, tsGenCountRenewable) && ret; } return ret; } @@ -64,27 +85,22 @@ void renewableTSNumberData::saveToINIFile(const Study& /* study */, prefix += get_prefix(); if (!pArea) - return; - -// Foreach year -#ifndef NDEBUG - if (pTSNumberRules.width) { - assert(pTSNumberRules.width == pArea->renewable.list.size()); + return; } -#endif - for (uint index = 0; index != pTSNumberRules.width; ++index) + for (auto& cluster: pArea->renewable.list.all()) { - // Foreach renewable cluster... - for (uint y = 0; y != pTSNumberRules.height; ++y) + for (uint year = 0; year != pTSNumberRules.height; ++year) { - const uint val = get(pArea->renewable.list.byIndex[index], y); + const uint val = get(cluster.get(), year); // Equals to zero means 'auto', which is the default mode if (!val) + { continue; - file << prefix << pArea->id << "," << y << ',' - << pArea->renewable.list.byIndex[index]->id() << " = " << val << '\n'; + } + file << prefix << pArea->id << "," << year << ',' << cluster->id() << " = " << val + << '\n'; } } } @@ -99,9 +115,9 @@ bool renewableTSNumberData::reset(const Study& study) // solver or not. // WARNING: At this point in time, the variable pArea->renewable.clusterCount() // might not be valid (because not really initialized yet) - const uint clusterCount = pArea->renewable.list.size(); + const uint clusterCount = pArea->renewable.list.allClustersCount(); // Resize pTSNumberRules.reset(clusterCount, nbYears); return true; } -} \ No newline at end of file +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/RenewableTSNumberData.h b/src/libs/antares/study/scenario-builder/RenewableTSNumberData.h deleted file mode 100644 index 73fee33d82..0000000000 --- a/src/libs/antares/study/scenario-builder/RenewableTSNumberData.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Created by marechaljas on 03/07/23. -// - -#pragma once - -#include "TSnumberData.h" -namespace Antares::Data::ScenarioBuilder -{ -class renewableTSNumberData : public TSNumberData -{ -public: - renewableTSNumberData() = default; - - virtual ~renewableTSNumberData() - { - } - - bool reset(const Study& study) override; - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; - - void attachArea(const Area* area) - { - pArea = area; - } - - void setTSnumber(const Antares::Data::RenewableCluster* cluster, const uint year, uint value); - uint get(const Antares::Data::RenewableCluster* cluster, const uint year) const; - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; - -private: - //! The attached area, if any - const Area* pArea = nullptr; -}; - -inline uint renewableTSNumberData::get(const Antares::Data::RenewableCluster* cluster, - const uint year) const -{ - assert(cluster != nullptr); - if (year < pTSNumberRules.height && cluster->areaWideIndex < pTSNumberRules.width) - { - const uint index = cluster->areaWideIndex; - return pTSNumberRules[index][year]; - } - return 0; -} - -inline CString<512, false> renewableTSNumberData::get_prefix() const -{ - return "r,"; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/SolarTSNumberData.cpp b/src/libs/antares/study/scenario-builder/SolarTSNumberData.cpp index 50e8ec2dd5..e818eec7d2 100644 --- a/src/libs/antares/study/scenario-builder/SolarTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/SolarTSNumberData.cpp @@ -1,9 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 04/07/23. // -#include "solarTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/solarTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -37,8 +58,8 @@ bool solarTSNumberData::apply(Study& study) const MatrixType::ColumnType& col = pTSNumberRules[areaIndex]; logprefix.clear() << "Solar: area '" << area.name << "': "; - ret = ApplyToMatrix(errors, logprefix, *area.solar.series, col, tsGenCountSolar) && ret; + ret = ApplyToMatrix(errors, logprefix, area.solar.series, col, tsGenCountSolar) && ret; } return ret; } -} \ No newline at end of file +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/TSnumberData.cpp b/src/libs/antares/study/scenario-builder/TSnumberData.cpp index 6f72b264b1..c0f81f411b 100644 --- a/src/libs/antares/study/scenario-builder/TSnumberData.cpp +++ b/src/libs/antares/study/scenario-builder/TSnumberData.cpp @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "TSnumberData.h" -#include "scBuilderUtils.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/TSnumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" +#include "antares/study/scenario-builder/scBuilderUtils.h" namespace Antares::Data::ScenarioBuilder { @@ -59,7 +54,9 @@ void TSNumberData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& fil const MatrixType::Type value = col[y]; // Equals to zero means 'auto', which is the default mode if (!value) + { continue; + } assert(index < study.areas.size()); file << prefix << study.areas.byIndex[index]->id << ',' << y << " = " << value << '\n'; } @@ -70,11 +67,14 @@ void TSNumberData::setTSnumber(uint areaindex, uint year, uint value) { assert(areaindex < pTSNumberRules.width); if (year < pTSNumberRules.height) + { pTSNumberRules[areaindex][year] = value; + } } void TSNumberData::set_value(uint x, uint y, uint value) { pTSNumberRules.entry[y][x] = value; } -} // namespace Antares + +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/TSnumberData.h b/src/libs/antares/study/scenario-builder/TSnumberData.h deleted file mode 100644 index ca2c1ee583..0000000000 --- a/src/libs/antares/study/scenario-builder/TSnumberData.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_TS_NUMBER_H__ -#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_TS_NUMBER_H__ - -#include "scBuilderDataInterface.h" - -namespace Antares::Data::ScenarioBuilder -{ -/*! -** \brief Rules for TS numbers, for all years and a single timeseries -*/ -class TSNumberData : public dataInterface -{ -public: - //! Matrix - using MatrixType = Matrix; - -public: - // We use default constructor and destructor - - //! \name Data manupulation - //@{ - /*! - ** \brief Reset data from the study - */ - bool reset(const Study& study) override; - - /*! - ** \brief Export the data into a mere INI file - */ - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; - - /*! - ** \brief Assign a single value - ** - ** \param index An area index or a thermal cluster index - ** \param year A year - ** \param value The new TS number - */ - void setTSnumber(uint index, uint year, uint value); - //@} - - uint width() const; - uint height() const; - - double get_value(uint x, uint y) const; - void set_value(uint x, uint y, uint value); - - /* - ** Give the study an access to TS numbers scenarii - */ - virtual bool apply(Study& study) = 0; - -protected: - virtual CString<512, false> get_prefix() const = 0; - - virtual uint get_tsGenCount(const Study& study) const = 0; - -protected: - //! All TS number overlay (0 if auto) - MatrixType pTSNumberRules; - -}; // class TSNumberData - -// class TSNumberData : inline functions - -inline uint TSNumberData::width() const -{ - return pTSNumberRules.width; -} - -inline uint TSNumberData::height() const -{ - return pTSNumberRules.height; -} - -inline double TSNumberData::get_value(uint x, uint y) const -{ - return pTSNumberRules.entry[y][x]; -} - -} // namespace Antares::Data::ScenarioBuilder - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_TS_NUMBER_H__ diff --git a/src/libs/antares/study/scenario-builder/ThermalTSNumberData.cpp b/src/libs/antares/study/scenario-builder/ThermalTSNumberData.cpp index bdd9e20582..73e094a9b3 100644 --- a/src/libs/antares/study/scenario-builder/ThermalTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/ThermalTSNumberData.cpp @@ -1,9 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 04/07/23. // -#include "ThermalTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/ThermalTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -15,11 +36,10 @@ bool thermalTSNumberData::reset(const Study& study) // If an area is available, it can only be an overlay for thermal timeseries // WARNING: The total number of clusters may vary if used from the // solver or not. - // WARNING: At this point in time, the variable pArea->thermal.clusterCount() + // WARNING: At this point, the variable pArea->thermal.list.size() // might not be valid (because not really initialized yet) - uint clusterCount = (study.usedByTheSolver) - ? (pArea->thermal.list.size() + pArea->thermal.mustrunList.size()) - : pArea->thermal.list.size(); + uint clusterCount = (study.usedByTheSolver) ? (pArea->thermal.list.enabledCount()) + : pArea->thermal.list.allClustersCount(); // Resize pTSNumberRules.reset(clusterCount, nbYears); @@ -34,27 +54,22 @@ void thermalTSNumberData::saveToINIFile(const Study& /* study */, prefix += get_prefix(); if (!pArea) - return; - -#ifndef NDEBUG - if (pTSNumberRules.width) { - assert(pTSNumberRules.width == pArea->thermal.list.size()); + return; } -#endif - // Foreach thermal cluster... - for (uint index = 0; index != pTSNumberRules.width; ++index) + for (auto& cluster: pArea->thermal.list.all()) { - // Foreach year ... - for (uint y = 0; y != pTSNumberRules.height; ++y) + for (uint year = 0; year != pTSNumberRules.height; ++year) { - const uint val = get(pArea->thermal.list.byIndex[index], y); + const uint val = get(cluster.get(), year); // Equals to zero means 'auto', which is the default mode if (!val) + { continue; - file << prefix << pArea->id << "," << y << ',' - << pArea->thermal.list.byIndex[index]->id() << " = " << val << '\n'; + } + file << prefix << pArea->id << "," << year << ',' << cluster->id() << " = " << val + << '\n'; } } } @@ -65,7 +80,9 @@ void thermalTSNumberData::setTSnumber(const Antares::Data::ThermalCluster* clust { assert(cluster != nullptr); if (year < pTSNumberRules.height && cluster->areaWideIndex < pTSNumberRules.width) + { pTSNumberRules[cluster->areaWideIndex][year] = value; + } } bool thermalTSNumberData::apply(Study& study) @@ -78,23 +95,20 @@ bool thermalTSNumberData::apply(Study& study) // Alias to the current area assert(pArea != nullptr); assert(pArea->index < study.areas.size()); - Area& area = *(study.areas.byIndex[pArea->index]); - // The total number of clusters for the area - // WARNING: We may have some thermal clusters with the `mustrun` option - auto clusterCount = (uint)area.thermal.clusterCount(); + const Area& area = *(study.areas.byIndex[pArea->index]); - const uint tsGenCountThermal = get_tsGenCount(study); - - for (uint clusterIndex = 0; clusterIndex != clusterCount; ++clusterIndex) + for (auto& cluster: area.thermal.list.each_enabled()) { - auto& cluster = *(area.thermal.clusters[clusterIndex]); - // alias to the current column - assert(clusterIndex < pTSNumberRules.width); - const auto& col = pTSNumberRules[clusterIndex]; + assert(cluster->areaWideIndex < pTSNumberRules.width); + const auto& col = pTSNumberRules[cluster->areaWideIndex]; + + uint tsGenCount = cluster->tsGenBehavior == LocalTSGenerationBehavior::forceNoGen + ? cluster->series.timeSeries.width + : get_tsGenCount(study); - logprefix.clear() << "Thermal: area '" << area.name << "', cluster: '" << cluster.name() + logprefix.clear() << "Thermal: area '" << area.name << "', cluster: '" << cluster->name() << "': "; - ret = ApplyToMatrix(errors, logprefix, *cluster.series, col, tsGenCountThermal) && ret; + ret = ApplyToMatrix(errors, logprefix, cluster->series, col, tsGenCount) && ret; } return ret; } @@ -107,4 +121,4 @@ uint thermalTSNumberData::get_tsGenCount(const Study& study) const bool tsGenThermal = (0 != (parameters.timeSeriesToGenerate & timeSeriesThermal)); return tsGenThermal ? parameters.nbTimeSeriesThermal : 0u; } -} \ No newline at end of file +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/ThermalTSNumberData.h b/src/libs/antares/study/scenario-builder/ThermalTSNumberData.h deleted file mode 100644 index 7831a13a0d..0000000000 --- a/src/libs/antares/study/scenario-builder/ThermalTSNumberData.h +++ /dev/null @@ -1,50 +0,0 @@ -// -// Created by marechaljas on 04/07/23. -// - -#pragma once - -#include "TSnumberData.h" -namespace Antares::Data::ScenarioBuilder -{ -class thermalTSNumberData : public TSNumberData -{ -public: - thermalTSNumberData() = default; - - bool reset(const Study& study) override; - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; - - void attachArea(const Area* area) - { - pArea = area; - } - - void setTSnumber(const Antares::Data::ThermalCluster* cluster, const uint year, uint value); - uint get(const Antares::Data::ThermalCluster* cluster, const uint year) const; - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; - -private: - //! The attached area, if any - const Area* pArea = nullptr; -}; - -inline uint thermalTSNumberData::get(const Antares::Data::ThermalCluster* cluster, - const uint year) const -{ - assert(cluster != nullptr); - if (year < pTSNumberRules.height && cluster->areaWideIndex < pTSNumberRules.width) - { - const uint index = cluster->areaWideIndex; - return pTSNumberRules[index][year]; - } - return 0; -} - -inline CString<512, false> thermalTSNumberData::get_prefix() const -{ - return "t,"; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/WindTSNumberData.cpp b/src/libs/antares/study/scenario-builder/WindTSNumberData.cpp index c77c856348..6691c563d9 100644 --- a/src/libs/antares/study/scenario-builder/WindTSNumberData.cpp +++ b/src/libs/antares/study/scenario-builder/WindTSNumberData.cpp @@ -1,8 +1,29 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 04/07/23. // -#include "WindTSNumberData.h" -#include "applyToMatrix.hxx" +#include "antares/study/scenario-builder/WindTSNumberData.h" + +#include "antares/study/scenario-builder/applyToMatrix.hxx" namespace Antares::Data::ScenarioBuilder { @@ -36,8 +57,8 @@ bool windTSNumberData::apply(/*const*/ Study& study) const MatrixType::ColumnType& col = pTSNumberRules[areaIndex]; logprefix.clear() << "Wind: area '" << area.name << "': "; - ret = ApplyToMatrix(errors, logprefix, *area.wind.series, col, tsGenCountWind) && ret; + ret = ApplyToMatrix(errors, logprefix, area.wind.series, col, tsGenCountWind) && ret; } return ret; } -} \ No newline at end of file +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/WindTSNumberData.h b/src/libs/antares/study/scenario-builder/WindTSNumberData.h deleted file mode 100644 index 840372dbc9..0000000000 --- a/src/libs/antares/study/scenario-builder/WindTSNumberData.h +++ /dev/null @@ -1,23 +0,0 @@ -// -// Created by marechaljas on 04/07/23. -// - -#pragma once - -#include "TSnumberData.h" - -namespace Antares::Data::ScenarioBuilder -{ -class windTSNumberData : public TSNumberData -{ -public: - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; -}; - -inline CString<512, false> windTSNumberData::get_prefix() const -{ - return "w,"; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/applyToMatrix.hxx b/src/libs/antares/study/scenario-builder/applyToMatrix.hxx deleted file mode 100644 index c2990af51d..0000000000 --- a/src/libs/antares/study/scenario-builder/applyToMatrix.hxx +++ /dev/null @@ -1,92 +0,0 @@ -// -// Created by marechaljas on 03/07/23. -// - -#pragma once - -#include -#include "antares/study/parts/hydro/series.h" -#include "yuni/core/system/stdint.h" - -namespace Antares::Data::ScenarioBuilder { - -static constexpr unsigned maxErrors = 20; - -template -static inline bool CheckValidity(uint value, const D& data, uint tsGenMax) -{ - // When the TS-Generators are not used - return (!tsGenMax) ? (value < data.timeSeries.width) : (value < tsGenMax); -} - -template<> -inline bool CheckValidity(uint value, - const Data::DataSeriesHydro& data, - uint tsGenMax) -{ - // When the TS-Generators are not used - return (!tsGenMax) ? (value < data.count) : (value < tsGenMax); -} - -template<> -inline bool CheckValidity(uint value, - const Data::AreaLink& data, - uint /* tsGenMax */) -{ - //Value = index of time series - //Direct Capacities = all time series - //directCapacities.width = Number of time series - return value < data.directCapacities.width; -} - -template<> -inline bool CheckValidity(uint value, const BindingConstraintGroup& group, uint) -{ - return value < group.numberOfTimeseries(); -} - -template -bool ApplyToMatrix(uint& errors, - StringT& logprefix, - D& data, - const TSNumberData::MatrixType::ColumnType& years, - uint tsGenMax) -{ - bool ret = true; - - // In this case, m.height represents the total number of years - const uint nbYears = data.timeseriesNumbers.height; - // The matrix m has only one column - assert(data.timeseriesNumbers.width == 1); - typename Matrix::ColumnType& target = data.timeseriesNumbers[0]; - - for (uint y = 0; y != nbYears; ++y) - { - if (years[y] != 0) - { - // The new TS number - uint tsNum = years[y] - 1; - - // When the TS-Generators are not used - if (!CheckValidity(tsNum, data, tsGenMax)) - { - if (errors <= maxErrors) - { - if (++errors == maxErrors) - logs.warning() << "scenario-builder: ... (skipped)"; - else - logs.warning() << "scenario-builder: " << logprefix - << "value out of bounds for the year " << (y + 1); - } - ret = false; - continue; - } - // Ok, assign. The value provided by the interface is user-friendly - // and starts from 1. - target[y] = tsNum; - } - } - - return ret; -} -} diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index 654e9600d6..8d0575b96a 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -1,41 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/study/scenario-builder/hydroLevelsData.h" + #include -#include "hydroLevelsData.h" -#include "scBuilderUtils.h" +#include -namespace Antares -{ -namespace Data +#include "antares/study/scenario-builder/scBuilderUtils.h" + +namespace Antares::Data::ScenarioBuilder { -namespace ScenarioBuilder +hydroLevelsData::hydroLevelsData(const std::string& iniFilePrefix, + std::function applyToTarget): + addToPrefix_(iniFilePrefix), + applyToTarget_(applyToTarget) { +} + bool hydroLevelsData::reset(const Study& study) { const uint nbYears = study.parameters.nbYears; @@ -48,10 +47,6 @@ bool hydroLevelsData::reset(const Study& study) void hydroLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const { - // Prefix - CString<512, false> prefix; - prefix += "hl,"; - // Turning values into strings (precision 4) std::ostringstream value_into_string; value_into_string << std::setprecision(4); @@ -68,10 +63,12 @@ void hydroLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& const MatrixType::Type value = col[y]; // Equals to zero means 'auto', which is the default mode if (std::isnan(value)) + { continue; + } assert(index < study.areas.size()); value_into_string << value; - file << prefix << study.areas.byIndex[index]->id << ',' << y << " = " + file << addToPrefix_ << study.areas.byIndex[index]->id << ',' << y << " = " << value_into_string.str() << '\n'; value_into_string.str(std::string()); // Clearing converter } @@ -85,10 +82,8 @@ void hydroLevelsData::set_value(uint x, uint y, double value) bool hydroLevelsData::apply(Study& study) { - study.scenarioHydroLevels.copyFrom(pHydroLevelsRules); + applyToTarget_(study, pHydroLevelsRules); return true; } -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h deleted file mode 100644 index 66c223ffbe..0000000000 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ -#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ - -#include "scBuilderDataInterface.h" - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -/*! -** \brief Rules for hydro levels, for all years and areas -*/ -class hydroLevelsData final : public dataInterface -{ -public: - //! Matrix - using MatrixType = Matrix; - -public: - // We use default constructor and destructor - - //! \name Data manupulation - //@{ - /*! - ** \brief Reset data from the study - */ - bool reset(const Study& study); - - /*! - ** \brief Export the data into a mere INI file - */ - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const; - - /*! - ** \brief Assign a single value - ** - ** \param index An area index - ** \param year A year - ** \param value The new hydro level - */ - void setTSnumber(uint index, uint year, double value); - //@} - - uint width() const; - - uint height() const; - - double get_value(uint x, uint y) const; - - void set_value(uint x, uint y, double value); - - bool apply(Study& study); - -private: - //! Hydro levels overlay (0 if auto) - MatrixType pHydroLevelsRules; - -}; // class hydroLevelsData - -// class hydroLevelsData : inline functions - -inline void hydroLevelsData::setTSnumber(uint areaindex, uint year, double value) -{ - assert(areaindex < pHydroLevelsRules.width); - if (year < pHydroLevelsRules.height) - pHydroLevelsRules[areaindex][year] = value; -} - -inline uint hydroLevelsData::width() const -{ - return pHydroLevelsRules.width; -} - -inline uint hydroLevelsData::height() const -{ - return pHydroLevelsRules.height; -} - -inline double hydroLevelsData::get_value(uint x, uint y) const -{ - return pHydroLevelsRules.entry[y][x]; -} - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index e814468a9a..2037eede6b 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -1,46 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/scenario-builder/rules.h" + #include -#include "rules.h" -#include "../study.h" + #include -#include "scBuilderUtils.h" -#include "TSnumberData.h" +#include "antares/study/scenario-builder/TSnumberData.h" +#include "antares/study/scenario-builder/scBuilderUtils.h" +#include "antares/study/study.h" using namespace Yuni; -namespace Antares -{ -namespace Data +namespace Antares::Data::ScenarioBuilder { -namespace ScenarioBuilder -{ -Rules::Rules(Study& study) : study_(study), pAreaCount(0) +Rules::Rules(Study& study): + study_(study), + pAreaCount(0) { } @@ -65,7 +59,8 @@ void Rules::saveToINIFile(Yuni::IO::File::Stream& file) const linksNTC[i].saveToINIFile(study_, file); } // hydro levels - hydroLevels.saveToINIFile(study_, file); + hydroInitialLevels.saveToINIFile(study_, file); + hydroFinalLevels.saveToINIFile(study_, file); } binding_constraints.saveToINIFile(study_, file); file << '\n'; @@ -101,7 +96,8 @@ bool Rules::reset() renewable[i].reset(study_); } - hydroLevels.reset(study_); + hydroInitialLevels.reset(study_); + hydroFinalLevels.reset(study_); // links NTC linksNTC.clear(); @@ -135,17 +131,17 @@ bool Rules::readThermalCluster(const AreaName::Vector& splitKey, String value, b const ClusterName& clustername = splitKey[3]; if (clustername.empty()) + { return false; + } Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } - const ThermalCluster* cluster = area->thermal.list.find(clustername); - if (!cluster) - cluster = area->thermal.mustrunList.find(clustername); - - if (cluster) + if (const ThermalCluster* cluster = area->thermal.list.findInAll(clustername); cluster) { uint val = fromStringToTSnumber(value); thermal[area->index].setTSnumber(cluster, year, val); @@ -155,8 +151,7 @@ bool Rules::readThermalCluster(const AreaName::Vector& splitKey, String value, b bool isTheActiveRule = (pName.toLower() == study_.parameters.activeRulesScenario.toLower()); if (!updaterMode and isTheActiveRule) { - std::string clusterId - = (area->id).to() + "." + clustername; + std::string clusterId = (area->id).to() + "." + clustername; disabledClustersOnRuleActive[clusterId].push_back(year + 1); return false; } @@ -171,16 +166,22 @@ bool Rules::readRenewableCluster(const AreaName::Vector& splitKey, String value, const ClusterName& clustername = splitKey[3]; if (!study_.parameters.renewableGeneration.isClusters()) + { return false; + } if (clustername.empty()) + { return false; + } Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } - const RenewableCluster* cluster = area->renewable.list.find(clustername); + const RenewableCluster* cluster = area->renewable.list.findInAll(clustername); if (cluster) { @@ -192,8 +193,7 @@ bool Rules::readRenewableCluster(const AreaName::Vector& splitKey, String value, bool isTheActiveRule = (pName.toLower() == study_.parameters.activeRulesScenario.toLower()); if (!updaterMode and isTheActiveRule) { - std::string clusterId - = (area->id).to() + "." + clustername; + std::string clusterId = (area->id).to() + "." + clustername; disabledClustersOnRuleActive[clusterId].push_back(year + 1); return false; } @@ -208,7 +208,9 @@ bool Rules::readLoad(const AreaName::Vector& splitKey, String value, bool update const Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } uint val = fromStringToTSnumber(value); load.setTSnumber(area->index, year, val); @@ -222,7 +224,9 @@ bool Rules::readWind(const AreaName::Vector& splitKey, String value, bool update const Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } uint val = fromStringToTSnumber(value); wind.setTSnumber(area->index, year, val); @@ -236,7 +240,9 @@ bool Rules::readHydro(const AreaName::Vector& splitKey, String value, bool updat const Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } uint val = fromStringToTSnumber(value); hydro.setTSnumber(area->index, year, val); @@ -250,24 +256,44 @@ bool Rules::readSolar(const AreaName::Vector& splitKey, String value, bool updat const Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } uint val = fromStringToTSnumber(value); solar.setTSnumber(area->index, year, val); return true; } -bool Rules::readHydroLevels(const AreaName::Vector& splitKey, String value, bool updaterMode) +bool Rules::readInitialHydroLevels(const AreaName::Vector& splitKey, String value, bool updaterMode) { const uint year = splitKey[2].to(); const AreaName& areaname = splitKey[1]; const Data::Area* area = getArea(areaname, updaterMode); if (!area) + { return false; + } double val = fromStringToHydroLevel(value, 1.); - hydroLevels.setTSnumber(area->index, year, val); + hydroInitialLevels.setTSnumber(area->index, year, val); + return true; +} + +bool Rules::readFinalHydroLevels(const AreaName::Vector& splitKey, String value, bool updaterMode) +{ + const uint year = splitKey[2].to(); + const AreaName& areaname = splitKey[1]; + + const Data::Area* area = getArea(areaname, updaterMode); + if (!area) + { + return false; + } + + double finalLevel = fromStringToHydroLevel(value, 1.); + hydroFinalLevels.setTSnumber(area->index, year, finalLevel); return true; } @@ -293,15 +319,21 @@ bool Rules::readLink(const AreaName::Vector& splitKey, String value, bool update Data::Area* fromArea = getArea(fromAreaName, updaterMode); if (!fromArea) + { return false; + } const Data::Area* toArea = getArea(toAreaName, updaterMode); if (!toArea) + { return false; + } AreaLink* link = getLink(fromAreaName, toAreaName, updaterMode); if (!link) + { return false; + } uint val = fromStringToTSnumber(value); fromArea = link->from; @@ -314,18 +346,22 @@ bool Rules::checkGroupExists(const std::string& groupName) const const auto& groups = study_.bindingConstraintsGroups; if (!groups[groupName]) { - logs.warning() << "[scenario-builder] The binding constraint group '" << groupName << "' does not exist"; + logs.warning() << "[scenario-builder] The binding constraint group '" << groupName + << "' does not exist"; return false; } return true; } -bool Rules::readBindingConstraints(const AreaName::Vector &splitKey, String value) { +bool Rules::readBindingConstraints(const AreaName::Vector& splitKey, String value) +{ std::string group_name = splitKey[1].c_str(); auto year = std::stoi(splitKey[2].c_str()); if (!checkGroupExists(group_name)) + { return false; + } auto tsNumber = fromStringToTSnumber(value); binding_constraints.setTSnumber(group_name, year, tsNumber); @@ -335,30 +371,56 @@ bool Rules::readBindingConstraints(const AreaName::Vector &splitKey, String valu bool Rules::readLine(const AreaName::Vector& splitKey, String value, bool updaterMode) { if (splitKey.size() <= 2) + { return false; + } const AreaName& kind_of_scenario = splitKey[0]; // load, thermal, hydro, ..., hydro levels, ... if (kind_of_scenario.size() > 3) + { return false; + } if (kind_of_scenario == "t") + { return readThermalCluster(splitKey, value, updaterMode); + } else if (kind_of_scenario == "r") + { return readRenewableCluster(splitKey, value, updaterMode); + } else if (kind_of_scenario == "l") + { return readLoad(splitKey, value, updaterMode); + } else if (kind_of_scenario == "w") + { return readWind(splitKey, value, updaterMode); + } else if (kind_of_scenario == "h") + { return readHydro(splitKey, value, updaterMode); + } else if (kind_of_scenario == "s") + { return readSolar(splitKey, value, updaterMode); + } else if (kind_of_scenario == "hl") - return readHydroLevels(splitKey, value, updaterMode); + { + return readInitialHydroLevels(splitKey, value, updaterMode); + } + else if (kind_of_scenario == "hfl") + { + return readFinalHydroLevels(splitKey, value, updaterMode); + } else if (kind_of_scenario == "ntc") + { return readLink(splitKey, value, updaterMode); + } else if (kind_of_scenario == "bc") + { return readBindingConstraints(splitKey, value); + } return false; } @@ -377,11 +439,14 @@ bool Rules::apply() returned_status = renewable[i].apply(study_) && returned_status; returned_status = linksNTC[i].apply(study_) && returned_status; } - returned_status = hydroLevels.apply(study_) && returned_status; + returned_status = hydroInitialLevels.apply(study_) && returned_status; + returned_status = hydroFinalLevels.apply(study_) && returned_status; returned_status = binding_constraints.apply(study_) && returned_status; } else + { returned_status = false; + } return returned_status; } @@ -394,26 +459,28 @@ void Rules::sendWarningsForDisabledClusters() int nbScenariiForCluster = (int)scenariiForCurrentCluster.size(); std::vector::iterator itv = scenariiForCurrentCluster.begin(); - // Listing the 10 first years for which the current cluster was given a specific TS number - // in the scenario builder. - // Note that this list of years size could be less then 10, but are at least 1. + // Listing the 10 first years for which the current cluster was given a specific TS + // number in the scenario builder. Note that this list of years size could be less then + // 10, but are at least 1. std::string listYears = std::to_string(*itv); itv++; for (int year_count = 1; itv != scenariiForCurrentCluster.end() && year_count < 10; itv++, year_count++) + { listYears += ", " + std::to_string(*itv); + } // Adding last scenario to the list if (nbScenariiForCluster > 10) + { listYears += ", ..., " + std::to_string(scenariiForCurrentCluster.back()); + } - logs.warning() - << "Cluster " << it->first - << " not found: it may be disabled, though given TS numbers in sc builder for year(s) :"; + logs.warning() << "Cluster " << it->first + << " not found: it may be disabled, though given TS numbers in sc " + "builder for year(s) :"; logs.warning() << listYears; } } -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/rules.hxx b/src/libs/antares/study/scenario-builder/rules.hxx deleted file mode 100644 index 40bea7edbd..0000000000 --- a/src/libs/antares/study/scenario-builder/rules.hxx +++ /dev/null @@ -1,55 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_RULES_HXX__ -#define __LIBS_STUDY_SCENARIO_BUILDER_RULES_HXX__ - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -inline uint Rules::areaCount() const -{ - return pAreaCount; -} - -inline const RulesScenarioName& Rules::name() const -{ - return pName; -} - -inline void Rules::setName(RulesScenarioName name) -{ - pName = name; -} - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_RULES_H__ diff --git a/src/libs/antares/study/scenario-builder/scBuilderDataInterface.h b/src/libs/antares/study/scenario-builder/scBuilderDataInterface.h deleted file mode 100644 index 836ed23d71..0000000000 --- a/src/libs/antares/study/scenario-builder/scBuilderDataInterface.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_INTERFACE_H__ -#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_INTERFACE_H__ - -#include "../study.h" -#include - -using namespace Yuni; - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -/*! -** \brief Interface for scenario builder data (time series, hydro levels, ...) -*/ -class dataInterface -{ -public: - //! \name Data manupulation - //@{ - /*! - ** \brief Reset data from the study - */ - virtual bool reset(const Study& study) = 0; - - /*! - ** \brief Export the data into a mere INI file - */ - virtual void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const = 0; - - virtual uint width() const = 0; - - virtual uint height() const = 0; - - /*! - ** \brief Apply the changes to the study corresponding data (time series, hydro levels, ...) - ** - ** This method is only useful when launched from the solver. - */ - virtual bool apply(Study& study) = 0; - -}; // class dataInterface - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_INTERFACE_H__ diff --git a/src/libs/antares/study/scenario-builder/scBuilderUtils.cpp b/src/libs/antares/study/scenario-builder/scBuilderUtils.cpp index 4a4d1bc07b..ee869f1a8a 100644 --- a/src/libs/antares/study/scenario-builder/scBuilderUtils.cpp +++ b/src/libs/antares/study/scenario-builder/scBuilderUtils.cpp @@ -1,41 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/study/scenario-builder/scBuilderUtils.h" + +#include #include +#include #include + #include -#include "scBuilderUtils.h" -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder +namespace Antares::Data::ScenarioBuilder { std::string fromHydroLevelToString(double d) { @@ -48,28 +41,17 @@ std::string fromHydroLevelToString(double d) double fromStringToHydroLevel(const Yuni::String& value, const double maxLevel) { double result; - double result_tmp; - std::string val = value.to(); try { - result_tmp = stod(val); + result = stod(val); } catch (std::invalid_argument&) { return std::nan(""); } - if (result_tmp < 0.) - result = 0.; - else - { - if (result_tmp > maxLevel) - result = maxLevel; - else - result = result_tmp; - } - return result; + return std::clamp(result, 0., maxLevel); } uint fromStringToTSnumber(const Yuni::String& value) @@ -89,17 +71,21 @@ uint fromStringToTSnumber(const Yuni::String& value) } if (result_dbl < 0.) + { result = 0; + } else { if (result_dbl > maxTSnumber) + { result = maxTSnumber; + } else + { result = (uint)result_dbl; + } } return result; } -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/scBuilderUtils.h b/src/libs/antares/study/scenario-builder/scBuilderUtils.h deleted file mode 100644 index cd75b6bc49..0000000000 --- a/src/libs/antares/study/scenario-builder/scBuilderUtils.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_UTILS_H__ -#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_UTILS_H__ - -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -std::string fromHydroLevelToString(double d); -double fromStringToHydroLevel(const Yuni::String& value, const double maxLevel); - -uint fromStringToTSnumber(const Yuni::String& value); - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_UTILS_H__ diff --git a/src/libs/antares/study/scenario-builder/sets.cpp b/src/libs/antares/study/scenario-builder/sets.cpp index a4c49cdb51..76dbcb9166 100644 --- a/src/libs/antares/study/scenario-builder/sets.cpp +++ b/src/libs/antares/study/scenario-builder/sets.cpp @@ -1,45 +1,37 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "sets.h" -#include "../study.h" +#include "antares/study/scenario-builder/sets.h" + #include +#include "antares/study/study.h" using namespace Yuni; #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data::ScenarioBuilder { -namespace ScenarioBuilder -{ -Sets::Sets() : pStudy(nullptr) +Sets::Sets(): + pStudy(nullptr) { inUpdaterMode = false; } @@ -63,22 +55,30 @@ void Sets::clear() bool Sets::loadFromStudy(Study& study) { if (not study.usedByTheSolver) + { logs.info() << " Loading data for the scenario builder overlay"; + } setStudy(study); // Loading from the INI file - String filename; - filename << study.folder << SEP << "settings" << SEP << "scenariobuilder.dat"; + std::filesystem::path filename = std::filesystem::path(study.folder.c_str()) / "settings" + / "scenariobuilder.dat"; bool r = true; // If the source code below is changed, please change it in loadFromINIFile too - if (IO::Exists(filename)) - r = internalLoadFromINIFile(filename); + if (std::filesystem::exists(filename)) + { + r = internalLoadFromINIFile(filename.string()); + } else + { pMap.clear(); + } if (pMap.empty()) + { createNew("Default Ruleset"); + } return r; } @@ -90,7 +90,9 @@ Rules::Ptr Sets::createNew(const RulesScenarioName& name) RulesScenarioName id = name; id.toLower(); if (exists(id)) + { return nullptr; + } // The rule set does not exist, creating a new empty one auto newRulesSet = std::make_shared(*pStudy); @@ -106,13 +108,19 @@ Rules::Ptr Sets::rename(const RulesScenarioName& lname, const RulesScenarioName& RulesScenarioName id = newname; id.toLower(); if (id == lname) + { return find(lname); + } if (exists(id)) + { return nullptr; + } Rules::Map::iterator i = pMap.find(lname); if (i == pMap.end()) + { return nullptr; + } Rules::Ptr rules = i->second; pMap.erase(i); rules->setName(newname); @@ -124,11 +132,15 @@ bool Sets::remove(const RulesScenarioName& lname) { // Checking in a first time if the name already exists if (lname.empty()) + { return true; + } Rules::Map::iterator i = pMap.find(lname); if (i == pMap.end()) + { return false; + } pMap.erase(i); return true; } @@ -151,7 +163,9 @@ bool Sets::internalSaveToIniFile(const AnyString& filename) const // There is no ruleset. Trivial. Aborting. if (pMap.empty()) + { return true; + } const Rules::Map::const_iterator end = pMap.end(); for (Rules::Map::const_iterator i = pMap.begin(); i != end; ++i) @@ -160,7 +174,9 @@ bool Sets::internalSaveToIniFile(const AnyString& filename) const // Export the informations of the current ruleset const Rules::Ptr& ruleset = i->second; if (!(!ruleset)) + { ruleset->saveToINIFile(file); + } } return true; } @@ -174,33 +190,39 @@ bool Sets::internalLoadFromINIFile(const AnyString& filename) IniFile ini; if (not ini.open(filename)) + { return false; + } - ini.each([&](const IniFile::Section& section) { - if (section.name.empty()) - return; - - RulesScenarioName name = section.name; - name.trim(" \t"); - if (!name) - return; - - // Create a new ruleset - Rules::Ptr rulesetptr = createNew(name); - Rules& ruleset = *rulesetptr; - AreaName::Vector splitKey; - - for (auto* p = section.firstProperty; p != nullptr; p = p->next) - { - p->key.split(splitKey, ",", true, false); - ruleset.readLine(splitKey, p->value, inUpdaterMode); - } - - ruleset.sendWarningsForDisabledClusters(); - }); + ini.each( + [this](const IniFile::Section& section) + { + if (section.name.empty()) + { + return; + } + + RulesScenarioName name = section.name; + name.trim(" \t"); + if (!name) + { + return; + } + + // Create a new ruleset + Rules::Ptr rulesetptr = createNew(name); + Rules& ruleset = *rulesetptr; + AreaName::Vector splitKey; + + for (auto* p = section.firstProperty; p != nullptr; p = p->next) + { + p->key.split(splitKey, ",", true, false); + ruleset.readLine(splitKey, p->value, inUpdaterMode); + } + + ruleset.sendWarningsForDisabledClusters(); + }); return true; } -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares +} // namespace Antares::Data::ScenarioBuilder diff --git a/src/libs/antares/study/scenario-builder/sets.h b/src/libs/antares/study/scenario-builder/sets.h deleted file mode 100644 index b46cfcbc2a..0000000000 --- a/src/libs/antares/study/scenario-builder/sets.h +++ /dev/null @@ -1,165 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ -#define __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ - -#include -#include "rules.h" - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -/*! -** \brief Sets for TS numbers, for all years and a single timeseries -*/ -class Sets final : private Yuni::NonCopyable -{ -public: - //! Iterator - using iterator = Rules::Map::iterator; - //! Const iterator - using const_iterator = Rules::Map::const_iterator; - -public: - //! Update mode, indicates wether we are called from with a ScenarioBuilderUpdater instance or - //! not - bool inUpdaterMode; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - ** - ** \param tstype Type of the timeseries - */ - Sets(); - //! Destructor - ~Sets(); - //@} - - void setStudy(Study& study); - - //! \name Data manupulation - //@{ - /*! - ** \brief Load data from the study - */ - bool loadFromStudy(Study& study); - - /*! - ** \brief Clear all data - */ - void clear(); - - /*! - ** \brief Load all rulesets from an INI file - */ - template - bool loadFromINIFile(const StringT& filename); - /*! - ** \brief Save all rulesets into a mere INI file - */ - template - bool saveToINIFile(const StringT& filename); - //@} - - //! \name Set manipulation - //@{ - /*! - ** \brief Create a new set - ** - ** \return A non-null pointer if the operation succeeded, null otherwise - */ - Rules::Ptr createNew(const RulesScenarioName& name); - - /*! - ** \brief Test if a rules set exist - ** - ** \param lname Name of the rule set (in lower case) - */ - bool exists(const RulesScenarioName& lname) const; - - /*! - ** \brief Find a rule set - */ - Rules::Ptr find(const RulesScenarioName& lname) const; - - /*! - ** \brief Rename a given ruleset - ** - ** \return The object to the ruleset, null if the operation failed - */ - Rules::Ptr rename(const RulesScenarioName& lname, const RulesScenarioName& newname); - - /*! - ** \brief Delete a ruleset - ** - ** \return True if the operation suceeded, false otherwise - */ - bool remove(const RulesScenarioName& lname); - - iterator begin(); - const_iterator begin() const; - - iterator end(); - const_iterator end() const; - - /*! - ** \brief Get the number of available sets - */ - uint size() const; - - /*! - ** \brief Get if empty - */ - bool empty() const; - //@} - -private: - //! Load all rulesets into a mere INI file - bool internalLoadFromINIFile(const AnyString& filename); - //! Save all rulesets into a mere INI file - bool internalSaveToIniFile(const AnyString& filename) const; - -private: - //! All available sets, ordered by their lower name - Rules::Map pMap; - //! Alias to the study - Study* pStudy; -}; // class Sets - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares - -#include "sets.hxx" - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ diff --git a/src/libs/antares/study/scenario-builder/sets.hxx b/src/libs/antares/study/scenario-builder/sets.hxx deleted file mode 100644 index cf9576df25..0000000000 --- a/src/libs/antares/study/scenario-builder/sets.hxx +++ /dev/null @@ -1,104 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_SETS_HXX__ -#define __LIBS_STUDY_SCENARIO_BUILDER_SETS_HXX__ - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -inline uint Sets::size() const -{ - return (uint)pMap.size(); -} - -inline bool Sets::empty() const -{ - return pMap.empty(); -} - -inline Sets::iterator Sets::begin() -{ - return pMap.begin(); -} - -inline Sets::const_iterator Sets::begin() const -{ - return pMap.begin(); -} - -inline Sets::iterator Sets::end() -{ - return pMap.end(); -} - -inline Sets::const_iterator Sets::end() const -{ - return pMap.end(); -} - -inline bool Sets::exists(const RulesScenarioName& lname) const -{ - return pMap.find(lname) != pMap.end(); -} - -inline Rules::Ptr Sets::find(const RulesScenarioName& lname) const -{ - using namespace Yuni; - const_iterator i = pMap.find(lname); - if (i != pMap.end()) - return i->second; - return nullptr; -} - -template -inline bool Sets::saveToINIFile(const StringT& filename) -{ - const AnyString adapter(filename); - return internalSaveToIniFile(adapter); -} - -template -bool Sets::loadFromINIFile(const StringT& filename) -{ - // If the source code below is changed, please change it in loadFromStudy too - const AnyString adapter(filename); - bool r = internalLoadFromINIFile(adapter); - if (!r) - pMap.clear(); - if (pMap.empty()) - createNew("Default Ruleset"); - return r; -} - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_SETS_H__ diff --git a/src/libs/antares/study/scenario-builder/solarTSNumberData.h b/src/libs/antares/study/scenario-builder/solarTSNumberData.h deleted file mode 100644 index bf5595eb47..0000000000 --- a/src/libs/antares/study/scenario-builder/solarTSNumberData.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// Created by marechaljas on 04/07/23. -// - -#pragma once - -#include "TSnumberData.h" -namespace Antares::Data::ScenarioBuilder -{ -class solarTSNumberData : public TSNumberData -{ -public: - bool apply(Study& study) override; - CString<512, false> get_prefix() const override; - uint get_tsGenCount(const Study& study) const override; -}; - -inline CString<512, false> solarTSNumberData::get_prefix() const -{ - return "s,"; -} -} \ No newline at end of file diff --git a/src/libs/antares/study/scenario-builder/updater.hxx b/src/libs/antares/study/scenario-builder/updater.hxx deleted file mode 100644 index e79ad5cd25..0000000000 --- a/src/libs/antares/study/scenario-builder/updater.hxx +++ /dev/null @@ -1,92 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_SCENARIO_BUILDER_UPDATER_HXX__ -#define __ANTARES_LIBS_STUDY_SCENARIO_BUILDER_UPDATER_HXX__ - -#include -#include "../study.h" -#include "sets.h" - -#define SEP IO::Separator - -namespace Antares -{ -namespace // anonymous -{ -class ScenarioBuilderUpdater -{ -public: - ScenarioBuilderUpdater(Data::Study& study) : pStudy(study) - { - using namespace Yuni; - // We can store the INI files in disk because it may not fit in memory - - if (study.scenarioRules) - { - study.scenarioRules->inUpdaterMode = true; - logs.debug() << "[scenario-builder] updater mode ON"; - - logs.debug() - << "[scenario-builder] writing data to a temporary file before structure changes"; - pTempFile << memory.cacheFolder() << SEP << "antares-scenbld-save-" - << memory.processID() << '-' << (size_t)(this) << "-scenariobuilder.tmp"; - // Dump the memory - study.scenarioRules->saveToINIFile(pTempFile); - study.scenarioRules->clear(); - } - } - - ~ScenarioBuilderUpdater() - { - using namespace Yuni; - - if (not pTempFile.empty()) - { - if (pStudy.scenarioRules) - { - logs.debug() << "[scenario-builder] reloading data from a temporary file"; - pStudy.scenarioRules->loadFromINIFile(pTempFile); - - pStudy.scenarioRules->inUpdaterMode = false; - logs.debug() << "[scenario-builder] updater mode OFF"; - } - // Removing the temporary file - IO::File::Delete(pTempFile); - } - } - -private: - Data::Study& pStudy; - Yuni::String pTempFile; - -}; // class ScenarioBuilderUpdater - -} // anonymous namespace - -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_SCENARIO_BUILDER_UPDATER_HXX__ diff --git a/src/libs/antares/study/sets.h b/src/libs/antares/study/sets.h deleted file mode 100644 index f553d05f04..0000000000 --- a/src/libs/antares/study/sets.h +++ /dev/null @@ -1,299 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_SETS_H__ -#define __ANTARES_LIBS_STUDY_SETS_H__ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Antares -{ -namespace Data -{ -template -class Sets final -{ -public: - //! Type - using Type = T; - - // - using IDType = Yuni::CString<128, false>; - //! Value - using TypePtr = std::shared_ptr; - - //! Map of Item - using MapType = std::map; - //! Standard iterators from the STL - using iterator = typename MapType::iterator; - //! Standard iterators from the STL (const) - using const_iterator = typename MapType::const_iterator; - - enum RuleType - { - ruleNone = 0, - ruleAdd, - ruleRemove, - ruleFilter, - ruleMax, - }; - //! Definition of a single rule - using Rule = std::pair; - //! Rule Set - using RuleSet = std::vector; - - class Options final - { - public: - Options() : output(true), resultSize(0) - { - } - Options(const Options& rhs) : - caption(rhs.caption), - comments(rhs.comments), - rules(rhs.rules), - output(rhs.output), - resultSize(rhs.resultSize) - { - } - - void reset(const IDType& id) - { - caption = id; - comments.clear(); - rules.clear(); - output = false; - resultSize = 0; - } - - Options& operator=(const Options& rhs) - { - caption = rhs.caption; - comments = rhs.comments; - rules = rhs.rules; - output = rhs.output; - resultSize = rhs.resultSize; - return *this; - } - - public: - //! Caption - IDType caption; - //! Comments - Yuni::String comments; - //! Rules to build the group - RuleSet rules; - //! Enable/Disable the results in the output - bool output; - //! The number of items in the result set - uint resultSize; - - }; // class Options - - using MapOptions = std::map; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Sets(); - /*! - ** \brief Copy constructor - */ - Sets(const Sets& rhs); - //! Destructor - ~Sets(); - //@} - - //! \name Iterators - //@{ - iterator begin(); - const_iterator begin() const; - iterator end(); - const_iterator end() const; - //@} - - /*! - ** \brief Clear all groups - */ - void clear(); - - /*! - ** - */ - TypePtr add(const IDType& name) - { - TypePtr p = new T(); - pMap[name] = p; - pOptions[name].reset(name); - return p; - } - - /*! - ** - */ - TypePtr add(const IDType& name, const TypePtr& data) - { - pMap[name] = data; - pOptions[name].reset(name); - return data; - } - - /*! - ** - */ - TypePtr add(const IDType& name, const TypePtr& data, Options& opts) - { - pMap[name] = data; - pOptions[name] = opts; - return data; - } - - bool forceReload(bool /*reload*/) const - { - pModified = true; - return true; - } - - void markAsModified() const - { - pModified = true; - } - - uint size() const; - - void rebuildIndexes(); - - /*! - ** \brief Get if the results for a given group should be written to the output - */ - template - bool hasOutput(const StringT& s) const; - - /*! - ** \brief Get if the results for a given group should be written to the output - */ - bool hasOutput(const uint index) const; - - /*! - ** \brief Get the size of a result set - */ - template - uint resultSize(const StringT& s) const; - - /*! - ** \brief Get the size of a result set - */ - uint resultSize(const uint index) const; - - template - void dumpToLogs(L& log) const; - - /*! - ** \brief Load a rule set from an INI File - */ - template - bool loadFromFile(const StringT& filename); - - template - bool saveToFile(const StringT& filename) const; - /*! - ** \brief format the string to match the options - */ - YString toString(); - - /*! - ** \brief Create default groups for set of areas - */ - void defaultForAreas(); - - /*! - ** \brief Rebuild the lists of a group from the rules - */ - template - void rebuildFromRules(const IDType& id, HandlerT& handler); - - /*! - ** \brief Rebuild the lists of all group from the rules - */ - template - void rebuildAllFromRules(HandlerT& handler); - - const IDType& nameByIndex(const uint i) const - { - assert(i < pMap.size() && "Sets: operator[] index out of bounds"); - return pNameByIndex[i]; - } - - template - IDType caption(const StringT& s) const; - - IDType caption(const uint i) const; - - T& operator[](uint i); - const T& operator[](uint i) const; - /* - void changeTextFile(YString filename) { - if (IO::File::LoadFromFile(pFileContents, filename)) { - pFileContents = NULL; - } - } - - YString getFileContents() { - if (pFileContents!=NULL) { - YString ret; - ret << pFileContents; - return ret; - } - else return NULL; - } - */ -private: - //! All groups - MapType pMap; - MapOptions pOptions; - //! - TypePtr* pByIndex; - IDType* pNameByIndex; - mutable bool pModified; - -}; // class Sets - -} // namespace Data -} // namespace Antares - -#include "sets.hxx" - -#endif // __ANTARES_LIBS_STUDY_SETS_H__ diff --git a/src/libs/antares/study/sets.hxx b/src/libs/antares/study/sets.hxx deleted file mode 100644 index 162919c0bc..0000000000 --- a/src/libs/antares/study/sets.hxx +++ /dev/null @@ -1,466 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_SETS_HXX__ -#define __ANTARES_LIBS_STUDY_SETS_HXX__ - -namespace Antares -{ -namespace Data -{ -template -inline Sets::Sets() : pByIndex(NULL), pNameByIndex(NULL), pModified(false) -{ -} - -template -inline Sets::Sets(const Sets& rhs) : - pMap(rhs.pMap), pOptions(rhs.pOptions), pByIndex(NULL), pNameByIndex(NULL), pModified(false) -{ - if (rhs.pByIndex) - rebuildIndexes(); -} - -template -inline Sets::~Sets() -{ - delete[] pByIndex; -} - -template -typename Sets::iterator Sets::begin() -{ - return pMap.begin(); -} - -template -typename Sets::const_iterator Sets::begin() const -{ - return pMap.begin(); -} - -template -typename Sets::iterator Sets::end() -{ - return pMap.end(); -} - -template -typename Sets::const_iterator Sets::end() const -{ - return pMap.end(); -} - -template -void Sets::clear() -{ - if (pByIndex) - { - delete[] pByIndex; - pByIndex = NULL; - } - if (pNameByIndex) - { - delete[] pNameByIndex; - pNameByIndex = NULL; - } - - pMap.clear(); - pOptions.clear(); -} - -template -inline T& Sets::operator[](uint i) -{ - assert(i < pMap.size() && "Sets: operator[] index out of bounds"); - return *(pByIndex[i]); -} - -template -inline const T& Sets::operator[](uint i) const -{ - assert(i < pMap.size() && "Sets: operator[] index out of bounds"); - return *(pByIndex[i]); -} - -template -template -void Sets::dumpToLogs(L& log) const -{ - using namespace Yuni; - const typename MapType::const_iterator end = pMap.end(); - for (typename MapType::const_iterator i = pMap.begin(); i != end; ++i) - { - log.info() << " found `" << i->first << "` (" << (uint)i->second->size() << ' ' - << (i->second->size() < 2 ? "item" : "items") - << ((!hasOutput(i->first)) ? ", no output" : "") << ')'; - } -} - -template -void Sets::defaultForAreas() -{ - using namespace Yuni; - clear(); - Options opts; - opts.caption = "All areas"; - opts.comments = "Spatial aggregates on all areas"; - opts.output = false; - opts.rules.push_back(Rule(ruleFilter, new String("add-all"))); - auto item = std::make_shared(); - add("all areas", item, opts); -} - -template -YString Sets::toString() -{ - using namespace Yuni; - using namespace Antares; - static const char* cmds[ruleMax] = {"none", "+", "-", "apply-filter"}; - const auto end = pOptions.cend(); - YString ret = ""; - for (auto i = pOptions.cbegin(); i != end; ++i) - { - const Options& opts = i->second; - ret << '[' << i->first << "]\n"; - ret << "caption = " << opts.caption << '\n'; - if (not opts.comments.empty()) - ret << "comments = " << opts.comments << '\n'; - if (!opts.output) - ret << "output = false\n"; - - for (uint r = 0; r != opts.rules.size(); ++r) - { - const Rule& rule = opts.rules[r]; - ret << cmds[rule.first] << " = " << rule.second << '\n'; - } - ret << '\n'; - } - return ret; -} - -template -template -bool Sets::saveToFile(const StringT& filename) const -{ - using namespace Yuni; - using namespace Antares; - - IO::File::Stream file; - if (!file.open(filename, IO::OpenMode::write | IO::OpenMode::truncate)) - { - logs.error() << "I/O Error: " << filename << ": impossible to write the file"; - return false; - } - - static const char* cmds[ruleMax] = {"none", "+", "-", "apply-filter"}; - const auto end = pOptions.cend(); - for (auto i = pOptions.cbegin(); i != end; ++i) - { - const Options& opts = i->second; - file << '[' << i->first << "]\n"; - file << "caption = " << opts.caption << '\n'; - if (not opts.comments.empty()) - file << "comments = " << opts.comments << '\n'; - if (!opts.output) - file << "output = false\n"; - - for (uint r = 0; r != opts.rules.size(); ++r) - { - const Rule& rule = opts.rules[r]; - file << cmds[rule.first] << " = " << rule.second << '\n'; - } - file << '\n'; - } - return true; -} - -template -template -bool Sets::loadFromFile(const StringT& filename) -{ - using namespace Yuni; - using namespace Antares; - - // Empty the container first - clear(); - - // Loading the INI file - if (!IO::File::Exists(filename)) - // Error silently ignored - return true; - - IniFile ini; - if (ini.open(filename)) - { - Yuni::String value; - - // each section... - for (auto* section = ini.firstSection; section != nullptr; section = section->next) - { - // Clearing the name. - if (!section->name) - continue; - - // Creating a new section - auto item = std::make_shared(); - Options opts; - opts.caption = section->name; - - // each property... - const IniFile::Property* p; - for (p = section->firstProperty; p != nullptr; p = p->next) - { - if (p->key.empty()) - continue; - - value = p->value; - value.toLower(); - - if (p->key == "+") - { - opts.rules.push_back(Rule(ruleAdd, new String(value))); - continue; - } - if (p->key == "-") - { - opts.rules.push_back(Rule(ruleRemove, new String(value))); - continue; - } - if (p->key == "apply-filter") - { - opts.rules.push_back(Rule(ruleFilter, new String(value))); - continue; - } - if (p->key == "output") - { - opts.output = value.to(); - continue; - } - if (p->key == "comments") - { - opts.comments = p->value; - opts.comments.trim(" \t"); - continue; - } - if (p->key == "caption") - { - opts.caption = p->value; - continue; - } - - logs.warning() << "sets: `" << filename << "`: Invalid property `" << p->key - << '\''; - } - - // Add the new group - IDType newid = section->name; - newid.toLower(); - add(newid, item, opts); - } - - // Not modified anymore - pModified = false; - // All indexes must be rebuilt - rebuildIndexes(); - return true; - } - return false; -} - -template -template -inline void Sets::rebuildAllFromRules(HandlerT& handler) -{ - for (uint i = 0; i != pMap.size(); ++i) - rebuildFromRules(pNameByIndex[i], handler); -} - -template -template -void Sets::rebuildFromRules(const IDType& id, HandlerT& handler) -{ - using namespace Yuni; - using namespace Antares; - - typename MapOptions::iterator i = pOptions.find(id); - if (i == pOptions.end()) - return; - // Options - Options& opts = i->second; - Type& set = *(pMap[id]); - - // Clear the result first - handler.clear(set); - // Apply all rules - for (uint i = 0; i != opts.rules.size(); ++i) - { - const Rule& rule = opts.rules[i]; - const Yuni::String& arg = *(rule.second); - switch (rule.first) // type - { - case ruleAdd: - { - // Trying to add a single item - if (!handler.add(set, arg)) - { - // Failed. Maybe the argument references another group - const IDType other = arg; - typename MapType::iterator i = pMap.find(other); - if (i != pMap.end()) - { - if (handler.add(set, *(i->second))) - break; - } - } - break; - } - case ruleRemove: - { - // Trying to remove a single item - if (!handler.remove(set, arg)) - { - // Failed. Maybe the argument references another group - const IDType other = arg; - typename MapType::iterator i = pMap.find(other); - if (i != pMap.end()) - { - if (handler.remove(set, *(i->second))) - break; - } - } - break; - } - case ruleFilter: - { - handler.applyFilter(set, arg); - break; - } - case ruleNone: - case ruleMax: - { - // Huh ?? - assert(false && "Should not be here !"); - break; - } - } - } - // Retrieving the size of the result set - opts.resultSize = handler.size(set); - logs.debug() << " > set :: " << opts.caption << ": applying " << opts.rules.size() - << " rules, got " << opts.resultSize << " items"; -} - -template -void Sets::rebuildIndexes() -{ - delete[] pByIndex; - delete[] pNameByIndex; - - if (!pMap.empty()) - { - pByIndex = new TypePtr[pMap.size()]; - pNameByIndex = new IDType[pMap.size()]; - const typename MapType::iterator end = pMap.end(); - uint index = 0; - for (typename MapType::iterator i = pMap.begin(); i != end; ++i) - { - pByIndex[index] = i->second; - pNameByIndex[index] = i->first; - ++index; - } - } - else - { - pByIndex = NULL; - pNameByIndex = NULL; - } -} - -template -template -inline bool Sets::hasOutput(const StringT& s) const -{ - using namespace Yuni; - // Assert, if a C* container can not be found at compile time - YUNI_STATIC_ASSERT(Traits::CString::valid, HasOutput_InvalidTypeForBuffer); - - typename MapOptions::const_iterator i = pOptions.find(s); - return (i != pOptions.end()) ? i->second.output : false; -} - -template -inline bool Sets::hasOutput(const uint index) const -{ - return hasOutput(IDType(pNameByIndex[index])); -} - -template -template -inline uint Sets::resultSize(const StringT& s) const -{ - using namespace Yuni; - // Assert, if a C* container can not be found at compile time - YUNI_STATIC_ASSERT(Traits::CString::valid, HasOutput_InvalidTypeForBuffer); - - typename MapOptions::const_iterator i = pOptions.find(s); - return (i != pOptions.end()) ? i->second.resultSize : 0; -} - -template -template -inline typename Sets::IDType Sets::caption(const StringT& s) const -{ - using namespace Yuni; - // Assert, if a C* container can not be found at compile time - YUNI_STATIC_ASSERT(Traits::CString::valid, HasOutput_InvalidTypeForBuffer); - - typename MapOptions::const_iterator i = pOptions.find(s); - return (i != pOptions.end()) ? i->second.caption : IDType(); -} - -template -inline typename Sets::IDType Sets::caption(const uint i) const -{ - return caption(IDType(pNameByIndex[i])); -} - -template -inline uint Sets::resultSize(const uint index) const -{ - return resultSize(IDType(pNameByIndex[index])); -} - -template -inline uint Sets::size() const -{ - return (uint)pMap.size(); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_SETS_HXX__ diff --git a/src/libs/antares/study/simulation.cpp b/src/libs/antares/study/simulation.cpp index fd2534a58f..cb4465130a 100644 --- a/src/libs/antares/study/simulation.cpp +++ b/src/libs/antares/study/simulation.cpp @@ -1,38 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include "study.h" -#include "../constants.h" +#include "antares/study/simulation.h" + #include #include -#include "simulation.h" + +#include +#include + #include +#include "antares/antares/constants.h" +#include "antares/study/study.h" using namespace Yuni; @@ -42,7 +39,8 @@ namespace Antares { namespace Data { -SimulationComments::SimulationComments(Study& study) : pStudy(study) +SimulationComments::SimulationComments(Study& study): + pStudy(study) { } @@ -63,7 +61,9 @@ bool SimulationComments::saveToFolder(const AnyString& folder) const b = folder; b << SEP << "comments.txt"; if (IO::File::SetContent(b, comments)) + { return true; + } logs.error() << "I/O: impossible to write " << b; return false; } @@ -83,7 +83,9 @@ bool SimulationComments::loadFromFolder(const StudyLoadOptions& options) { pStudy.buffer.clear() << pStudy.folderSettings << SEP << "comments.txt"; if (IO::errNone != IO::File::LoadFromFile(comments, pStudy.buffer)) + { logs.warning() << pStudy.buffer << ": Impossible to read the file"; + } } return true; } diff --git a/src/libs/antares/study/simulation.h b/src/libs/antares/study/simulation.h deleted file mode 100644 index 8e3efc8f79..0000000000 --- a/src/libs/antares/study/simulation.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_SIMULATION_H__ -#define __ANTARES_LIBS_STUDY_SIMULATION_H__ - -#include -#include -#include "fwd.h" - -namespace Antares -{ -namespace Data -{ -/*! -** \brief Set of settings for a simulation -*/ -class SimulationComments final -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - SimulationComments(Study& study); - //! Destructor - ~SimulationComments() - { - } - //@} - - /*! - ** \brief Load a simulation from a folder - ** - ** \return A non-zero value if succeeded, 0 otherwise - */ - bool loadFromFolder(const StudyLoadOptions& options); - - /*! - ** \brief Save settings to the appropriate folder - */ - bool saveToFolder(const AnyString& folder) const; - - void saveUsingWriter(Solver::IResultWriter& writer, const AnyString& folder) const; - - //! Get (in bytes) the amount of memory used by the class - uint64_t memoryUsage() const; - -public: - //! Comments - YString comments; - //! name - YString name; - -private: - Study& pStudy; - -}; // class SimulationComments - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_SIMULATION_H__ diff --git a/src/libs/antares/study/study.cpp b/src/libs/antares/study/study.cpp index d46123f8dd..5b1dde8c5f 100644 --- a/src/libs/antares/study/study.cpp +++ b/src/libs/antares/study/study.cpp @@ -1,56 +1,52 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "../antares.h" -#include -#include -#include -#include -#include + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/study/study.h" -#include // std::ostringstream #include #include +#include // For use of floor(...) and ceil(...) #include +#include // std::ostringstream -#include "study.h" -#include "runtime.h" -#include "scenario-builder/sets.h" -#include "correlation-updater.hxx" -#include "scenario-builder/updater.hxx" -#include "area/constants.h" - +#include +#include #include // For use of Yuni::System::CPU::Count() -#include // For use of floor(...) and ceil(...) +#include +#include +#include + #include -#include "ui-runtimeinfos.h" +#include "antares/antares/antares.h" +#include "antares/study/area/constants.h" +#include "antares/study/correlation-updater.hxx" +#include "antares/study/runtime.h" +#include "antares/study/scenario-builder/sets.h" +#include "antares/study/scenario-builder/updater.hxx" +#include "antares/study/ui-runtimeinfos.h" +#include "antares/utils/utils.h" using namespace Yuni; +namespace fs = std::filesystem; namespace Antares::Data { @@ -69,16 +65,18 @@ static inline void FreeAndNil(T*& pointer) pointer = nullptr; } -Study::Study(bool forTheSolver) : - LayerData(0, true), - simulationComments(*this), - areas(*this), - pQueueService(std::make_shared()), - usedByTheSolver(forTheSolver) +Study::Study(bool forTheSolver): + LayerData(0, true), + simulationComments(*this), + areas(*this), + pQueueService(std::make_shared()), + usedByTheSolver(forTheSolver) { // TS generators for (uint i = 0; i != timeSeriesCount; ++i) + { cacheTSGenerator[i] = nullptr; + } // Correlation names preproLoadCorrelation.correlationName = "Correlation: Load"; @@ -132,8 +130,6 @@ void Study::clear() ClearAndShrink(folderOutput); ClearAndShrink(folderSettings); inputExtension.clear(); - - gotFatalError = false; } void Study::createAsNew() @@ -178,7 +174,9 @@ void Study::createAsNew() if (JIT::usedFromGUI) { if (not uiinfo) + { uiinfo = new UIRuntimeInfo(*this); + } uiinfo->reloadAll(); } // Reduce memory footprint @@ -219,7 +217,9 @@ std::map Study::getRawNumberCoresPerLevel() uint nbLogicalCores = Yuni::System::CPU::Count(); if (!nbLogicalCores) + { logs.fatal() << "Number of logical cores available is 0."; + } switch (nbLogicalCores) { @@ -357,28 +357,44 @@ void Study::getNumberOfCores(const bool forceParallel, const uint nbYearsParalle // In case solver option '--force-parallel n' is used, previous computation is overridden. if (forceParallel) + { maxNbYearsInParallel = nbYearsParallelForced; + } // Limiting the number of parallel years by the smallest refresh span auto& p = parameters; uint TSlimit = UINT_MAX; if ((p.timeSeriesToGenerate & timeSeriesLoad) && (p.timeSeriesToRefresh & timeSeriesLoad)) + { TSlimit = p.refreshIntervalLoad; + } if ((p.timeSeriesToGenerate & timeSeriesSolar) && (p.timeSeriesToRefresh & timeSeriesSolar)) + { TSlimit = (p.refreshIntervalSolar < TSlimit) ? p.refreshIntervalSolar : TSlimit; + } if ((p.timeSeriesToGenerate & timeSeriesHydro) && (p.timeSeriesToRefresh & timeSeriesHydro)) + { TSlimit = (p.refreshIntervalHydro < TSlimit) ? p.refreshIntervalHydro : TSlimit; + } if ((p.timeSeriesToGenerate & timeSeriesWind) && (p.timeSeriesToRefresh & timeSeriesWind)) + { TSlimit = (p.refreshIntervalWind < TSlimit) ? p.refreshIntervalWind : TSlimit; + } if ((p.timeSeriesToGenerate & timeSeriesThermal) && (p.timeSeriesToRefresh & timeSeriesThermal)) + { TSlimit = (p.refreshIntervalThermal < TSlimit) ? p.refreshIntervalThermal : TSlimit; + } if (TSlimit < maxNbYearsInParallel) + { maxNbYearsInParallel = TSlimit; + } // Limiting the number of parallel years by the total number of years if (p.nbYears < maxNbYearsInParallel) + { maxNbYearsInParallel = p.nbYears; + } // Getting the minimum number of years in a set of parallel years. // To get this number, we have to divide all years into sets of parallel @@ -392,7 +408,9 @@ void Study::getNumberOfCores(const bool forceParallel, const uint nbYearsParalle { bool performCalculations = true; if (p.userPlaylist) + { performCalculations = p.yearsFilter[y]; + } // Do we have to refresh ? bool refreshing = false; @@ -432,13 +450,19 @@ void Study::getNumberOfCores(const bool forceParallel, const uint nbYearsParalle } if (performCalculations) + { set->push_back(y); + } // Do we build a new set at next iteration (for years to be executed or not) ? if (set->size() == maxNbYearsInParallel) + { buildNewSet = true; + } else + { buildNewSet = false; + } } // End of loop over years // Now finding the smallest size among all sets. @@ -449,7 +473,9 @@ void Study::getNumberOfCores(const bool forceParallel, const uint nbYearsParalle // Empty sets are not taken into account because, on the solver side, // they will contain only skipped years if (setSize && (setSize < minNbYearsInParallel)) + { minNbYearsInParallel = setSize; + } } // GUI : storing minimum number of parallel years (in a set of parallel years). @@ -464,7 +490,9 @@ void Study::getNumberOfCores(const bool forceParallel, const uint nbYearsParalle for (uint s = 0; s < setsOfParallelYears.size(); s++) { if (setsOfParallelYears[s].size() > maxNbYearsOverAllSets) + { maxNbYearsOverAllSets = (uint)setsOfParallelYears[s].size(); + } } maxNbYearsInParallel = maxNbYearsOverAllSets; @@ -472,93 +500,6 @@ void Study::getNumberOfCores(const bool forceParallel, const uint nbYearsParalle // enabled. // Useful for RAM estimation. maxNbYearsInParallel_save = maxNbYearsInParallel; - - // Here we answer the question (useful only if hydro hot start is asked) : do all sets of - // parallel years have the same size ? - if (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart - && setsOfParallelYears.size() && maxNbYearsInParallel > 1) - { - uint currentSetSize = (uint)setsOfParallelYears[0].size(); - if (setsOfParallelYears.size() > 1) - { - for (uint s = 1; s < setsOfParallelYears.size(); s++) - { - if (setsOfParallelYears[s].size() != currentSetSize) - { - parameters.allSetsHaveSameSize = false; - break; - } - } - } - } // End if hot start -} - -bool Study::checkHydroHotStart() -{ - bool hydroHotStart = (parameters.initialReservoirLevels.iniLevels == irlHotStart); - - // No need to check further if hydro hot start is not required - if (!hydroHotStart) - return true; - - // Here we answer the question (useful only if hydro hot start is asked) : In case of parallel - // run, do all sets of parallel years have the same size ? - if (maxNbYearsInParallel != 1 && !parameters.allSetsHaveSameSize) - { - logs.error() << "Hot Start Hydro option : conflict with parallelization parameters."; - logs.error() - << "Please update relevant simulation parameters or use Cold Start option. "; - return false; - } - - // Checking calendar conditions - // ... The simulation lasts one year exactly - uint nbDaysInSimulation = parameters.simulationDays.end - parameters.simulationDays.first + 1; - if (nbDaysInSimulation < 364) - { - logs.error() - << "Hot Start Hydro option : simulation calendar must cover one complete year. "; - logs.error() << "Please update data or use Cold Start option."; - return false; - } - - // ... For all areas for which reservoir management is enabled : - // - Their starting level is initialized on the same day - // - This day is the first day of the simulation calendar - const Area::Map::iterator end = areas.end(); - for (Area::Map::iterator i = areas.begin(); i != end; ++i) - { - // Reference to the area - Area* area = i->second; - - // No need to make a check on level initialization when reservoir management - // is not activated for the current area - if (!area->hydro.reservoirManagement) - continue; - - // Month the reservoir level is initialized according to. - // This month number is given in the civil calendar, from january to december (0 is - // january). - int initLevelOnMonth = area->hydro.initializeReservoirLevelDate; - - // Conversion of the previous month into simulation calendar - uint initLevelOnSimMonth = calendar.mapping.months[initLevelOnMonth]; - - // Previous month's first day in the year - uint initLevelOnSimDay = calendar.months[initLevelOnSimMonth].daysYear.first; - - // Check the day of level initialization is the first day of simulation - if (initLevelOnSimDay != parameters.simulationDays.first) - { - logs.error() - << "Hot Start Hydro option : area '" << area->name - << "' - hydro level must be initialized on the first simulation month. "; - logs.error() << "Please update data or use Cold Start option."; - return false; - } - } // End loop over areas - - return true; } bool Study::initializeRuntimeInfos() @@ -578,35 +519,37 @@ void Study::performTransformationsBeforeLaunchingSimulation() #endif // ForEach area - areas.each([&](Data::Area& area) { - if (not parameters.geographicTrimming) - { - // reset filtering - area.filterSynthesis = (uint)filterAll; - area.filterYearByYear = (uint)filterAll; - } - - // Informations about time-series for the load - auto& matrix = area.load.series->timeSeries; - auto& dsmvalues = area.reserves[fhrDSM]; - - // Adding DSM values - for (uint timeSeries = 0; timeSeries < matrix.width; ++timeSeries) - { - auto& perHour = matrix[timeSeries]; - for (uint h = 0; h < matrix.height; ++h) - { - perHour[h] += dsmvalues[h]; - // MBO - 13/05/2014 - #20 - // Starting v4.5 load can be negative - /*if (perHour[h] < 0.) - { - logs.warning() << area.id << ", hour " << h << ": `load - dsm` can not be - negative. Reset to 0"; perHour[h] = 0.; - }*/ - } - } - }); + areas.each( + [this](Data::Area& area) + { + if (not parameters.geographicTrimming) + { + // reset filtering + area.filterSynthesis = (uint)filterAll; + area.filterYearByYear = (uint)filterAll; + } + + // Informations about time-series for the load + auto& matrix = area.load.series.timeSeries; + auto& dsmvalues = area.reserves[fhrDSM]; + + // Adding DSM values + for (uint timeSeries = 0; timeSeries < matrix.width; ++timeSeries) + { + auto& perHour = matrix[timeSeries]; + for (uint h = 0; h < matrix.height; ++h) + { + perHour[h] += dsmvalues[h]; + // MBO - 13/05/2014 - #20 + // Starting v4.5 load can be negative + /*if (perHour[h] < 0.) + { + logs.warning() << area.id << ", hour " << h << ": `load - dsm` can not be + negative. Reset to 0"; perHour[h] = 0.; + }*/ + } + } + }); } // This function is a helper. It should be completed when adding new formats @@ -621,12 +564,17 @@ static std::string getOutputSuffix(ResultFormat fmt) } } -YString StudyCreateOutputPath(StudyMode mode, +YString StudyCreateOutputPath(SimulationMode mode, ResultFormat fmt, const YString& outputRoot, const YString& label, int64_t startTime) { + if (fmt == ResultFormat::inMemory) + { + return "no_output"; + } + auto suffix = getOutputSuffix(fmt); YString folderOutput; @@ -638,41 +586,36 @@ YString StudyCreateOutputPath(StudyMode mode, switch (mode) { - case stdmEconomy: + case SimulationMode::Economy: folderOutput += "eco"; break; - case stdmAdequacy: + case SimulationMode::Adequacy: folderOutput += "adq"; break; - case stdmUnknown: - case stdmExpansion: - case stdmMax: + case SimulationMode::Expansion: + folderOutput += "exp"; + break; + case SimulationMode::Unknown: break; } - // Temporary buffer - String buffer; - buffer.reserve(1024); - // Folder output if (not label.empty()) { - buffer.clear(); - TransformNameIntoID(label, buffer); - folderOutput << '-' << buffer; + folderOutput << '-' << transformNameIntoID(label); } - buffer.clear() << folderOutput << suffix; + std::string outpath = folderOutput + suffix; // avoid creating the same output twice - if (IO::Exists(buffer)) + if (fs::exists(outpath)) { - String newpath; + std::string newpath; uint index = 1; // will start from 2 do { ++index; - newpath.clear() << folderOutput << '-' << index << suffix; - } while (IO::Exists(newpath) and index < 2000); + newpath = folderOutput + '-' + std::to_string(index) + suffix; + } while (fs::exists(newpath) and index < 2000); folderOutput << '-' << index; } @@ -684,12 +627,17 @@ void Study::prepareOutput() pStartTime = DateTime::Now(); if (parameters.noOutput || !usedByTheSolver) + { return; + } buffer.clear() << folder << SEP << "output"; - folderOutput = StudyCreateOutputPath( - parameters.mode, parameters.resultFormat, buffer, simulationComments.name, pStartTime); + folderOutput = StudyCreateOutputPath(parameters.mode, + parameters.resultFormat, + buffer, + simulationComments.name, + pStartTime); logs.info() << " Output folder : " << folderOutput; } @@ -708,9 +656,7 @@ void Study::saveAboutTheStudy(Solver::IResultWriter& resultWriter) Antares::IniFile ini; header.CopySettingsToIni(ini, false); - std::string writeBuffer; - ini.saveToString(writeBuffer); - + std::string writeBuffer = ini.toString(); resultWriter.addEntryFromBuffer(path.c_str(), writeBuffer); } @@ -729,9 +675,9 @@ void Study::saveAboutTheStudy(Solver::IResultWriter& resultWriter) String startTimeStr; DateTime::TimestampToString(startTimeStr, "%Y.%m.%d - %H:%M", pStartTime); f << "[general]"; - f << "\nversion = " << (uint)Data::versionLatest; + f << "\nversion = " << StudyVersion::latest().toString(); f << "\nname = " << simulationComments.name; - f << "\nmode = " << StudyModeToCString(parameters.mode); + f << "\nmode = " << SimulationModeToCString(parameters.mode); f << "\ndate = " << startTimeStr; f << "\ntitle = " << startTimeStr; f << "\ntimestamp = " << pStartTime; @@ -748,9 +694,11 @@ void Study::saveAboutTheStudy(Solver::IResultWriter& resultWriter) for (auto i = setsOfAreas.begin(); i != setsOfAreas.end(); ++i) { if (setsOfAreas.hasOutput(i->first)) + { buffer << "@ " << i->first << "\r\n"; + } } - areas.each([&](const Data::Area& area) { buffer << area.name << "\r\n"; }); + areas.each([&buffer](const Data::Area& area) { buffer << area.name << "\r\n"; }); resultWriter.addEntryFromBuffer(path.c_str(), buffer); } @@ -767,7 +715,9 @@ void Study::saveAboutTheStudy(Solver::IResultWriter& resultWriter) Area* Study::areaAdd(const AreaName& name, bool updateMode) { if (name.empty()) + { return nullptr; + } if (CheckForbiddenCharacterInAreaName(name)) { logs.error() << "character '*' is forbidden in area name: `" << name << "`"; @@ -803,7 +753,9 @@ Area* Study::areaAdd(const AreaName& name, bool updateMode) // Adding an area area = addAreaToListOfAreas(areas, newName); if (not area) + { return nullptr; + } // Rebuild indexes for all areas areas.rebuildIndexes(); @@ -814,16 +766,22 @@ Area* Study::areaAdd(const AreaName& name, bool updateMode) } if (uiinfo) + { uiinfo->reload(); + } return area; } bool Study::areaDelete(Area* area) { if (not area) + { return true; + } if (not AreaListLFind(&areas, area->id.c_str())) + { return false; + } logs.info() << "destroying the area: " << area->name; @@ -831,7 +789,7 @@ bool Study::areaDelete(Area* area) // and the scenario builder data *before* reloading uiinfo. { // Updating all hydro allocation - areas.each([&](Data::Area& areait) { areait.hydro.allocation.remove(area->id); }); + areas.each([&area](Data::Area& areait) { areait.hydro.allocation.remove(area->id); }); // We __must__ update the scenario builder data // We may delete an area and re-create a new one with the same @@ -855,16 +813,22 @@ bool Study::areaDelete(Area* area) } if (uiinfo) + { uiinfo->reloadAll(); + } return true; } void Study::areaDelete(Area::Vector& arealist) { if (arealist.empty()) + { return; + } if (arealist.size() > 1) + { logs.info() << "destroying " << arealist.size() << " areas..."; + } // The new scope is mandatory to rebuild the correlation matrices // and the scenario builder data @@ -892,7 +856,8 @@ void Study::areaDelete(Area::Vector& arealist) << area.name; // Updating all hydro allocation - areas.each([&](Data::Area& areait) { areait.hydro.allocation.remove(area.id); }); + areas.each([&area](Data::Area& areait) + { areait.hydro.allocation.remove(area.id); }); // Remove all binding constraints attached to the area bindingConstraints.remove(*i); @@ -906,10 +871,14 @@ void Study::areaDelete(Area::Vector& arealist) } if (uiinfo) + { uiinfo->reloadAll(); + } if (arealist.size() > 1) + { logs.info() << arealist.size() << " areas have been destroyed"; + } } bool Study::linkDelete(AreaLink* lnk) @@ -917,7 +886,9 @@ bool Study::linkDelete(AreaLink* lnk) // Impossible to find the attached area // The link might be already deleted if (not lnk or !AreaListFindPtr(&areas, lnk->from) or !AreaListFindPtr(&areas, lnk->with)) + { return false; + } assert(lnk->with); assert(lnk->from); @@ -929,7 +900,9 @@ bool Study::linkDelete(AreaLink* lnk) AreaLinkRemove(lnk); if (uiinfo) + { uiinfo->reloadAll(); + } return true; } @@ -937,19 +910,24 @@ bool Study::areaRename(Area* area, AreaName newName) { // A name must not be empty if (not area or newName.empty()) + { return false; + } String beautifyname; BeautifyName(beautifyname, newName); if (beautifyname.empty()) + { return false; + } newName = beautifyname; // Preparing the new area ID - AreaName newid; - TransformNameIntoID(newName, newid); + AreaName newid = transformNameIntoID(newName); if (newid.empty()) + { return false; + } // Checking if the area exists { @@ -978,7 +956,8 @@ bool Study::areaRename(Area* area, AreaName newName) logs.info() << "renaming area " << area->name << " into " << newName; // Updating all hydro allocation - areas.each([&](Data::Area& areait) { areait.hydro.allocation.rename(oldid, newid); }); + areas.each([&oldid, &newid](Data::Area& areait) + { areait.hydro.allocation.rename(oldid, newid); }); ScenarioBuilderUpdater updaterSB(*this); bool ret = true; @@ -1002,7 +981,9 @@ bool Study::areaRename(Area* area, AreaName newName) areas.fixOrientationForAllInterconnections(bindingConstraints); if (uiinfo) + { uiinfo->reloadAll(); + } return ret; } @@ -1010,18 +991,21 @@ bool Study::areaRename(Area* area, AreaName newName) bool Study::clusterRename(Cluster* cluster, ClusterName newName) { // A name must not be empty - if (!cluster or !newName.empty()) + if (!cluster or newName.empty()) + { return false; + } String beautifyname; BeautifyName(beautifyname, newName); if (!beautifyname) + { return false; + } newName = beautifyname.c_str(); // Preparing the new area ID - ClusterName newID; - TransformNameIntoID(newName, newID); + ClusterName newID = transformNameIntoID(newName); if (newID.empty()) { logs.error() << "invalid id transformation"; @@ -1043,17 +1027,16 @@ bool Study::clusterRename(Cluster* cluster, ClusterName newName) kThermal, kRenewable, kUnknown - } type - = kUnknown; + } type = kUnknown; if (dynamic_cast(cluster)) { - found = area.thermal.list.find(newID); + found = area.thermal.list.findInAll(newID); type = kThermal; } else if (dynamic_cast(cluster)) { - found = area.renewable.list.find(newID); + found = area.renewable.list.findInAll(newID); type = kRenewable; } @@ -1086,11 +1069,9 @@ bool Study::clusterRename(Cluster* cluster, ClusterName newName) { case kRenewable: ret = area.renewable.list.rename(cluster->id(), newName); - area.renewable.prepareAreaWideIndexes(); break; case kThermal: ret = area.thermal.list.rename(cluster->id(), newName); - area.thermal.prepareAreaWideIndexes(); break; case kUnknown: logs.error() << "Unknown cluster type"; @@ -1100,49 +1081,53 @@ bool Study::clusterRename(Cluster* cluster, ClusterName newName) ScenarioBuilderUpdater updaterSB(*this); if (uiinfo) + { uiinfo->reloadAll(); + } return ret; } void Study::destroyAllLoadTSGeneratorData() { - areas.each([&](Data::Area& area) { FreeAndNil(area.load.prepro); }); + areas.each([](Data::Area& area) { FreeAndNil(area.load.prepro); }); } void Study::destroyAllSolarTSGeneratorData() { - areas.each([&](Data::Area& area) { FreeAndNil(area.solar.prepro); }); + areas.each([](Data::Area& area) { FreeAndNil(area.solar.prepro); }); } void Study::destroyAllHydroTSGeneratorData() { - areas.each([&](Data::Area& area) { FreeAndNil(area.hydro.prepro); }); + areas.each([](Data::Area& area) { FreeAndNil(area.hydro.prepro); }); } void Study::destroyAllWindTSGeneratorData() { - areas.each([&](Data::Area& area) { FreeAndNil(area.wind.prepro); }); + areas.each([](Data::Area& area) { FreeAndNil(area.wind.prepro); }); } void Study::destroyAllThermalTSGeneratorData() { - areas.each([&](Data::Area& area) { - auto pend = area.thermal.list.end(); - for (auto j = area.thermal.list.begin(); j != pend; ++j) - { - ThermalCluster& cluster = *(j->second); - FreeAndNil(cluster.prepro); - } - }); + areas.each( + [](const Data::Area& area) + { + for (const auto& cluster: area.thermal.list.each_enabled_and_not_mustrun()) + { + FreeAndNil(cluster->prepro); + } + }); } void Study::ensureDataAreLoadedForAllBindingConstraints() { - for(const auto& constraint: bindingConstraints) + for (const auto& constraint: bindingConstraints) { if (not JIT::IsReady(constraint->RHSTimeSeries().jit)) + { constraint->forceReload(true); + } } } @@ -1154,7 +1139,9 @@ struct TS final static bool IsNeeded(const Study& s, const uint y) { if (not(T & s.parameters.timeSeriesToRefresh)) + { return false; + } switch (T) { @@ -1203,21 +1190,27 @@ void Study::initializeProgressMeter(bool tsGeneratorOnly) { n = parameters.nbTimeSeriesLoad * areas.size() * 365; if (0 != (timeSeriesLoad & parameters.timeSeriesToArchive)) + { n += (int)areas.size(); + } progression.add(y, Solver::Progression::sectTSGLoad, n); } if (TS::IsNeeded(*this, y)) { n = parameters.nbTimeSeriesSolar * areas.size() * 365; if (0 != (timeSeriesSolar & parameters.timeSeriesToArchive)) + { n += (int)areas.size(); + } progression.add(y, Solver::Progression::sectTSGSolar, n); } if (TS::IsNeeded(*this, y)) { n = parameters.nbTimeSeriesWind * areas.size() * 365; if (0 != (timeSeriesWind & parameters.timeSeriesToArchive)) + { n += (int)areas.size(); + } progression.add(y, Solver::Progression::sectTSGWind, n); } if (TS::IsNeeded(*this, y)) @@ -1225,7 +1218,9 @@ void Study::initializeProgressMeter(bool tsGeneratorOnly) // n += parameters.nbTimeSeriesHydro * areas.size() * 12; n = parameters.nbTimeSeriesHydro; if (0 != (timeSeriesHydro & parameters.timeSeriesToArchive)) + { n += (int)areas.size(); + } progression.add(y, Solver::Progression::sectTSGHydro, n); } if (TS::IsNeeded(*this, y)) @@ -1242,7 +1237,9 @@ void Study::initializeProgressMeter(bool tsGeneratorOnly) progression.add(y, Solver::Progression::sectYear, ticksPerYear); if (parameters.yearByYear) + { progression.add(y, Solver::Progression::sectOutput, ticksPerOutput); + } } // Output @@ -1251,17 +1248,29 @@ void Study::initializeProgressMeter(bool tsGeneratorOnly) // Import n = 0; if (0 != (timeSeriesLoad & parameters.exportTimeSeriesInInput)) + { n += (int)areas.size(); + } if (0 != (timeSeriesSolar & parameters.exportTimeSeriesInInput)) + { n += (int)areas.size(); + } if (0 != (timeSeriesWind & parameters.exportTimeSeriesInInput)) + { n += (int)areas.size(); + } if (0 != (timeSeriesHydro & parameters.exportTimeSeriesInInput)) + { n += (int)areas.size(); + } if (0 != (timeSeriesThermal & parameters.exportTimeSeriesInInput)) + { n += (int)areas.size(); + } if (n) + { progression.add(Solver::Progression::sectImportTS, n); + } // Needed by the progression meter thread to retrieve properly // messages from all MC years @@ -1302,7 +1311,7 @@ void Study::markAsModified() const setsOfLinks.markAsModified(); } -void Study::relocate(AnyString newFolder) +void Study::relocate(const std::string& newFolder) { folder = newFolder; folderInput.clear() << newFolder << SEP << "input"; @@ -1329,41 +1338,48 @@ bool Study::checkForFilenameLimits(bool output, const String& chfolder) const }; if (areas.empty()) + { return true; + } String studyfolder; if (chfolder.empty()) + { studyfolder = folder; + } else + { studyfolder = chfolder; + } if (output) { String linkname; String areaname; - areas.each([&](const Area& area) { - if (areaname.size() < area.id.size()) - areaname = area.id; - - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - { - auto& link = *(i->second); - uint len = link.from->id.size() + link.with->id.size(); - len += output ? 3 : 1; - if (len > linkname.size()) - { - linkname.clear(); - linkname << i->second->from->id; - if (output) - linkname << " - "; // 3 - else - linkname << SEP; - linkname << i->second->with->id; - } - } - }); + areas.each( + [&output, &linkname, &areaname](const Area& area) + { + if (areaname.size() < area.id.size()) + { + areaname = area.id; + } + + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + auto& link = *(i->second); + uint len = link.from->id.size() + link.with->id.size(); + len += 3; + if (len > linkname.size()) + { + linkname.clear(); + linkname << i->second->from->id; + linkname << " - "; // 3 + linkname << i->second->with->id; + } + } + }); String filename; filename << studyfolder << SEP << "output" << SEP; @@ -1371,7 +1387,9 @@ bool Study::checkForFilenameLimits(bool output, const String& chfolder) const if (linkname.empty()) { if (areaname.empty()) + { filename.clear(); + } else { // no links : obtained from areas @@ -1412,17 +1430,24 @@ bool Study::checkForFilenameLimits(bool output, const String& chfolder) const // /input/hydro/common/capacity/maxcapacityexpectation_languedocroussillon.txt // or even constraints - areas.each([&](const Area& area) { - if (areaname.size() < area.id.size()) - areaname = area.id; - auto& cname = clustername; - cname.clear(); - - area.thermal.list.each([&](const Cluster& cluster) { - if (cluster.id().size() > cname.size()) - cname = cluster.id(); - }); - }); + areas.each( + [&areaname, &clustername](const Area& area) + { + if (areaname.size() < area.id.size()) + { + areaname = area.id; + } + auto& cname = clustername; + cname.clear(); + + for (auto& cluster: area.thermal.list.all()) + { + if (cluster->id().size() > cname.size()) + { + cname = cluster->id(); + } + } + }); String filename; @@ -1512,15 +1537,25 @@ void Study::removeTimeseriesIfTSGeneratorEnabled() if (0 != parameters.timeSeriesToGenerate) { if (0 != (parameters.timeSeriesToGenerate & timeSeriesLoad)) + { areas.removeLoadTimeseries(); + } if (0 != (parameters.timeSeriesToGenerate & timeSeriesHydro)) + { areas.removeHydroTimeseries(); + } if (0 != (parameters.timeSeriesToGenerate & timeSeriesSolar)) + { areas.removeSolarTimeseries(); + } if (0 != (parameters.timeSeriesToGenerate & timeSeriesWind)) + { areas.removeWindTimeseries(); + } if (0 != (parameters.timeSeriesToGenerate & timeSeriesThermal)) + { areas.removeThermalTimeseries(); + } } } @@ -1531,16 +1566,14 @@ void Study::computePThetaInfForThermalClusters() const // Alias de la zone courant const auto& area = *(this->areas.byIndex[i]); - for (uint j = 0; j < area.thermal.list.size(); j++) + for (auto& cluster: area.thermal.list.each_enabled_and_not_mustrun()) { - // Alias du cluster courant - auto& cluster = area.thermal.list.byIndex[j]; for (uint k = 0; k < HOURS_PER_YEAR; k++) + { cluster->PthetaInf[k] = cluster->modulation[Data::thermalMinGenModulation][k] * cluster->unitCount * cluster->nominalCapacity; + } } } } - } // namespace Antares::Data - diff --git a/src/libs/antares/study/study.extra.cpp b/src/libs/antares/study/study.extra.cpp index 70862ee598..1ec628c321 100644 --- a/src/libs/antares/study/study.extra.cpp +++ b/src/libs/antares/study/study.extra.cpp @@ -1,39 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/study.h" + #include -#include "study.h" -#include "scenario-builder/sets.h" + +#include "antares/study/scenario-builder/sets.h" using namespace Yuni; -namespace Antares -{ -namespace Data +namespace Antares::Data { // The path to the Icon file to use when writing a study String StudyIconFile; @@ -147,7 +141,9 @@ bool Study::IsInsideStudyFolder(const AnyString& path, String& location, String& // Looking for the next folder separator p = path.find(IO::Separator, offset); if (p >= path.size()) + { return false; + } AnyString tmp(path, 0, p); if (!tmp.empty()) @@ -164,5 +160,4 @@ bool Study::IsInsideStudyFolder(const AnyString& path, String& location, String& return false; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/study.hxx b/src/libs/antares/study/study.hxx deleted file mode 100644 index 0af64811b4..0000000000 --- a/src/libs/antares/study/study.hxx +++ /dev/null @@ -1,73 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_STUDY_HXX__ -#define __ANTARES_LIBS_STUDY_STUDY_HXX__ - -namespace Antares -{ -namespace Data -{ -inline bool Study::readonly() const -{ - return (parameters.readonly); -} - -template -inline void Study::storeTimeSeriesNumbers(Solver::IResultWriter& resultWriter) const -{ - storeTimeseriesNumbers(resultWriter, areas); -} - -template -inline void Study::destroyTSGeneratorData() -{ - switch (TS) - { - case TimeSeriesType::timeSeriesLoad: - destroyAllLoadTSGeneratorData(); - break; - case TimeSeriesType::timeSeriesSolar: - destroyAllSolarTSGeneratorData(); - break; - case TimeSeriesType::timeSeriesWind: - destroyAllWindTSGeneratorData(); - break; - case TimeSeriesType::timeSeriesHydro: - destroyAllHydroTSGeneratorData(); - break; - case TimeSeriesType::timeSeriesThermal: - destroyAllThermalTSGeneratorData(); - break; - case TimeSeriesType::timeSeriesCount: - break; - } -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_STUDY_HXX__ diff --git a/src/libs/antares/study/study.importprepro.cpp b/src/libs/antares/study/study.importprepro.cpp index 5c3499a64b..f7c8082050 100644 --- a/src/libs/antares/study/study.importprepro.cpp +++ b/src/libs/antares/study/study.importprepro.cpp @@ -1,46 +1,39 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "study.h" -#include +#include "antares/study/study.h" + +#include using namespace Yuni; #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data { bool Study::importTimeseriesIntoInput() { // Special case: some thermal clusters may force TS generation - const bool importThermal - = parameters.haveToImport(timeSeriesThermal) && runtime->thermalTSRefresh; + const bool importThermal = parameters.haveToImport(timeSeriesThermal) + && runtime->thermalTSRefresh; // Something to import ? if ((parameters.exportTimeSeriesInInput && parameters.timeSeriesToGenerate) || importThermal) { @@ -57,49 +50,52 @@ bool Study::importTimeseriesIntoInput() if (parameters.haveToImport(timeSeriesLoad)) { logs.info() << "Importing load timeseries..."; - areas.each([&](const Data::Area& area) { - logs.info() << "Importing load timeseries : " << area.name; + for (const auto& [areaName, area]: areas) + { + logs.info() << "Importing load timeseries : " << areaName; buffer.clear() << folderInput << SEP << "load" << SEP << "series"; - ret = DataSeriesLoadSaveToFolder(area.load.series, area.id, buffer.c_str()) && ret; + ret = area->load.series.saveToFolder(area->id, buffer.c_str(), "load_") && ret; ++progression; - }); + } } // Solar if (parameters.haveToImport(timeSeriesSolar)) { logs.info() << "Importing solar timeseries..."; - areas.each([&](const Data::Area& area) { - logs.info() << "Importing solar timeseries : " << area.name; + for (const auto& [areaName, area]: areas) + { + logs.info() << "Importing solar timeseries : " << areaName; buffer.clear() << folderInput << SEP << "solar" << SEP << "series"; - ret - = DataSeriesSolarSaveToFolder(area.solar.series, area.id, buffer.c_str()) && ret; + ret = area->solar.series.saveToFolder(area->id, buffer.c_str(), "solar_") && ret; ++progression; - }); + } } // Hydro if (parameters.haveToImport(timeSeriesHydro)) { logs.info() << "Importing hydro timeseries..."; - areas.each([&](const Data::Area& area) { - logs.info() << "Importing hydro timeseries : " << area.name; + for (const auto& [areaName, area]: areas) + { + logs.info() << "Importing hydro timeseries : " << areaName; buffer.clear() << folderInput << SEP << "hydro" << SEP << "series"; - ret = area.hydro.series->saveToFolder(area.id, buffer) && ret; + ret = area->hydro.series->saveToFolder(area->id, buffer) && ret; ++progression; - }); + } } // Wind if (parameters.haveToImport(timeSeriesWind)) { logs.info() << "Importing wind timeseries..."; - areas.each([&](const Data::Area& area) { - logs.info() << "Importing wind timeseries : " << area.name; + for (const auto& [areaName, area]: areas) + { + logs.info() << "Importing wind timeseries : " << areaName; buffer.clear() << folderInput << SEP << "wind" << SEP << "series"; - ret = DataSeriesWindSaveToFolder(area.wind.series, area.id, buffer.c_str()) && ret; + area->wind.series.saveToFolder(area->id, buffer.c_str(), "wind_") && ret; ++progression; - }); + } } // Thermal @@ -108,17 +104,17 @@ bool Study::importTimeseriesIntoInput() logs.info() << "Importing thermal timeseries..."; String msg; - areas.each([&](Data::Area& area) { - msg.clear() << "Importing thermal timeseries : " << area.name; + for (const auto& [areaName, area]: areas) + { + msg.clear() << "Importing thermal timeseries : " << areaName; // Spinning - area.thermal.list.reverseCalculationOfSpinning(); - area.thermal.mustrunList.reverseCalculationOfSpinning(); + area->thermal.list.reverseCalculationOfSpinning(); buffer.clear() << folderInput << SEP << "thermal" << SEP << "series"; - ret = area.thermal.list.saveDataSeriesToFolder(buffer.c_str(), msg) && ret; + ret = area->thermal.list.saveDataSeriesToFolder(buffer.c_str()) && ret; ++progression; - }); + } } return ret; @@ -126,5 +122,4 @@ bool Study::importTimeseriesIntoInput() return true; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/ui-runtimeinfos.cpp b/src/libs/antares/study/ui-runtimeinfos.cpp index 0ba362f828..5140656226 100644 --- a/src/libs/antares/study/ui-runtimeinfos.cpp +++ b/src/libs/antares/study/ui-runtimeinfos.cpp @@ -1,41 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/study/ui-runtimeinfos.h" + #include -#include "study.h" -#include "ui-runtimeinfos.h" + +#include "antares/study/study.h" using namespace Yuni; -namespace Antares -{ -namespace Data +namespace Antares::Data { -UIRuntimeInfo::UIRuntimeInfo(Study& study) : pStudy(study) +UIRuntimeInfo::UIRuntimeInfo(Study& study): + pStudy(study) { reloadAll(); } @@ -77,13 +72,14 @@ void UIRuntimeInfo::reload() { const AreaLink::Map::iterator end = area->links.end(); for (AreaLink::Map::iterator i = area->links.begin(); i != end; ++i) + { set.insert(i->second); + } } - for (uint j = 0; j < area->thermal.clusterCount(); ++j) + for (auto& cluster: area->thermal.list.each_enabled()) { - ThermalCluster* cluster = area->thermal.clusters[j]; - pClusters.push_back(cluster); + pClusters.push_back(cluster.get()); } } } @@ -117,7 +113,8 @@ void UIRuntimeInfo::reloadBindingConstraints() { const auto end = pStudy.bindingConstraints.end(); auto i = pStudy.bindingConstraints.begin(); - for (; i != end; ++i) { + for (; i != end; ++i) + { auto bc = *i; orderedConstraint.insert(bc); } @@ -158,7 +155,9 @@ uint UIRuntimeInfo::countItems(BindingConstraint::Operator op, BindingConstraint { VectorByType::const_iterator j = i->second.find(type); if (j != i->second.end()) + { return (uint)j->second.size(); + } } return 0; } @@ -170,7 +169,9 @@ uint UIRuntimeInfo::visibleClustersCount(uint layerID) for (auto cluster = pClusters.begin(); cluster != cEnd; cluster++) { if ((*cluster)->isVisibleOnLayer(layerID)) + { count++; + } } return count; } @@ -182,10 +183,11 @@ uint UIRuntimeInfo::visibleLinksCount(uint layerID) for (auto link = pLink.begin(); link != lEnd; link++) { if ((*link)->isVisibleOnLayer(layerID)) + { count++; + } } return count; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/variable-print-info.cpp b/src/libs/antares/study/variable-print-info.cpp index 1b5e20281c..e27d121d13 100644 --- a/src/libs/antares/study/variable-print-info.cpp +++ b/src/libs/antares/study/variable-print-info.cpp @@ -1,46 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "variable-print-info.h" +#include "antares/study/variable-print-info.h" + #include -#include +#include + #include -#include "../solver/variable/categories.h" +#include "antares/solver/variable/categories.h" using namespace Antares::Solver::Variable; -namespace Antares -{ -namespace Data +namespace Antares::Data { // ============================================================ // One variable print information // ============================================================ -VariablePrintInfo::VariablePrintInfo(uint dataLvl, uint fileLvl) : +VariablePrintInfo::VariablePrintInfo(uint dataLvl, uint fileLvl): to_be_printed_(true), dataLevel_(dataLvl), fileLevel_(fileLvl) @@ -51,6 +45,7 @@ void VariablePrintInfo::enablePrint(bool b) { to_be_printed_ = b; } + bool VariablePrintInfo::isPrinted() const { return to_be_printed_; @@ -60,6 +55,7 @@ void VariablePrintInfo::reverse() { to_be_printed_ = !to_be_printed_; } + uint VariablePrintInfo::getMaxColumnsCount() { return maxNumberColumns_; @@ -73,14 +69,12 @@ void VariablePrintInfo::setMaxColumns(uint maxColumnsNumber) // ============================================================ // Variables print information collector // ============================================================ -variablePrintInfoCollector::variablePrintInfoCollector(AllVariablesPrintInfo* allvarsprintinfo) : - allvarsinfo(allvarsprintinfo) +variablePrintInfoCollector::variablePrintInfoCollector(AllVariablesPrintInfo* allvarsprintinfo): + allvarsinfo(allvarsprintinfo) { } -void variablePrintInfoCollector::add(const AnyString& name, - uint dataLevel, - uint fileLevel) +void variablePrintInfoCollector::add(const AnyString& name, uint dataLevel, uint fileLevel) { allvarsinfo->add(name.to(), VariablePrintInfo(dataLevel, fileLevel)); } @@ -154,9 +148,11 @@ void AllVariablesPrintInfo::prepareForSimulation(bool isThematicTrimmingEnabled, { // Initializing output variables status if (!isThematicTrimmingEnabled) + { setAllPrintStatusesTo(true); + } - for (const auto& varname : excluded_vars) + for (const auto& varname: excluded_vars) { setPrintStatus(varname, false); // varname is supposed to in uppercase already } @@ -173,36 +169,36 @@ bool AllVariablesPrintInfo::isPrinted(std::string var_name) const void AllVariablesPrintInfo::setAllPrintStatusesTo(bool b) { - for (auto& [name, variable] : allVarsPrintInfo) + for (auto& [name, variable]: allVarsPrintInfo) { variable.enablePrint(b); } - } void AllVariablesPrintInfo::reverseAll() { - for (auto& [name, variable] : allVarsPrintInfo) + for (auto& [name, variable]: allVarsPrintInfo) { variable.reverse(); } - } unsigned int AllVariablesPrintInfo::numberOfEnabledVariables() { - return std::count_if(allVarsPrintInfo.begin(), - allVarsPrintInfo.end(), - [](auto& p) {return p.second.isPrinted(); }); + return std::count_if(allVarsPrintInfo.begin(), + allVarsPrintInfo.end(), + [](auto& p) { return p.second.isPrinted(); }); } std::vector AllVariablesPrintInfo::namesOfVariablesWithPrintStatus(bool printStatus) { std::vector vector_to_return; - for (auto& [name, variable] : allVarsPrintInfo) + for (auto& [name, variable]: allVarsPrintInfo) { if (variable.isPrinted() == printStatus) + { vector_to_return.push_back(name); + } } return vector_to_return; } @@ -224,30 +220,30 @@ void AllVariablesPrintInfo::computeMaxColumnsCountInReports() number of columns and especially what is this number ? If there are some unselected variables, the previous number is reduced. Note that synthesis reports always contain more columns than year by year reports. - So the computed max number of columns is actually the max number of columns in a synthesis report. + So the computed max number of columns is actually the max number of columns in a synthesis + report. */ // Looping over all kinds of data levels (area report, link reports, districts reports, thermal - // reports,...) and for a given data level, looping over file levels + // reports,...) and for a given data level, looping over file levels // (values reports, years ids reports, details reports, ...) the - // code can produce. + // code can produce. // For one particular kind of report, looping over (selected) output variables // it contains, and incrementing a counter with as many columns as the current variable can take // up at most in a report. - for (uint CDataLevel = 1; CDataLevel <= Category::maxDataLevel; CDataLevel *= 2) + for (uint CDataLevel = 1; CDataLevel <= Category::DataLevel::maxDataLevel; CDataLevel *= 2) { - for (uint CFileLevel = 1; CFileLevel <= Category::maxFileLevel; CFileLevel *= 2) + for (uint CFileLevel = 1; CFileLevel <= Category::FileLevel::maxFileLevel; CFileLevel *= 2) { uint currentColumnsCount = 0; - for (auto& [name, variable] : allVarsPrintInfo) + for (auto& [name, variable]: allVarsPrintInfo) { - if (variable.isPrinted() && - variable.isPrintedOnFileLevel(CFileLevel) && - variable.isPrintedOnDataLevel(CDataLevel)) + if (variable.isPrinted() && variable.isPrintedOnFileLevel(CFileLevel) + && variable.isPrintedOnDataLevel(CDataLevel)) { // For the current output variable, we retrieve the max number - // of columns it takes in a sysnthesis report. + // of columns it takes in a sysnthesis report. currentColumnsCount += variable.getMaxColumnsCount(); } } @@ -259,22 +255,24 @@ void AllVariablesPrintInfo::computeMaxColumnsCountInReports() void AllVariablesPrintInfo::countSelectedAreaVars() { - numberSelectedAreaVariables = - std::count_if(allVarsPrintInfo.begin(), - allVarsPrintInfo.end(), - [](auto& p) {return p.second.isPrinted() && - p.second.isPrintedOnDataLevel(Category::area); }); + numberSelectedAreaVariables = std::count_if(allVarsPrintInfo.begin(), + allVarsPrintInfo.end(), + [](auto& p) { + return p.second.isPrinted() + && p.second.isPrintedOnDataLevel( + Category::DataLevel::area); + }); } void AllVariablesPrintInfo::countSelectedLinkVars() { - numberSelectedLinkVariables = - std::count_if(allVarsPrintInfo.begin(), - allVarsPrintInfo.end(), - [](auto& p) {return p.second.isPrinted() && - p.second.isPrintedOnDataLevel(Category::link); }); + numberSelectedLinkVariables = std::count_if(allVarsPrintInfo.begin(), + allVarsPrintInfo.end(), + [](auto& p) { + return p.second.isPrinted() + && p.second.isPrintedOnDataLevel( + Category::DataLevel::link); + }); } - -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/version.cpp b/src/libs/antares/study/version.cpp index 3bdda2ebfb..5459ed5d63 100644 --- a/src/libs/antares/study/version.cpp +++ b/src/libs/antares/study/version.cpp @@ -1,211 +1,192 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include "study.h" -#include "version.h" -#include "../../../config.h" - -using namespace Yuni; - -#define SEP IO::Separator - -// Checking version between CMakeLists.txt and Antares'versions -enum -{ - versionFromCMake = (ANTARES_VERSION_HI * 100 + ANTARES_VERSION_LO * 10), -}; - -YUNI_STATIC_ASSERT((uint)versionFromCMake == (uint)Antares::Data::versionLatest, - DiscrepancyBetweenCMakeVersionAndAntaresVersion); +#include "antares/study/version.h" -namespace Antares::Data -{ +#include +#include "antares/study/study.h" -static inline Version StudyFormatCheck(const String& headerFile) -{ - // The raw version number - uint version = StudyHeader::ReadVersionFromFile(headerFile); - // Its equivalent - Version venum = VersionIntToVersion(version); - - switch (venum) - { - // Dealing with special values - case versionUnknown: - case versionFutur: - { - return (version and (uint) version > (uint)versionLatest) ? versionFutur : versionUnknown; - } - default: - return venum; - } -} +using namespace Yuni; +using namespace Antares::Data; -const char* VersionToCStr(const Version v) +namespace { - // The list should remain ordered in the reverse order for performance reasons - switch (v) - { - case versionFutur: - return ">8.7"; - case version870: - return "8.7"; - case version860: - return "8.6"; - case version850: - return "8.5"; - case version840: - return "8.4"; - case version830: - return "8.3"; - case version820: - return "8.2"; - case version810: - return "8.1"; - case version800: - return "8.0"; - - // older versions - case version720: - return "7.2"; - case version710: - return "7.1"; - case version700: - return "7.0"; - - case versionUnknown: - return "0"; - } - return "0.0"; -} - -const wchar_t* VersionToWStr(const Version v) +constexpr auto supportedVersions = std::to_array({ + StudyVersion(7, 0), + StudyVersion(7, 1), + StudyVersion(7, 2), + StudyVersion(8, 0), + StudyVersion(8, 1), + StudyVersion(8, 2), + StudyVersion(8, 3), + StudyVersion(8, 4), + StudyVersion(8, 5), + StudyVersion(8, 6), + StudyVersion(8, 7), + StudyVersion(8, 8), + StudyVersion(9, 0), + StudyVersion(9, 1) + // Add new versions here +}); + +/// Convert a unsigned into a StudyVersion, used for legacy version format (ex: 720) +StudyVersion legacyVersionIntToVersion(unsigned version) { - // The list should remain ordered in the reverse order for performance reasons - switch (v) - { - case versionFutur: - return L">8.7"; - case version870: - return L"8.7"; - case version860: - return L"8.6"; - case version850: - return L"8.5"; - case version840: - return L"8.4"; - case version830: - return L"8.3"; - case version820: - return L"8.2"; - case version810: - return L"8.1"; - case version800: - return L"8.0"; + // It's not necessary to add anything here, since legacy versions should not be created - // older versions - case version720: - return L"7.2"; - case version710: - return L"7.1"; - case version700: - return L"7.0"; - case versionUnknown: - return L"0"; - } - return L"0.0"; -} - -Version VersionIntToVersion(uint version) -{ // The list should remain ordered in the reverse order for performance reasons switch (version) { + case 880: + return StudyVersion(8, 8); case 870: - return version870; + return StudyVersion(8, 7); case 860: - return version860; + return StudyVersion(8, 6); case 850: - return version850; + return StudyVersion(8, 5); case 840: - return version840; + return StudyVersion(8, 4); case 830: - return version830; + return StudyVersion(8, 3); case 820: - return version820; + return StudyVersion(8, 2); case 810: - return version810; + return StudyVersion(8, 1); case 800: - return version800; + return StudyVersion(8, 0); // older versions case 720: - return version720; + return StudyVersion(7, 2); case 710: - return version710; + return StudyVersion(7, 1); case 700: - return version700; - case versionFutur: - case versionUnknown: - return versionUnknown; + return StudyVersion(7, 0); default: - logs.error() << "Study version " << version << " is not supported by this version of " - "antares-solver"; + logs.error() << "Study version " << version + << " is not supported by this version of " + "antares-solver"; logs.error() << "Studies in version <7.0 are no longer supported. Please upgrade it first" - << " if it's the case"; - return versionUnknown; + << " if it's the case"; + return StudyVersion::unknown(); } } -Version StudyTryToFindTheVersion(const AnyString& folder) +StudyVersion parseLegacyVersion(const std::string& versionStr) { - if (folder.empty()) // trivial check - return versionUnknown; + unsigned versionNumber = 0; + try + { + versionNumber = std::stoul(versionStr); + } + catch (std::invalid_argument&) + { + logs.error() << "Invalid version number: " << versionStr; + return StudyVersion::unknown(); + } + return ::legacyVersionIntToVersion(versionNumber); +} - // foldernormalization - String abspath, directory; - IO::MakeAbsolute(abspath, folder); - IO::Normalize(directory, abspath); +StudyVersion parseCurrentVersion(const std::string& s, size_t separator) +{ + unsigned major, minor; - if (not directory.empty() and IO::Directory::Exists(directory)) + if (separator == std::string::npos) + { + logs.error() << "Invalid version format, exiting"; + } + + try + { + major = std::stoul(s.substr(0, separator)); + minor = std::stoul(s.substr(separator + 1)); + } + catch (std::invalid_argument&) { - abspath.reserve(directory.size() + 20); - abspath.clear() << directory << SEP << "study.antares"; - if (IO::File::Exists(abspath)) - return StudyFormatCheck(abspath); + logs.error() << "Invalid version format, exiting"; + return StudyVersion::unknown(); } - return versionUnknown; + return StudyVersion(major, minor); } -bool StudyVersion::isStudyLatestVersion(std::string studyFolder) const { - return StudyTryToFindTheVersion(studyFolder) == versionLatest; +} // namespace + +// Checking version between CMakeLists.txt and Antares'versions +static_assert(StudyVersion(ANTARES_VERSION_HI, ANTARES_VERSION_LO) == ::supportedVersions.back(), + "Please check that CMake's version and version.cpp's version match"); + +namespace Antares::Data +{ +bool StudyVersion::fromString(const std::string& versionStr) +{ + // if the string doesn't contains a dot it's legacy format + if (size_t separator = versionStr.find("."); separator == std::string::npos) + { + *this = parseLegacyVersion(versionStr); + } + else + { + *this = parseCurrentVersion(versionStr, separator); + } + + if (isSupported(true)) + { + return true; + } + + *this = unknown(); + return false; +} + +std::string StudyVersion::toString() const +{ + return std::to_string(major_) + "." + std::to_string(minor_); +} + +StudyVersion StudyVersion::latest() +{ + return ::supportedVersions.back(); +} + +StudyVersion StudyVersion::unknown() +{ + return StudyVersion(); } -} // namespace Antares::Data +bool StudyVersion::isSupported(bool verbose) const +{ + if (std::ranges::find(::supportedVersions, *this) != ::supportedVersions.end()) + { + return true; + } + + if (*this > latest() && verbose) + { + logs.error() << "Maximum study version supported: " + << ::supportedVersions.back().toString(); + logs.error() << "Please upgrade the solver to the latest version"; + } + + return false; +} +} // namespace Antares::Data diff --git a/src/libs/antares/study/version.h b/src/libs/antares/study/version.h deleted file mode 100644 index c00210bef5..0000000000 --- a/src/libs/antares/study/version.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_VERSION_H__ -#define __ANTARES_LIBS_STUDY_VERSION_H__ - -#include - -namespace Antares::Data -{ -/*! -** \brief Version of a study -** -** \ingroup study -** \see CHANGELOG.txt -*/ -enum Version -{ - //! Unknown version of a study - versionUnknown = 0, - //! Study version 7.0 - version700 = 700, - //! Study version 7.1 - version710 = 710, - //! Study version 7.2 - version720 = 720, - //! Study version 8.0 - version800 = 800, - //! Study version 8.1 - version810 = 810, - //! Study version 8.2 - version820 = 820, - //! Study version 8.3 - version830 = 830, - //! Study version 8.4 - version840 = 840, - //! Study version 8.5 - version850 = 850, - //! Study version 8.6 - version860 = 860, - version870 = 870, - - // Constants - //! A more recent version that we can't handle - versionFutur = 99999, - -}; - -constexpr Version versionLatest = version870; - -/*! -** \brief Try to determine the version of a study -** \ingroup study -** -** \param folder The folder where data are located -** \param checkFor1x True to check for an old 1.x study -** \return The version of the study. `VersionUnknown` of not found -*/ -Version StudyTryToFindTheVersion(const AnyString& folder); - -/*! -** \brief Get the human readable version of the version of a study -** -** \ingroup study -** \param v The study version to convert -** \return A CString -*/ -const char* VersionToCStr(const Version v); - -/*! -** \brief Get the human readable version of the version of a study (wide char) -** -** \ingroup study -** \param v The study version to convert -** \return A wide string -*/ -const wchar_t* VersionToWStr(const Version v); - -/*! -** \brief Convert a mere integer into an enum `Version` -*/ -Version VersionIntToVersion(uint version); - -class StudyVersion { -public: - [[nodiscard]] bool isStudyLatestVersion(std::string studyFolder) const; -}; -} // namespace Antares::Data - - -#endif // __ANTARES_LIBS_STUDY_VERSION_H__ diff --git a/src/libs/antares/study/xcast.h b/src/libs/antares/study/xcast.h deleted file mode 100644 index bfd8ec3a03..0000000000 --- a/src/libs/antares/study/xcast.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_XCAST_H__ -#define __ANTARES_LIBS_STUDY_XCAST_H__ - -#include "xcast/xcast.h" - -#endif // __ANTARES_LIBS_STUDY_XCAST_H__ diff --git a/src/libs/antares/study/xcast/xcast.cpp b/src/libs/antares/study/xcast/xcast.cpp index 99978abe41..0f2e05956b 100644 --- a/src/libs/antares/study/xcast/xcast.cpp +++ b/src/libs/antares/study/xcast/xcast.cpp @@ -1,43 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "xcast.h" -#include -#include -#include "../study.h" +#include "antares/study/xcast/xcast.h" + #include +#include +#include +#include +#include "antares/study//study.h" + using namespace Yuni; #define SEP IO::Separator -namespace Antares -{ -namespace Data +namespace Antares::Data { const char* XCast::TSTranslationUseToCString(TSTranslationUse use) @@ -54,13 +49,19 @@ XCast::TSTranslationUse XCast::CStringToTSTranslationUse(const AnyString& str) CString<40, false> s(str); s.toLower(); if (s == "never" || s == "do not use" || s == "none" || s == "no") + { return tsTranslationNone; + } if (s == "before-conversion" || s == "add before conversion" || s == "before conversion" || s == "before" || s == "before scaling" || s == "add before scaling") + { return tsTranslationBeforeConversion; + } if (s == "after-conversion" || s == "add after conversion" || s == "after conversion" || s == "after" || s == "after scaling" || s == "add after scaling") + { return tsTranslationAfterConversion; + } } return tsTranslationNone; } @@ -113,28 +114,40 @@ XCast::Distribution XCast::StringToDistribution(AnyString text) { // The most usefull probability distribution is the Beta distribution if (id == "beta") + { return dtBeta; + } if (id == "uniform") + { return dtUniform; + } if (id == "normal" || id == "normale") + { return dtNormal; + } if (id == "weibullshapea" || id == "weibull" || id == "weibul") + { return dtWeibullShapeA; + } if (id == "gammashapea" || id == "gamma") + { return dtGammaShapeA; + } // auto-fix for intermediate studies in 3.3.x. Can be removed in future releases if (id == "weibulshapea") + { return dtWeibullShapeA; + } } return dtNone; } -XCast::XCast(TimeSeriesType ts) : - useTranslation(tsTranslationNone), - distribution(dtBeta), - capacity(0), - useConversion(false), - timeSeries(ts) +XCast::XCast(TimeSeriesType ts): + useTranslation(tsTranslationNone), + distribution(dtBeta), + capacity(0), + useConversion(false), + timeSeries(ts) { K.resize(12, 24); data.resize((uint)dataMax, 12); @@ -188,58 +201,59 @@ bool XCast::loadFromFolder(const AnyString& folder) IniFile ini; if (ini.open(buffer)) { - // For each section - const IniFile::Property* p; - CString<30, false> key; - - ini.each([&](const IniFile::Section& section) { - // For each property - if (section.name == "general") - { - for (p = section.firstProperty; p != nullptr; p = p->next) - { - key = p->key; - key.toLower(); - if (key == "distribution") - { - distribution = StringToDistribution(p->value); - if (distribution == dtNone) - { - logs.warning() << buffer - << ": Invalid probability distribution. The beta " - "distribution will be used"; - distribution = dtBeta; - } - continue; - } - if (key == "capacity") - { - capacity = p->value.to(); - if (capacity < 0.) - { - logs.warning() - << buffer << ": The capacity can not be a negative value"; - capacity = 0.; - } - continue; - } - if (key == "conversion" || key == "transfer-function" || key == "convertion") - { - useConversion = p->value.to(); - continue; - } - if (key == "translation" || key == "ts-average") - { - useTranslation = CStringToTSTranslationUse(p->value); - continue; - } - - logs.warning() << buffer << ": Unknown property '" << p->key << "'"; - } - } - else - logs.warning() << buffer << ": unknown section '" << section.name << "'"; - }); + ini.each( + [this, &buffer](const IniFile::Section& section) + { + // For each property + if (section.name == "general") + { + for (const IniFile::Property* p = section.firstProperty; p != nullptr; + p = p->next) + { + CString<30, false> key = p->key; + key.toLower(); + if (key == "distribution") + { + distribution = StringToDistribution(p->value); + if (distribution == dtNone) + { + logs.warning() << buffer + << ": Invalid probability distribution. The beta " + "distribution will be used"; + distribution = dtBeta; + } + continue; + } + if (key == "capacity") + { + capacity = p->value.to(); + if (capacity < 0.) + { + logs.warning() + << buffer << ": The capacity can not be a negative value"; + capacity = 0.; + } + continue; + } + if (key == "conversion" || key == "transfer-function" || key == "convertion") + { + useConversion = p->value.to(); + continue; + } + if (key == "translation" || key == "ts-average") + { + useTranslation = CStringToTSTranslationUse(p->value); + continue; + } + + logs.warning() << buffer << ": Unknown property '" << p->key << "'"; + } + } + else + { + logs.warning() << buffer << ": unknown section '" << section.name << "'"; + } + }); } else { @@ -255,7 +269,7 @@ bool XCast::loadFromFolder(const AnyString& folder) // Performing normal loading ret = data.loadFromCSVFile(buffer, (uint)dataMax, 12, Matrix<>::optFixedSize, &readBuffer) - && ret; + && ret; // K buffer.clear() << folder << SEP << "k.txt"; @@ -303,7 +317,9 @@ bool XCast::loadFromFolder(const AnyString& folder) for (uint x = 1; x < conversion.width - 1; ++x) { if (conversion[x][0] <= -1.0e+19 || conversion[x][0] >= +1.0e+19) + { logs.error() << "TS-Generator: Conversion: Invalid range: " << buffer; + } } conversion[conversion.width - 1][0] = (float)1.0e+19; // + std::numeric_limits::max(); @@ -364,13 +380,21 @@ bool XCast::saveToFolder(const AnyString& folder) const IniFile ini; IniFile::Section* s = ini.addSection("general"); if (distribution != dtBeta) + { s->add("distribution", DistributionToNameID(distribution)); - if (!Math::Zero(capacity)) + } + if (!Utils::isZero(capacity)) + { s->add("capacity", capacity); + } if (useConversion) + { s->add("conversion", useConversion); + } if (useTranslation != tsTranslationNone) + { s->add("translation", TSTranslationUseToCString(useTranslation)); + } // Writing the INI file buffer.clear() << folder << SEP << "settings.ini"; @@ -425,5 +449,4 @@ void XCast::copyFrom(const XCast& rhs) distribution = rhs.distribution; } -} // namespace Data -} // namespace Antares +} // namespace Antares::Data diff --git a/src/libs/antares/study/xcast/xcast.h b/src/libs/antares/study/xcast/xcast.h deleted file mode 100644 index 32abeeba46..0000000000 --- a/src/libs/antares/study/xcast/xcast.h +++ /dev/null @@ -1,223 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_XCAST_XCAST_H__ -#define __ANTARES_LIBS_STUDY_XCAST_XCAST_H__ - -#include -#include -#include -#include - -namespace Antares::Data -{ -class XCast final : private Yuni::NonCopyable -{ -public: - //! Vector - using Vector = std::vector; - //! Vector with the const qualifier - using VectorConst = std::vector; - - /*! - ** \brief All coefficients - */ - enum - { - dataCoeffAlpha = 0, - dataCoeffBeta, - dataCoeffGamma, - dataCoeffDelta, - dataCoeffTheta, - dataCoeffMu, - //! The maximum number of coefficients - dataMax, - }; - - /*! - ** \brief All available probability distribution - */ - enum Distribution - { - //! None - dtNone = 0, - //! The uniform distribution - dtUniform = 1, - //! The Beta distribution - dtBeta = 2, - //! The normal distribution - dtNormal = 3, - //! The Weibul distribution, of shape A - dtWeibullShapeA = 4, - //! The Gamma distribution, of shape A - dtGammaShapeA = 5, - //! The maximum number of distributions - dtMax - }; - - enum - { - //! Hard limit for the number of points of the transfer function - conversionMaxPoints = 100, - }; - - enum TSTranslationUse - { - //! Do not use the time-series average - tsTranslationNone = 0, - //! Add the time-series average before computing the transfer function - tsTranslationBeforeConversion, - //! Add the time-series average after computing the transfer function - tsTranslationAfterConversion, - }; - -public: - /*! - ** \brief Convert a distribution into its human readable representation - */ - static const char* DistributionToCString(Distribution d); - - /*! - ** \brief Convert a CString into a probability distribution - */ - static Distribution StringToDistribution(AnyString str); - - /*! - ** \brief Convert a probability distribution into its string id representation - */ - static const char* DistributionToNameID(Distribution d); - - /*! - ** \brief How to use the timeseries average - */ - static const char* TSTranslationUseToCString(TSTranslationUse use); - - static TSTranslationUse CStringToTSTranslationUse(const AnyString& str); - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Constructor - */ - XCast(TimeSeriesType ts); - /*! - ** \brief Destructor - */ - ~XCast(); - //@} - - /*! - ** \brief Reset to default values - */ - void resetToDefaultValues(); - - /*! - ** \brief Copy settings from another XCast struct - */ - void copyFrom(const XCast& rhs); - - /*! - ** \brief Load data from a folder - */ - bool loadFromFolder(const AnyString& folder); - - /*! - ** \brief Save data to a folder - */ - bool saveToFolder(const AnyString& folder) const; - - //! \name Memory management - //@{ - /*! - ** \brief Make sure that all data are loaded in memory - */ - bool forceReload(bool reload = false) const; - - /*! - ** \brief Mark the load data as modified - */ - void markAsModified() const; - - /*! - ** \brief Get the amount of memory currently used by the XCast data - */ - uint64_t memoryUsage() const; - - /*! - ** \brief Estimate the amount of memory required by this class for a simulation - */ - - //@} - -public: - /*! - ** \brief Data required for XCast: coefficients (coeffMax x 12) - */ - Matrix data; - - /*! - ** \brief K (12x24) - */ - Matrix K; - - /*! - ** \brief Time-series average - */ - Matrix translation; - - //! How to use the timeseries average - TSTranslationUse useTranslation; - - //! The probability distribution to use - Distribution distribution; - - //! The installed capacity - double capacity; - - //! True to use the transfer function after the generation of the time-series - bool useConversion; - /*! - ** \brief The conversion function - ** - ** The first row gives the X-Coordinates, the second one the Y-Coordinates. - */ - Matrix conversion; - - //! The related time-series - const TimeSeriesType timeSeries; - -protected: - void resetTransferFunction(); - -}; // class XCast - -} // namespace Antares::Data - - -#include "xcast.hxx" - -#endif // __ANTARES_LIBS_STUDY_XCAST_XCAST_H__ diff --git a/src/libs/antares/study/xcast/xcast.hxx b/src/libs/antares/study/xcast/xcast.hxx deleted file mode 100644 index 696f411718..0000000000 --- a/src/libs/antares/study/xcast/xcast.hxx +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_STUDY_XCAST_XCAST_HXX__ -#define __ANTARES_LIBS_STUDY_XCAST_XCAST_HXX__ - -#include - -namespace Antares -{ -namespace Data -{ -inline uint64_t XCast::memoryUsage() const -{ - return sizeof(XCast) + data.memoryUsage() + K.memoryUsage() + translation.memoryUsage() - + conversion.memoryUsage(); -} - -} // namespace Data -} // namespace Antares - -#endif // __ANTARES_LIBS_STUDY_XCAST_XCAST_HXX__ diff --git a/src/libs/antares/sys/CMakeLists.txt b/src/libs/antares/sys/CMakeLists.txt index b0cd415915..e52567a77a 100644 --- a/src/libs/antares/sys/CMakeLists.txt +++ b/src/libs/antares/sys/CMakeLists.txt @@ -17,13 +17,19 @@ target_link_libraries(${PROJ} PUBLIC yuni-static-core PRIVATE + antares-core Antares::logs Antares::inifile + Antares::config ) target_include_directories(${PROJ} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + $ PRIVATE - ${CMAKE_SOURCE_DIR}/libs + $ ) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/libs/antares/sys/appdata.cpp b/src/libs/antares/sys/appdata.cpp index 78f415916e..cfc509ff67 100644 --- a/src/libs/antares/sys/appdata.cpp +++ b/src/libs/antares/sys/appdata.cpp @@ -1,39 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/sys/appdata.h" #ifdef YUNI_OS_WINDOWS -#include #include -#endif -#include +#include +#endif #include +#include + using namespace Yuni; namespace OperatingSystem @@ -43,7 +38,9 @@ static inline bool ConvertWideCharIntoString(String& out, const wchar_t* wpath) { int sizeRequired = WideCharToMultiByte(CP_UTF8, 0, wpath, -1, nullptr, 0, nullptr, nullptr); if (sizeRequired <= 0) + { return false; + } out.reserve((uint)sizeRequired + 1); WideCharToMultiByte(CP_UTF8, 0, wpath, -1, (char*)out.data(), sizeRequired, nullptr, nullptr); @@ -57,22 +54,30 @@ bool FindLocalAppData(Yuni::String& out, bool allusers) out.clear(); #ifdef YUNI_OS_WINDOWS - typedef HRESULT WINAPI SHGetFolderPathWFn( - HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, __out LPTSTR pszPath); + typedef HRESULT WINAPI SHGetFolderPathWFn(HWND hwndOwner, + int nFolder, + HANDLE hToken, + DWORD dwFlags, + __out LPTSTR pszPath); HMODULE hShell32 = GetModuleHandleW(L"shell32.dll"); if (hShell32) { // Windows XP - SHGetFolderPathWFn* folderPathW - = (SHGetFolderPathWFn*)(GetProcAddress(hShell32, "SHGetFolderPathW")); + SHGetFolderPathWFn* folderPathW = (SHGetFolderPathWFn*)(GetProcAddress(hShell32, + "SHGetFolderPathW")); if (folderPathW) { wchar_t* wpath = new wchar_t[MAX_PATH + 1]; if (!wpath) + { return false; - folderPathW( - 0, (allusers ? CSIDL_COMMON_APPDATA : CSIDL_LOCAL_APPDATA), nullptr, 0, wpath); + } + folderPathW(0, + (allusers ? CSIDL_COMMON_APPDATA : CSIDL_LOCAL_APPDATA), + nullptr, + 0, + wpath); if (ConvertWideCharIntoString(out, wpath)) { delete[] wpath; @@ -92,7 +97,9 @@ bool FindLocalAppData(Yuni::String& out, bool allusers) { System::Environment::Read("HOME", out); if (not out.empty()) + { return true; + } } #endif return false; @@ -101,13 +108,17 @@ bool FindLocalAppData(Yuni::String& out, bool allusers) bool FindAntaresLocalAppData(Yuni::String& out, bool allusers) { if (not FindLocalAppData(out, allusers)) + { return false; + } #ifdef YUNI_OS_WINDOWS out += "\\RTE\\antares"; #else if (allusers) + { out += "/antares"; + } else { // ~/.antares is already taken by wx - recent files diff --git a/src/libs/antares/sys/include/antares/sys/appdata.h b/src/libs/antares/sys/include/antares/sys/appdata.h index d7bb0b5ad2..e4c1ba0ef6 100644 --- a/src/libs/antares/sys/include/antares/sys/appdata.h +++ b/src/libs/antares/sys/include/antares/sys/appdata.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_SYS_APPDATA_H__ #define __ANTARES_LIBS_SYS_APPDATA_H__ diff --git a/src/libs/antares/sys/include/antares/sys/policy.h b/src/libs/antares/sys/include/antares/sys/policy.h index 0166211bb8..63c9d8dc12 100644 --- a/src/libs/antares/sys/include/antares/sys/policy.h +++ b/src/libs/antares/sys/include/antares/sys/policy.h @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_ADMIN_POLICY_H__ #define __ANTARES_LIBS_ADMIN_POLICY_H__ #include -#include #include +#include /*! ** \brief Local policy settings @@ -59,14 +53,6 @@ void Close(); */ void CheckRootPrefix(const char* argv0); -/*! -** \brief Read an entry from the local policies -** -** If the local policies are not opened, it will always return false -** \return True if the entry exists, false otherwise -*/ -bool HasKey(const PolicyKey& key); - /*! ** \brief Read the content of a single entry ** @@ -83,11 +69,6 @@ bool Read(YString& out, const PolicyKey& key); */ bool ReadAsBool(const PolicyKey& key, bool defval = false); -/*! -** \brief Dump the entries to the standard output -*/ -void DumpToStdOut(); - /*! ** \brief Dump the entries to the logs */ diff --git a/src/libs/antares/sys/policy.cpp b/src/libs/antares/sys/policy.cpp index c45de88af5..0427c7441c 100644 --- a/src/libs/antares/sys/policy.cpp +++ b/src/libs/antares/sys/policy.cpp @@ -1,44 +1,42 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/sys/policy.h" + #include -#include -#include "antares/sys/appdata.h" -#include -#include -#include -#include "../config.h" -#include +#include + +#include #include +#include #include #include -#include -#include +#include + +#include +#include +#include +#include +#include "antares/config/config.h" +#include "antares/sys/appdata.h" using namespace Yuni; using namespace Antares; @@ -56,34 +54,37 @@ using PolicyMap = std::map; //! All entries static PolicyMap* entries = nullptr; -//! Mutex for policy entries -static Mutex gsMutex; +static std::mutex gsMutex; //!< Mutex for policy entries template static void OpenFromINIFileWL(const String& filename, const StringT& hostname) { IniFile ini; if (not ini.open(filename)) + { return; + } - PolicyKey key; - ShortString128 hostnameVersion; - ShortString128 hostnameAll; - hostnameVersion << hostname << ':' << ANTARES_VERSION; - hostnameAll << hostname << ":*"; - - ini.each([&](const IniFile::Section& section) { - // This section is dedicated to another host - if (section.name == "*:*" or section.name == "*:" ANTARES_VERSION - or section.name == hostnameAll or section.name == hostnameVersion) - { - section.each([&](const IniFile::Property& property) { - key = property.key; - key.trim(" \t"); - (*entries)[key] = property.value; - }); - } - }); + std::string hostnameVersion = hostname + ':' + ANTARES_VERSION; + std::string hostnameAll = hostname + ":*"; + + ini.each( + [&hostnameVersion, &hostnameAll](const IniFile::Section& section) + { + // This section is dedicated to another host + if (section.name == "*:*" or section.name == "*:" ANTARES_VERSION + or section.name.equals(hostnameAll) or section.name.equals(hostnameVersion)) + { + section.each( + [](const IniFile::Property& property) + { + PolicyKey key; + key = property.key; + key.trim(" \t"); + (*entries)[key] = property.value; + }); + } + }); } class PredicateEnv final @@ -94,7 +95,9 @@ class PredicateEnv final { PolicyMap::const_iterator i = entries->find(value); if (i != entries->end()) + { out += i->second; + } else { const ShortString128 zeroT = value; @@ -112,7 +115,9 @@ static inline uint ExpandWL(StringT1& out, const StringT2& string, PredicateT& p // Try to find the first occurence of an expression String::Size p = string.find("${", 0); if (p == String::npos) + { return 0; + } // Ok we have found something, let's go deeper... uint count = 0; @@ -137,7 +142,9 @@ static inline uint ExpandWL(StringT1& out, const StringT2& string, PredicateT& p // The expression expr.adapt(string.c_str() + p + 2, end - p - 2); if (not expr.empty()) + { predicate(out, expr); + } // Try to find the next one offset = end + 1; @@ -145,7 +152,9 @@ static inline uint ExpandWL(StringT1& out, const StringT2& string, PredicateT& p } while (p != String::npos); if (offset < string.size()) + { out.append(string.c_str() + offset, string.size() - offset); + } return count; } @@ -159,7 +168,9 @@ static inline void ExpansionWL() { String& value = i->second; if (ExpandWL(out, value, predicate)) + { value = out; + } } } @@ -168,10 +179,12 @@ static inline void ExpansionWL() bool Open(bool expandEntries) { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (localPoliciesOpened) + { return true; + } String path; path.reserve(512); @@ -191,10 +204,14 @@ bool Open(bool expandEntries) String localAppData; if (not OperatingSystem::FindAntaresLocalAppData(localAppData, false)) + { localAppData.clear(); + } String localAppDataAllUsers; if (not OperatingSystem::FindAntaresLocalAppData(localAppDataAllUsers, true)) + { localAppDataAllUsers.clear(); + } String pathLocalPolicy; pathLocalPolicy << localAppData << SEP << "localpolicy.ini"; @@ -202,9 +219,13 @@ bool Open(bool expandEntries) pathLocalPolicyAllUsers << localAppDataAllUsers << SEP << "localpolicy.ini"; if (IO::File::Exists(pathLocalPolicy)) + { OpenFromINIFileWL(pathLocalPolicy, hostname); + } if (IO::File::Exists(pathLocalPolicyAllUsers)) + { OpenFromINIFileWL(pathLocalPolicyAllUsers, hostname); + } // informations about antares // version @@ -225,21 +246,23 @@ bool Open(bool expandEntries) (*entries)[(key = "sys.cpu")] = System::CPU::Count(); // how much memory ? (*entries)[(key = "sys.memory")].clear() - << (uint)Math::Round(((double)(System::Memory::Total() + 1) / 1024 / 1024 / 1024)) << " Go"; + << (uint)std::round(((double)(System::Memory::Total() + 1) / 1024 / 1024 / 1024)) << " Go"; // paths (*entries)[(key = "localpolicy.user.path")] = pathLocalPolicy; (*entries)[(key = "localpolicy.allusers.path")] = pathLocalPolicyAllUsers; if (expandEntries) + { ExpansionWL(); + } return true; } void Close() { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (localPoliciesOpened) { @@ -252,18 +275,10 @@ void Close() } } -bool HasKey(const PolicyKey& key) -{ - // avoid concurrent changes - MutexLocker locker(gsMutex); - - return (not key.empty() and entries and entries->find(key) != entries->end()); -} - bool Read(String& out, const PolicyKey& key) { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (not key.empty() and entries) { @@ -281,7 +296,7 @@ bool Read(String& out, const PolicyKey& key) bool ReadAsBool(const PolicyKey& key, bool defval) { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (not key.empty() and entries) { @@ -290,7 +305,9 @@ bool ReadAsBool(const PolicyKey& key, bool defval) { bool v; if (i->second.to(v)) + { return v; + } } } return defval; @@ -299,10 +316,12 @@ bool ReadAsBool(const PolicyKey& key, bool defval) void DumpToString(Clob& out) { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (!entries or entries->empty()) + { return; + } // The end of the container const PolicyMap::const_iterator end = entries->end(); @@ -314,7 +333,9 @@ void DumpToString(Clob& out) { uint len = i->first.size(); if (len > maxlen) + { maxlen = len; + } } } @@ -330,43 +351,10 @@ void DumpToString(Clob& out) } } -void DumpToStdOut() -{ - // avoid concurrent changes - MutexLocker locker(gsMutex); - - if (!entries or entries->empty()) - return; - - // The end of the container - const PolicyMap::const_iterator end = entries->end(); - - // Find the longest key length - uint maxlen = 0; - { - for (PolicyMap::const_iterator i = entries->begin(); i != end; ++i) - { - uint len = i->first.size(); - if (len > maxlen) - maxlen = len; - } - } - - maxlen += 3; // spaces after the key - PolicyKey row; - - for (PolicyMap::const_iterator i = entries->begin(); i != end; ++i) - { - row = i->first; - row.resize(maxlen, " "); - std::cout << " " << row << ": " << i->second << '\n'; - } -} - void DumpToLogs() { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (not entries or entries->empty()) { @@ -383,28 +371,34 @@ void DumpToLogs() } } +// TODO VP: delete void CheckRootPrefix(const char* argv0) { // avoid concurrent changes - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); - if (!entries) + if (entries == nullptr) + { return; - auto i = entries->find("force_root_prefix"); - if (i != entries->end() and not i->second.empty()) + } + if (auto i = entries->find("force_root_prefix"); i != entries->end() and not i->second.empty()) { AnyString adapter = argv0; if (IO::IsAbsolute(adapter)) { if (0 != adapter.ifind(i->second)) + { throw FatalError("Invalid root prefix."); + } } else { String absfilename; IO::MakeAbsolute(absfilename, adapter); if (0 != absfilename.ifind(i->second)) + { throw FatalError("Invalid root prefix."); + } } } } diff --git a/src/libs/antares/utils/CMakeLists.txt b/src/libs/antares/utils/CMakeLists.txt index 79b7d4f62f..904ad43dfc 100644 --- a/src/libs/antares/utils/CMakeLists.txt +++ b/src/libs/antares/utils/CMakeLists.txt @@ -1,8 +1,8 @@ set(PROJ StudyUtils) set(SRC_PROJ - utils.cpp - include/antares/utils/utils.h - include/antares/utils/utils.hxx + utils.cpp + include/antares/utils/utils.h + include/antares/utils/utils.hxx ) source_group("utils" FILES ${SRC_PROJ}) @@ -12,9 +12,14 @@ add_library(Antares::utils ALIAS ${PROJ}) target_link_libraries(${PROJ} PRIVATE yuni-static-core + Antares::logs ) target_include_directories(${PROJ} - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" ) diff --git a/src/libs/antares/utils/include/antares/utils/utils.h b/src/libs/antares/utils/include/antares/utils/utils.h index 974787d84c..1043e7ca4e 100644 --- a/src/libs/antares/utils/include/antares/utils/utils.h +++ b/src/libs/antares/utils/include/antares/utils/utils.h @@ -1,32 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_UTILS_H__ #define __ANTARES_LIBS_UTILS_H__ +#include +#include + #include #include @@ -40,12 +37,26 @@ namespace Antares template void TransformNameIntoID(const AnyString& name, StringT& out); +std::string transformNameIntoID(const std::string& name); + /*! ** \brief Beautify a name, for renaming an area for example */ void BeautifyName(YString& out, AnyString oldname); void BeautifyName(std::string& out, const std::string& oldname); +std::vector> splitStringIntoPairs(const std::string& s, + char delimiter1, + char delimiter2); + +namespace Utils +{ + +bool isZero(double d); + +double round(double d, unsigned precision); + +} // namespace Utils } // namespace Antares #include "utils.hxx" diff --git a/src/libs/antares/utils/include/antares/utils/utils.hxx b/src/libs/antares/utils/include/antares/utils/utils.hxx index e0940b6b4f..93bb970ba9 100644 --- a/src/libs/antares/utils/include/antares/utils/utils.hxx +++ b/src/libs/antares/utils/include/antares/utils/utils.hxx @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_UTILS_HXX__ #define __ANTARES_LIBS_UTILS_HXX__ #include + #include namespace Antares diff --git a/src/libs/antares/utils/utils.cpp b/src/libs/antares/utils/utils.cpp index d400f1d716..31992d6020 100644 --- a/src/libs/antares/utils/utils.cpp +++ b/src/libs/antares/utils/utils.cpp @@ -1,32 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares/utils/utils.h" +#include + +#include + using namespace Yuni; namespace Antares @@ -35,16 +33,18 @@ void BeautifyName(YString& out, AnyString oldname) { out.clear(); if (oldname.empty()) + { return; + } oldname.trim(" \r\n\t"); if (oldname.empty()) + { return; + } out.reserve(oldname.size()); - - auto end = oldname.utf8end(); for (auto i = oldname.utf8begin(); i != end; ++i) { @@ -59,13 +59,17 @@ void BeautifyName(YString& out, AnyString oldname) out += c; } else + { out += ' '; + } } out.trim(" \t\r\n"); while (std::string(out.c_str()).find(" ") != std::string::npos) + { out.replace(" ", " "); + } out.trim(" \t\r\n"); } @@ -78,6 +82,13 @@ void TransformNameIntoID(const AnyString& name, std::string& out) out = yuniOut; } +std::string transformNameIntoID(const std::string& name) +{ + std::string out; + TransformNameIntoID(name, out); + return out; +} + void BeautifyName(std::string& out, const std::string& oldname) { YString yuniOut; @@ -85,4 +96,48 @@ void BeautifyName(std::string& out, const std::string& oldname) out = yuniOut.c_str(); } +std::vector> splitStringIntoPairs(const std::string& s, + char delimiter1, + char delimiter2) +{ + std::vector> pairs; + std::stringstream ss(s); + std::string token; + + while (std::getline(ss, token, delimiter1)) + { + size_t pos = token.find(delimiter2); + if (pos != std::string::npos) + { + std::string begin = token.substr(0, pos); + std::string end = token.substr(pos + 1); + pairs.push_back({begin, end}); + } + else + { + logs.warning() << "Error while parsing: " << token; + logs.warning() << "Correct format is: \"object1" << delimiter2 << "object2" + << delimiter1 << "object3" << delimiter2 << "object4\""; + } + } + + return pairs; +} + +namespace Utils +{ + +bool isZero(double d) +{ + constexpr double threshold = 1.e-6; + return std::abs(d) < threshold; +} + +double round(double d, unsigned precision) +{ + unsigned factor = std::pow(10, precision); + return std::round(d * factor) / factor; +} + +} // namespace Utils } // namespace Antares diff --git a/src/libs/antares/version.cpp b/src/libs/antares/version.cpp index 52e52430bf..c4316291db 100644 --- a/src/libs/antares/version.cpp +++ b/src/libs/antares/version.cpp @@ -1,34 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "version.h" -#include "../../config.h" +#include "antares/antares/version.h" + #include +#include "antares/config/config.h" + namespace Antares { void PrintVersionToStdCout() diff --git a/src/libs/antares/version.h b/src/libs/antares/version.h deleted file mode 100644 index a00867f63e..0000000000 --- a/src/libs/antares/version.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_LIBS_VERSION_H__ -#define __ANTARES_LIBS_VERSION_H__ - -namespace Antares -{ -/*! -** \brief Get the version of Antares in a C-string format -*/ -const char* VersionToCString(); - -/*! -** \brief Print the version of Antares on the standard output -*/ -void PrintVersionToStdCout(); - -} // namespace Antares - -#endif // __ANTARES_LIBS_VERSION_H__ diff --git a/src/libs/antares/writer/CMakeLists.txt b/src/libs/antares/writer/CMakeLists.txt index 1f468f5151..9795f6ace4 100644 --- a/src/libs/antares/writer/CMakeLists.txt +++ b/src/libs/antares/writer/CMakeLists.txt @@ -1,15 +1,12 @@ project(result-writer) -add_library(result_writer - # Interface class (public API) - antares/writer/i_writer.h - antares/writer/result_format.h +add_library(result_writer # Helper class private/ensure_queue_started.h ensure_queue_started.cpp # Generic factory (public API) - antares/writer/writer_factory.h + include/antares/writer/writer_factory.h writer_factory.cpp # Immediate file writer (private) @@ -19,14 +16,19 @@ add_library(result_writer # Add entry to zip, using a job queue (private) zip_writer.cpp private/zip_writer.h - antares/writer/result_format.h + + in_memory_writer.cpp + include/antares/writer/in_memory_writer.h # Public (for tests) + include/antares/writer/result_format.h ) add_library(Antares::result_writer ALIAS result_writer) target_include_directories(result_writer PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/private ) target_link_libraries(result_writer @@ -39,7 +41,8 @@ target_link_libraries(result_writer inifile io Antares::concurrency - ) - - +) +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/libs/antares/writer/antares/writer/i_writer.h b/src/libs/antares/writer/antares/writer/i_writer.h deleted file mode 100644 index be579165e5..0000000000 --- a/src/libs/antares/writer/antares/writer/i_writer.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -namespace Antares -{ -namespace Solver -{ - -/*! - * A generic I/O exception that may be thrown by writer operations. - */ -class IOError : public std::runtime_error -{ -public: - using std::runtime_error::runtime_error; -}; - -class IResultWriter -{ -public: - using Ptr = std::shared_ptr; - virtual void addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) = 0; - virtual void addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) = 0; - virtual void addEntryFromFile(const std::string& entryPath, const std::string& filePath) = 0; - - /*! - * Waits for completion of every write operation previously appended. - * An IOError may be raised if any of those fails. - */ - virtual void flush() = 0; - virtual bool needsTheJobQueue() const = 0; - virtual void finalize(bool verbose) = 0; -}; - -class NullResultWriter: public Solver::IResultWriter { - void addEntryFromBuffer(const std::string &, Yuni::Clob &) override; - void addEntryFromBuffer(const std::string &, std::string &) override; - void addEntryFromFile(const std::string &, const std::string &) override; - void flush() override; - bool needsTheJobQueue() const override; - void finalize(bool ) override; -}; - -} // namespace Solver -} // namespace Antares diff --git a/src/libs/antares/writer/antares/writer/result_format.h b/src/libs/antares/writer/antares/writer/result_format.h deleted file mode 100644 index b189fbadda..0000000000 --- a/src/libs/antares/writer/antares/writer/result_format.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// Created by marechaljas on 10/08/23. -// - -#pragma once - -namespace Antares::Data -{ - // Format of results - enum ResultFormat - { - // Store outputs as files inside directories - legacyFilesDirectories = 0, - // Store outputs inside a single zip archive - zipArchive - }; -} \ No newline at end of file diff --git a/src/libs/antares/writer/antares/writer/writer_factory.h b/src/libs/antares/writer/antares/writer/writer_factory.h deleted file mode 100644 index f507d3e48c..0000000000 --- a/src/libs/antares/writer/antares/writer/writer_factory.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include -#include - -#include "i_writer.h" -#include "result_format.h" - -namespace Benchmarking { - class IDurationCollector; -} - -namespace Antares::Solver -{ -IResultWriter::Ptr resultWriterFactory(Antares::Data::ResultFormat fmt, - const YString& folderOutput, - std::shared_ptr qs, - Benchmarking::IDurationCollector& duration_collector); -} - diff --git a/src/libs/antares/writer/ensure_queue_started.cpp b/src/libs/antares/writer/ensure_queue_started.cpp index 8c77b524e7..49f46e421c 100644 --- a/src/libs/antares/writer/ensure_queue_started.cpp +++ b/src/libs/antares/writer/ensure_queue_started.cpp @@ -1,13 +1,32 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "private/ensure_queue_started.h" namespace Antares { namespace Solver { -EnsureQueueStartedIfNeeded::EnsureQueueStartedIfNeeded( - IResultWriter* writer, - std::shared_ptr qs) : - qs(qs) +EnsureQueueStartedIfNeeded::EnsureQueueStartedIfNeeded(IResultWriter* writer, + std::shared_ptr qs): + qs(qs) { startQueue = !qs->started() && writer->needsTheJobQueue(); if (startQueue) diff --git a/src/libs/antares/writer/immediate_file_writer.cpp b/src/libs/antares/writer/immediate_file_writer.cpp index 8d3ff5e016..f67e3740e8 100644 --- a/src/libs/antares/writer/immediate_file_writer.cpp +++ b/src/libs/antares/writer/immediate_file_writer.cpp @@ -1,119 +1,111 @@ -#include -#include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "immediate_file_writer.h" + +#include -#include "private/immediate_file_writer.h" #include #include - -// Create directory hierarchy (incl. root) -// Don't complain if directories already exist -// Example. Assuming /root exists, `createDirectoryHierarchy("/root", "a/b/c");` -// Creates /root/a, /root/a/b, /root/a/b/c -static bool createDirectory(const Yuni::String& path) -{ - using namespace Yuni; - if (!IO::Directory::Exists(path)) - { - const bool ret = IO::Directory::Create(path); - - if (!ret) - { - Antares::logs.error() << "Error creating directory " << path; - return false; - } - } - return true; -} - -static bool createDirectoryHierarchy(const Yuni::String& root, const Yuni::String& toCreate) -{ - using namespace Yuni; - String::Vector dirs; - toCreate.split(dirs, IO::SeparatorAsString); - String currentDir = root; - - if (!createDirectory(root)) - return false; - - // Remove file component - dirs.pop_back(); - - for (auto& dir : dirs) - { - currentDir << Yuni::IO::Separator << dir; - if (!createDirectory(currentDir)) - return false; - } - return true; -} +namespace fs = std::filesystem; namespace Antares { namespace Solver { -ImmediateFileResultWriter::ImmediateFileResultWriter(const char* folderOutput) : - pOutputFolder(folderOutput) +ImmediateFileResultWriter::ImmediateFileResultWriter(const char* folderOutput): + pOutputFolder(folderOutput) { } ImmediateFileResultWriter::~ImmediateFileResultWriter() = default; -static bool prepareDirectoryHierarchy(const YString& root, - const std::string& entryPath, - Yuni::String& output) +static bool prepareDirectoryHierarchy(const fs::path& root, + const fs::path& entryPath, + fs::path& output) { - output << root << Yuni::IO::Separator << entryPath.c_str(); - return createDirectoryHierarchy(root, entryPath.c_str()); + // Use relative path to remove root dir part + fs::path fullPath = root / entryPath.relative_path(); + output = fullPath; + + fs::path directory = fullPath.parent_path(); + if (fs::exists(directory)) + { + return true; + } + + return fs::create_directories(directory); } // Write to file immediately, creating directories if needed void ImmediateFileResultWriter::addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) { - Yuni::String output; + fs::path output; if (prepareDirectoryHierarchy(pOutputFolder, entryPath, output)) - IOFileSetContent(output, entryContent); + { + IO::fileSetContent(output.string(), entryContent); + } } // Write to file immediately, creating directories if needed void ImmediateFileResultWriter::addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) { - Yuni::String output; + fs::path output; if (prepareDirectoryHierarchy(pOutputFolder, entryPath, output)) - IOFileSetContent(output, entryContent); + { + IO::fileSetContent(output.string(), entryContent); + } } -void ImmediateFileResultWriter::addEntryFromFile(const std::string& entryPath, - const std::string& filePath) +void ImmediateFileResultWriter::addEntryFromFile(const fs::path& entryPath, + const fs::path& filePath) { - Yuni::String fullPath; + fs::path fullPath; if (!prepareDirectoryHierarchy(pOutputFolder, entryPath, fullPath)) + { return; + } + + std::error_code ec; + try + { + fs::copy(filePath, fullPath, ec); + } + catch (const fs::filesystem_error& exc) + { + logs.error() << exc.what(); + } - switch (Yuni::IO::File::Copy(filePath.c_str(), fullPath)) + if (ec) { - using namespace Yuni::IO; - case errNone: - break; - case errNotFound: - logs.error() << filePath << ": file does not exist"; - break; - case errReadFailed: - logs.error() << "Read failed '" << filePath << "'"; - break; - case errWriteFailed: - logs.error() << "Write failed '" << fullPath << "'"; - break; - default: - logs.error() << "Unhandled error"; - break; + logs.error() << "Error: " << ec.message(); } } void ImmediateFileResultWriter::flush() -{} +{ +} bool ImmediateFileResultWriter::needsTheJobQueue() const { @@ -126,19 +118,28 @@ void ImmediateFileResultWriter::finalize(bool /*verbose*/) } void NullResultWriter::addEntryFromBuffer(const std::string&, Yuni::Clob&) -{} +{ +} + void NullResultWriter::addEntryFromBuffer(const std::string&, std::string&) -{} -void NullResultWriter::addEntryFromFile(const std::string&, const std::string&) -{} +{ +} + +void NullResultWriter::addEntryFromFile(const fs::path&, const fs::path&) +{ +} + void NullResultWriter::flush() -{} +{ +} bool NullResultWriter::needsTheJobQueue() const { return false; } + void NullResultWriter::finalize(bool) -{} +{ +} } // namespace Solver } // namespace Antares diff --git a/src/libs/antares/writer/in_memory_writer.cpp b/src/libs/antares/writer/in_memory_writer.cpp new file mode 100644 index 0000000000..182fee1927 --- /dev/null +++ b/src/libs/antares/writer/in_memory_writer.cpp @@ -0,0 +1,113 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +#include +#include +#include +#include + +namespace Antares::Solver +{ + +namespace +{ + +template +void addToMap(InMemoryWriter::MapType& entries, + const std::string& entryPath, + ContentT& content, + std::mutex& mutex, + Benchmarking::DurationCollector& duration_collector) +{ + std::string entryPathSanitized = entryPath; + std::replace(entryPathSanitized.begin(), entryPathSanitized.end(), '\\', '/'); + + Benchmarking::Timer timer_wait; + std::lock_guard lock(mutex); + timer_wait.stop(); + duration_collector.addDuration("in_memory_wait", timer_wait.get_duration()); + + Benchmarking::Timer timer_insert; + entries.insert({entryPathSanitized, content}); + timer_insert.stop(); + duration_collector.addDuration("in_memory_insert", timer_insert.get_duration()); +} +} // namespace + +InMemoryWriter::InMemoryWriter(Benchmarking::DurationCollector& duration_collector): + pDurationCollector(duration_collector) +{ +} + +InMemoryWriter::~InMemoryWriter() = default; + +void InMemoryWriter::addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) +{ + addToMap(pEntries, entryPath, entryContent, pMapMutex, pDurationCollector); +} + +void InMemoryWriter::addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) +{ + addToMap(pEntries, entryPath, entryContent, pMapMutex, pDurationCollector); +} + +void InMemoryWriter::addEntryFromFile(const fs::path& entryPath, const fs::path& filePath) +{ + // Shamelessly copy-pasted from zip_writer.cpp + // TODO refactor + std::string buffer = IO::readFile(filePath); + + addToMap(pEntries, entryPath.string(), buffer, pMapMutex, pDurationCollector); +} + +void InMemoryWriter::flush() +{ + // Nothing to do here +} + +bool InMemoryWriter::needsTheJobQueue() const +{ + // We may reconsider if performance is atrocious + return false; +} + +void InMemoryWriter::finalize(bool /* verbose */) +{ + // Nothing to do here +} + +const InMemoryWriter::MapType& InMemoryWriter::getMap() const +{ + return pEntries; +} + +} // namespace Antares::Solver diff --git a/src/libs/antares/writer/include/antares/writer/i_writer.h b/src/libs/antares/writer/include/antares/writer/i_writer.h new file mode 100644 index 0000000000..40fd3799ee --- /dev/null +++ b/src/libs/antares/writer/include/antares/writer/i_writer.h @@ -0,0 +1,62 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include +#include +#include + +#include + +namespace Antares::Solver +{ + +class IResultWriter +{ +public: + using Ptr = std::shared_ptr; + virtual void addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) = 0; + virtual void addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) = 0; + virtual void addEntryFromFile(const std::filesystem::path& entryPath, + const std::filesystem::path& filePath) + = 0; + + /*! + * Waits for completion of every write operation previously appended. + * A runtime error may be raised if any of those fails. + */ + virtual void flush() = 0; + virtual bool needsTheJobQueue() const = 0; + virtual void finalize(bool verbose) = 0; +}; + +class NullResultWriter: public Solver::IResultWriter +{ + void addEntryFromBuffer(const std::string&, Yuni::Clob&) override; + void addEntryFromBuffer(const std::string&, std::string&) override; + void addEntryFromFile(const std::filesystem::path&, const std::filesystem::path&) override; + void flush() override; + bool needsTheJobQueue() const override; + void finalize(bool) override; +}; + +} // namespace Antares::Solver diff --git a/src/libs/antares/writer/include/antares/writer/in_memory_writer.h b/src/libs/antares/writer/include/antares/writer/in_memory_writer.h new file mode 100644 index 0000000000..9fc465a83f --- /dev/null +++ b/src/libs/antares/writer/include/antares/writer/in_memory_writer.h @@ -0,0 +1,56 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include +#include + +#include + +#include +#include "antares/writer/i_writer.h" + +namespace Antares::Solver +{ +class InMemoryWriter: public IResultWriter +{ +public: + using MapType = std::map>; + explicit InMemoryWriter(Benchmarking::DurationCollector& duration_collector); + virtual ~InMemoryWriter(); + void addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) override; + void addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) override; + void addEntryFromFile(const std::filesystem::path& entryPath, + const std::filesystem::path& filePath) override; + void flush() override; + bool needsTheJobQueue() const override; + void finalize(bool verbose) override; + const MapType& getMap() const; + +private: + std::mutex pMapMutex; + // minizip-ng requires a void* as a zip handle. + MapType pEntries; + // State, to allow/prevent new jobs being added to the queue + Benchmarking::DurationCollector& pDurationCollector; +}; +} // namespace Antares::Solver diff --git a/src/libs/antares/writer/include/antares/writer/result_format.h b/src/libs/antares/writer/include/antares/writer/result_format.h new file mode 100644 index 0000000000..8f9a209fe0 --- /dev/null +++ b/src/libs/antares/writer/include/antares/writer/result_format.h @@ -0,0 +1,40 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +// +// Created by marechaljas on 10/08/23. +// + +#pragma once + +namespace Antares::Data +{ +// Format of results +enum ResultFormat +{ + // Store outputs as files inside directories + legacyFilesDirectories = 0, + // Store outputs inside a single zip archive + zipArchive, + // Store outputs in-memory + inMemory +}; +} // namespace Antares::Data diff --git a/src/libs/antares/writer/include/antares/writer/writer_factory.h b/src/libs/antares/writer/include/antares/writer/writer_factory.h new file mode 100644 index 0000000000..8e2d76cef7 --- /dev/null +++ b/src/libs/antares/writer/include/antares/writer/writer_factory.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include +#include + +#include "i_writer.h" +#include "result_format.h" + +namespace Benchmarking +{ +class DurationCollector; +} + +namespace Antares::Solver +{ +IResultWriter::Ptr resultWriterFactory(Antares::Data::ResultFormat fmt, + const YString& folderOutput, + std::shared_ptr qs, + Benchmarking::DurationCollector& duration_collector); +} diff --git a/src/libs/antares/writer/private/ensure_queue_started.h b/src/libs/antares/writer/private/ensure_queue_started.h index 691cc29c79..a2f82a2fa3 100644 --- a/src/libs/antares/writer/private/ensure_queue_started.h +++ b/src/libs/antares/writer/private/ensure_queue_started.h @@ -1,8 +1,28 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once -#include "antares/writer/i_writer.h" - #include +#include "antares/writer/i_writer.h" + namespace Antares { namespace Solver diff --git a/src/libs/antares/writer/private/immediate_file_writer.h b/src/libs/antares/writer/private/immediate_file_writer.h index 91f45719e5..1f4decc786 100644 --- a/src/libs/antares/writer/private/immediate_file_writer.h +++ b/src/libs/antares/writer/private/immediate_file_writer.h @@ -1,12 +1,34 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include + #include + #include "antares/writer/i_writer.h" namespace Antares::Solver { -class ImmediateFileResultWriter : public IResultWriter +class ImmediateFileResultWriter: public IResultWriter { public: ImmediateFileResultWriter(const char* folderOutput); @@ -14,13 +36,13 @@ class ImmediateFileResultWriter : public IResultWriter // Write to file immediately, creating directories if needed void addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) override; void addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) override; - void addEntryFromFile(const std::string& entryPath, const std::string& filePath) override; + void addEntryFromFile(const std::filesystem::path& entryPath, + const std::filesystem::path& filePath) override; void flush() override; bool needsTheJobQueue() const override; void finalize(bool verbose) override; private: - Yuni::String pOutputFolder; + std::string pOutputFolder; }; } // namespace Antares::Solver - diff --git a/src/libs/antares/writer/private/zip_writer.h b/src/libs/antares/writer/private/zip_writer.h index 4b3f076742..3b9256f3e8 100644 --- a/src/libs/antares/writer/private/zip_writer.h +++ b/src/libs/antares/writer/private/zip_writer.h @@ -1,15 +1,34 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include #include -#include #include +#include -#include "antares/writer/i_writer.h" #include #include "antares/concurrency/concurrency.h" - +#include "antares/writer/i_writer.h" namespace Antares::Solver { @@ -30,11 +49,13 @@ class ZipWriteJob { public: ZipWriteJob(ZipWriter& writer, - std::string entryPath, + std::string entryPath, ContentT& content, - Benchmarking::IDurationCollector& duration_collector); + Benchmarking::DurationCollector& duration_collector); void writeEntry(); - void operator()() { + + void operator()() + { writeEntry(); } @@ -50,19 +71,20 @@ class ZipWriteJob // Content of the new file ContentT pContent; // Benchmarking. How long do we wait ? How long does the zip write take ? - Benchmarking::IDurationCollector& pDurationCollector; + Benchmarking::DurationCollector& pDurationCollector; }; -class ZipWriter : public IResultWriter +class ZipWriter: public IResultWriter { public: ZipWriter(std::shared_ptr qs, const char* archivePath, - Benchmarking::IDurationCollector& duration_collector); + Benchmarking::DurationCollector& duration_collector); virtual ~ZipWriter(); void addEntryFromBuffer(const std::string& entryPath, Yuni::Clob& entryContent) override; void addEntryFromBuffer(const std::string& entryPath, std::string& entryContent) override; - void addEntryFromFile(const std::string& entryPath, const std::string& filePath) override; + void addEntryFromFile(const std::filesystem::path& entryPath, + const std::filesystem::path& filePath) override; void flush() override; bool needsTheJobQueue() const override; void finalize(bool verbose) override; @@ -81,7 +103,7 @@ class ZipWriter : public IResultWriter // Absolute path to the archive const std::string pArchivePath; // Benchmarking. Passed to jobs - Benchmarking::IDurationCollector& pDurationCollector; + Benchmarking::DurationCollector& pDurationCollector; Concurrency::FutureSet pendingTasks_; @@ -91,5 +113,4 @@ class ZipWriter : public IResultWriter }; } // namespace Antares::Solver - #include "zip_writer.hxx" diff --git a/src/libs/antares/writer/private/zip_writer.hxx b/src/libs/antares/writer/private/zip_writer.hxx index a933f94a5b..a435768b5a 100644 --- a/src/libs/antares/writer/private/zip_writer.hxx +++ b/src/libs/antares/writer/private/zip_writer.hxx @@ -1,6 +1,27 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include "antares/concurrency/concurrency.h" + #include "ensure_queue_started.h" namespace Antares::Solver @@ -9,12 +30,15 @@ template void ZipWriter::addEntryFromBufferHelper(const std::string& entryPath, ContentType& entryContent) { if (pState != ZipState::can_receive_data) + { return; + } EnsureQueueStartedIfNeeded ensureQueue(this, pQueueService); - pendingTasks_.add(Concurrency::AddTask(*pQueueService, - ZipWriteJob(*this, entryPath, entryContent, pDurationCollector), - Yuni::Job::priorityLow)); + pendingTasks_.add(Concurrency::AddTask( + *pQueueService, + ZipWriteJob(*this, entryPath, entryContent, pDurationCollector), + Yuni::Job::priorityLow)); } } // namespace Antares::Solver diff --git a/src/libs/antares/writer/writer_factory.cpp b/src/libs/antares/writer/writer_factory.cpp index 6ab416a717..ec5acd03d2 100644 --- a/src/libs/antares/writer/writer_factory.cpp +++ b/src/libs/antares/writer/writer_factory.cpp @@ -1,4 +1,27 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "antares/writer/writer_factory.h" + +#include "antares/writer/in_memory_writer.h" + #include "private/immediate_file_writer.h" #include "private/zip_writer.h" @@ -7,17 +30,18 @@ namespace Antares::Solver IResultWriter::Ptr resultWriterFactory(Antares::Data::ResultFormat fmt, const YString& folderOutput, std::shared_ptr qs, - Benchmarking::IDurationCollector& duration_collector) + Benchmarking::DurationCollector& duration_collector) { using namespace Antares::Data; switch (fmt) { case zipArchive: return std::make_shared(qs, folderOutput.c_str(), duration_collector); + case inMemory: + return std::make_shared(duration_collector); case legacyFilesDirectories: default: return std::make_shared(folderOutput.c_str()); } } } // namespace Antares::Solver - diff --git a/src/libs/antares/writer/zip_writer.cpp b/src/libs/antares/writer/zip_writer.cpp index 383dd9828d..6359460f8a 100644 --- a/src/libs/antares/writer/zip_writer.cpp +++ b/src/libs/antares/writer/zip_writer.cpp @@ -1,35 +1,54 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "zip_writer.h" + +#include +#include #include -#include // Yuni::IO::File::LoadFromFile -#include "private/zip_writer.h" -#include "antares/logs/logs.h" -#include #include +#include +#include "antares/logs/logs.h" extern "C" { #include -#include #include +#include #include } #include // std::time -#include #include +#include -namespace Antares::Solver -{ +namespace fs = std::filesystem; -namespace +namespace Antares::Solver { -void logErrorAndThrow(const std::string& errorMessage) +static void logErrorAndThrow [[noreturn]] (const std::string& errorMessage) { logs.error() << errorMessage; - throw IOError(errorMessage); -} - + throw std::runtime_error(errorMessage); } // Class ZipWriteJob @@ -37,13 +56,13 @@ template ZipWriteJob::ZipWriteJob(ZipWriter& writer, std::string entryPath, ContentT& content, - Benchmarking::IDurationCollector& duration_collector) : - pZipHandle(writer.pZipHandle), - pZipMutex(writer.pZipMutex), - pState(writer.pState), - pEntryPath(std::move(entryPath)), - pContent(std::move(content)), - pDurationCollector(duration_collector) + Benchmarking::DurationCollector& duration_collector): + pZipHandle(writer.pZipHandle), + pZipMutex(writer.pZipMutex), + pState(writer.pState), + pEntryPath(std::move(entryPath)), + pContent(std::move(content)), + pDurationCollector(duration_collector) { } @@ -63,12 +82,14 @@ void ZipWriteJob::writeEntry() { // Don't write data if finalize() has been called if (pState != ZipState::can_receive_data) + { return; + } auto file_info = createInfo(pEntryPath); Benchmarking::Timer timer_wait; - std::lock_guard guard(pZipMutex); // Wait + std::lock_guard guard(pZipMutex); // Wait timer_wait.stop(); pDurationCollector.addDuration("zip_wait", timer_wait.get_duration()); @@ -82,7 +103,7 @@ void ZipWriteJob::writeEntry() if (static_cast(bw) != pContent.size()) { logErrorAndThrow("Error writing entry " + pEntryPath + "(written = " + std::to_string(bw) - + ", size = " + std::to_string(pContent.size()) + ")"); + + ", size = " + std::to_string(pContent.size()) + ")"); } timer_write.stop(); @@ -92,16 +113,17 @@ void ZipWriteJob::writeEntry() // Class ZipWriter ZipWriter::ZipWriter(std::shared_ptr qs, const char* archivePath, - Benchmarking::IDurationCollector& duration_collector) : - pQueueService(qs), - pState(ZipState::can_receive_data), - pArchivePath(std::string(archivePath) + ".zip"), - pDurationCollector(duration_collector) + Benchmarking::DurationCollector& duration_collector): + pQueueService(qs), + pState(ZipState::can_receive_data), + pArchivePath(std::string(archivePath) + ".zip"), + pDurationCollector(duration_collector) { - mz_zip_writer_create(&pZipHandle); + pZipHandle = mz_zip_writer_create(); if (int32_t ret = mz_zip_writer_open_file(pZipHandle, pArchivePath.c_str(), 0, 0); ret != MZ_OK) { - logErrorAndThrow("Error opening zip file " + pArchivePath + " (" + std::to_string(ret) + ")"); + logErrorAndThrow("Error opening zip file " + pArchivePath + " (" + std::to_string(ret) + + ")"); } // TODO : make level of compression configurable mz_zip_writer_set_compress_level(pZipHandle, MZ_COMPRESS_LEVEL_FAST); @@ -110,7 +132,9 @@ ZipWriter::ZipWriter(std::shared_ptr qs, ZipWriter::~ZipWriter() { if (!pZipHandle) + { return; + } try { @@ -132,29 +156,29 @@ void ZipWriter::addEntryFromBuffer(const std::string& entryPath, std::string& en addEntryFromBufferHelper(entryPath, entryContent); } -void ZipWriter::addEntryFromFile(const std::string& entryPath, const std::string& filePath) +static std::string readFile(const fs::path& filePath) { - // Read file into buffer immediately, write into archive async - Yuni::Clob buffer; - switch (Yuni::IO::File::LoadFromFile(buffer, filePath.c_str())) + std::ifstream file(filePath, std::ios_base::binary | std::ios_base::in); + if (!file.is_open()) { - using namespace Yuni::IO; - case errNone: - addEntryFromBufferHelper(entryPath, buffer); - break; - case errNotFound: - logErrorAndThrow(filePath + ": file does not exist"); - break; - case errReadFailed: - logErrorAndThrow("Read failed '" + filePath + "'"); - break; - case errMemoryLimit: - logErrorAndThrow("Size limit hit for file '" + filePath + "'"); - break; - default: - logErrorAndThrow("Unhandled error"); - break; + logErrorAndThrow(filePath.string() + ": file does not exist"); } + + using Iterator = std::istreambuf_iterator; + std::string content(Iterator{file}, Iterator{}); + if (!file) + { + logErrorAndThrow("Read failed '" + filePath.string() + "'"); + } + return content; +} + +void ZipWriter::addEntryFromFile(const fs::path& entryPath, const fs::path& filePath) +{ + // Read file into buffer immediately, write into archive async + std::string buffer = readFile(filePath); + + addEntryFromBufferHelper(entryPath.string(), buffer); } bool ZipWriter::needsTheJobQueue() const @@ -164,27 +188,35 @@ bool ZipWriter::needsTheJobQueue() const void ZipWriter::finalize(bool verbose) { - //wait for completion of pending writing tasks + // wait for completion of pending writing tasks flush(); // Prevent new jobs from being submitted pState = ZipState::blocking; if (!pZipHandle) + { return; + } if (verbose) + { logs.notice() << "Writing results..."; + } - std::lock_guard guard(pZipMutex); + std::lock_guard guard(pZipMutex); if (int ret = mz_zip_writer_close(pZipHandle); ret != MZ_OK && verbose) + { logs.warning() << "Error closing the zip file " << pArchivePath << " (" << ret << ")"; + } mz_zip_writer_delete(&pZipHandle); pZipHandle = nullptr; if (verbose) + { logs.notice() << "Done"; + } } void ZipWriter::flush() diff --git a/src/libs/antares/xpansion.h b/src/libs/antares/xpansion.h deleted file mode 100644 index 5405eee1f7..0000000000 --- a/src/libs/antares/xpansion.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once - -/*! Enable / Disable the expansion mode */ -#define STUDY_MODE_EXPANSION 0 diff --git a/src/libs/fswalker/CMakeLists.txt b/src/libs/fswalker/CMakeLists.txt index e115b444e2..0745636c9b 100644 --- a/src/libs/fswalker/CMakeLists.txt +++ b/src/libs/fswalker/CMakeLists.txt @@ -13,12 +13,15 @@ add_library(antares-fswalker job.cpp ) +add_library(Antares::fswalker ALIAS antares-fswalker) + target_include_directories(antares-fswalker - PRIVATE + PUBLIC ${CMAKE_SOURCE_DIR}/libs ) target_link_libraries(antares-fswalker PRIVATE yuni-static-core + antares-core logs ) diff --git a/src/libs/fswalker/filejob.inc.hxx b/src/libs/fswalker/filejob.inc.hxx index dc002ce50c..11a3863ae3 100644 --- a/src/libs/fswalker/filejob.inc.hxx +++ b/src/libs/fswalker/filejob.inc.hxx @@ -1,42 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FS_WALKER_FILEJOB_H__ #define __ANTARES_FS_WALKER_FILEJOB_H__ +#include "registry.inc.hxx" + using namespace Yuni; namespace FSWalker { -class FileJob : public IJob +class FileJob: public IJob { public: - FileJob(EventsRegistry& events) : events(events) + FileJob(EventsRegistry& events): + events(events) { } + virtual ~FileJob() { } @@ -67,7 +65,9 @@ void FileJob::onExecute() void* user = events.file.userdata[e]; for (uint i = 0; i != files.size(); ++i) + { (*access)(files[i], parents[i], modified[i], filessize[i], user); + } } } diff --git a/src/libs/fswalker/fswalker.cpp b/src/libs/fswalker/fswalker.cpp index 11fd1affa0..403572bb3e 100644 --- a/src/libs/fswalker/fswalker.cpp +++ b/src/libs/fswalker/fswalker.cpp @@ -1,52 +1,51 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "fswalker.h" -#include -#include + +#include #include -#include +#include +#include + #include -#include -#include #include #include -#include -#include "registry.inc.hxx" -#include "filejob.inc.hxx" +#include +#include +#include + +#include #include +#include "filejob.inc.hxx" +#include "registry.inc.hxx" + using namespace Yuni; using namespace Antares; namespace FSWalker { -//! Mutex for the global queueservice -static Yuni::Mutex gsMutex; + +static std::mutex gsMutex; //!< Mutex for the global queueservice static bool queueserviceInitialized = false; //! Global Queue service static Job::QueueService queueservice; @@ -101,12 +100,14 @@ class WalkerThread final void waitForAllJobs() const; private: - class DirectoryContext final : private Yuni::NonCopyable + class DirectoryContext final: private Yuni::NonCopyable { public: using Stack = std::stack; - explicit DirectoryContext(const String& path) : info(path), cursor(info.begin()) + explicit DirectoryContext(const String& path): + info(path), + cursor(info.begin()) { // Currently bug // info.directory() = path; @@ -116,6 +117,7 @@ class WalkerThread final IO::Directory::Info info; IO::Directory::Info::iterator cursor; }; + //! Directory stack std::list pStack; //! Context @@ -133,12 +135,14 @@ class WalkerThread final }; // class WalkerThread -WalkerThread::WalkerThread(Statistics& stats) : pFileJob(nullptr), pOriginalStatistics(stats) +WalkerThread::WalkerThread(Statistics& stats): + pFileJob(nullptr), + pOriginalStatistics(stats) { - pJobCounter = std::make_shared>(); + pJobCounter = std::make_shared>(); pShouldStop = false; - MutexLocker locker(gsMutex); + std::lock_guard locker(gsMutex); if (not queueserviceInitialized) { queueserviceInitialized = true; @@ -146,11 +150,17 @@ WalkerThread::WalkerThread(Statistics& stats) : pFileJob(nullptr), pOriginalStat // jobCount == 0 uint core = System::CPU::Count(); if (core < 3) + { core = 3; + } else if (core >= 16) + { core -= 4; + } else if (core > 4) + { core -= 1; + } logs.info() << "queueservice: " << core << " workers"; queueservice.maximumThreadCount(core); @@ -257,7 +267,7 @@ bool WalkerThread::triggerFileEvent(const String& filename, int64_t modified, uint64_t size) { - assert(pFileJob != NULL); + assert(pFileJob); // Statistics ++statistics.fileCount; @@ -279,9 +289,12 @@ bool WalkerThread::triggerFileEvent(const String& filename, // timeout in ms based on constants timeout = maxFilesPerJob * maxJobsInQueueReducedPressure / 4, }; + SuspendMilliSeconds(timeout); if (pShouldStop) + { return false; + } } while (queueservice.waitingJobsCount() > maxJobsInQueueReducedPressure); logs.debug() << logPrefix << " :: resuming"; } @@ -298,18 +311,22 @@ bool WalkerThread::triggerFileEvent(const String& filename, void WalkerThread::walk(const String& path) { if (not onDirectoryEnter(path)) // nothing to walk through + { return; + } // Should we take care of files ? bool handleSingleFiles = not events.file.access.empty(); do { - assert(pContext.top() != NULL); + assert(pContext.top()); auto& context = *(pContext.top()); if (pShouldStop) + { break; + } // Iterating all files { @@ -326,7 +343,9 @@ void WalkerThread::walk(const String& path) auto size = context.cursor.size(); auto modified = context.cursor.modified(); if (not triggerFileEvent(filename, parent, modified, size)) + { return; + } } // next entry @@ -342,7 +361,9 @@ void WalkerThread::walk(const String& path) ++context.cursor; if (pShouldStop) + { break; + } } else { @@ -356,7 +377,9 @@ void WalkerThread::walk(const String& path) } if (reloop) + { continue; + } } // Leaving directories @@ -364,7 +387,9 @@ void WalkerThread::walk(const String& path) { onDirectoryLeave(); if (pStack.empty() || pContext.top()->cursor.valid()) + { break; + } } while (true); } while (not pStack.empty()); @@ -419,7 +444,9 @@ void WalkerThread::waitForAllJobs() const Suspend(2); // checking if we were asked to stop if (pShouldStop) + { break; + } } while (true); } } @@ -434,11 +461,14 @@ void WalkerThread::dispatchJob(IJob::Ptr job) const queueservice += job; } -Walker::Walker() : pJobCount(0) +Walker::Walker(): + pJobCount(0) { } -Walker::Walker(const AnyString& logprefix) : pJobCount(0), pLogPrefix(logprefix) +Walker::Walker(const AnyString& logprefix): + pJobCount(0), + pLogPrefix(logprefix) { } @@ -472,19 +502,22 @@ void Walker::run() pStats.aborted = false; if (pDirectory.empty()) + { return; + } // If there is no extensions, there is nothing to do if (pExtensions.empty()) + { return; + } // Sorting extensions by they priority in the reverse order // higher priority must be executed first std::sort(pExtensions.begin(), pExtensions.end(), - [](const IExtension::Ptr& a, const IExtension::Ptr& b) { - return b->priority() < a->priority(); - }); + [](const IExtension::Ptr& a, const IExtension::Ptr& b) + { return b->priority() < a->priority(); }); // The process has aborted by default from now on pStats.aborted = true; @@ -496,7 +529,7 @@ void Walker::run() thread->logPrefix = pLogPrefix; // Extensions DispatchJobEvent callback; - callback.bind(thread, &WalkerThread::dispatchJob); + callback = std::bind(&WalkerThread::dispatchJob, thread, std::placeholders::_1); thread->events.initialize(pExtensions, callback); // Starting the thread ! @@ -517,6 +550,8 @@ void Walker::retrieveStatistics(Statistics& out) void Walker::add(IExtension::Ptr extension) { if (!(!extension)) + { pExtensions.push_back(extension); + } } } // namespace FSWalker diff --git a/src/libs/fswalker/fswalker.h b/src/libs/fswalker/fswalker.h index bbfc433db7..c1daf29c66 100644 --- a/src/libs/fswalker/fswalker.h +++ b/src/libs/fswalker/fswalker.h @@ -1,41 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FS_WALKER_FS_WALKER_H__ #define __ANTARES_FS_WALKER_FS_WALKER_H__ +#include + #include -#include -#include #include #include -#include "statistics.h" -#include "job.h" +#include +#include -#include +#include "job.h" +#include "statistics.h" namespace FSWalker { @@ -55,7 +50,7 @@ using OnFileEvent = void (*)(const YString& filename, uint64_t size, void* user); //! Event for dispatching a new job -using DispatchJobEvent = Yuni::Bind; +using DispatchJobEvent = std::function; class IExtension { @@ -72,6 +67,7 @@ class IExtension IExtension() { } + /*! ** \brief Destructor */ @@ -128,7 +124,7 @@ class IExtension /*! ** This class is thread-safe. */ -class Walker final : public Yuni::NonCopyable +class Walker final: public Yuni::NonCopyable { public: Walker(); diff --git a/src/libs/fswalker/job.cpp b/src/libs/fswalker/job.cpp index 41331047ea..662514afba 100644 --- a/src/libs/fswalker/job.cpp +++ b/src/libs/fswalker/job.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "job.h" @@ -43,7 +37,9 @@ IJob::~IJob() { InternalJobCounter counter = pJobCounter; if (!(!counter)) + { --(*counter); + } } } // namespace FSWalker diff --git a/src/libs/fswalker/job.h b/src/libs/fswalker/job.h index 483be5c7ed..b7a109bac9 100644 --- a/src/libs/fswalker/job.h +++ b/src/libs/fswalker/job.h @@ -1,37 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FS_WALKER_JOB_H__ #define __ANTARES_FS_WALKER_JOB_H__ +#include +#include + #include #include -#include - namespace FSWalker { // Forward declaration @@ -39,9 +34,9 @@ class Walker; class WalkerThread; //! Internal job counter -using InternalJobCounter = std::shared_ptr>; +using InternalJobCounter = std::shared_ptr>; -class IJob : public Yuni::Job::IJob +class IJob: public Yuni::Job::IJob { public: //! The most suitable smart pointer for the class @@ -51,6 +46,7 @@ class IJob : public Yuni::Job::IJob IJob() { } + virtual ~IJob(); protected: diff --git a/src/libs/fswalker/registry.inc.hxx b/src/libs/fswalker/registry.inc.hxx index 95dca1e130..c44b001eb9 100644 --- a/src/libs/fswalker/registry.inc.hxx +++ b/src/libs/fswalker/registry.inc.hxx @@ -1,39 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FS_WALKER_REGISTRY_H__ #define __ANTARES_FS_WALKER_REGISTRY_H__ +#include + #include #include -#include namespace FSWalker { -class EventsRegistry : private Yuni::NonCopyable +class EventsRegistry: private Yuni::NonCopyable { public: using OnDirectoryEventList = std::vector; @@ -45,6 +40,7 @@ public: EventsRegistry() { } + ~EventsRegistry(); void initialize(const IExtension::Vector& exts, DispatchJobEvent& queue); void finalize(); @@ -78,13 +74,17 @@ inline EventsRegistry::~EventsRegistry() void EventsRegistry::finalize() { if (extensions.empty()) + { return; + } for (uint i = 0; i != extensions.size(); ++i) { void* userdata = uniqueUserdata[i]; if (!userdata) + { continue; + } auto& extension = *(extensions[i]); // release ressources diff --git a/src/libs/fswalker/statistics.h b/src/libs/fswalker/statistics.h index 2325b0ad3c..6d8176e544 100644 --- a/src/libs/fswalker/statistics.h +++ b/src/libs/fswalker/statistics.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FS_WALKER_STATISTICS_H__ #define __ANTARES_FS_WALKER_STATISTICS_H__ @@ -34,7 +28,11 @@ namespace FSWalker class Statistics { public: - Statistics() : fileCount(0), folderCount(0), bytesCopied(0), aborted(true) + Statistics(): + fileCount(0), + folderCount(0), + bytesCopied(0), + aborted(true) { } diff --git a/src/packaging/CMakeLists.txt b/src/packaging/CMakeLists.txt new file mode 100644 index 0000000000..868cd7a8ec --- /dev/null +++ b/src/packaging/CMakeLists.txt @@ -0,0 +1,124 @@ +########################## +# This file contains the instructions to generate the Antares package and install it +# Installing a target requires to know its dependency and so on thus the long list below +# + +include(GNUInstallDirs) +# generate and install export file +set(TARGET_LIBS #No alias + #each "block" of dependency describe the dependency for a target + #not dependency is present since once a dependency is in the export set + #it is available for everything + + solver_api #What we want to export + + #solver_api + study + study-loader + file-tree-study-loader + antares-solver-simulation + #study + yuni-static-core + array + date + inifile + stdcxx + StudyUtils + utils + correlation + path + mersenne + result_writer + series + antares-core + antares-solver-hydro + exception + benchmarking + antares-solver-variable + lps + + #study-loader + #nothing + + #file-tree-study-loader + application + + #run-mode + infoCollection + + #antares-solver-simulation + concurrency + misc + model_antares + antares-solver-ts-generator + + #lps + #nothing + + #array + io + jit + AntaresMemory + + #date + logs + + #correlation + locator + + #antares-core + antares-config-lib + + #application + solver-lib + sys + signal-handling + antares-solver-variable-info + optimization-options + resources + + #model_antares + infeasible_problem_analysis + + #solver-lib + args_helper + checks + locale + yuni-static-uuid + + antares-solver #executable +) + +install(TARGETS ${TARGET_LIBS} + EXPORT AntaresTargets + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib + RUNTIME DESTINATION bin + INCLUDES DESTINATION include +) + +install(EXPORT AntaresTargets + FILE "AntaresTargets.cmake" + NAMESPACE Antares:: + DESTINATION lib/cmake/Antares +) + +include(CMakePackageConfigHelpers) + +# generate the version file for the config file +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/AntaresConfigVersion.cmake" + VERSION "${version}" + COMPATIBILITY SameMajorVersion +) +# create config file +configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/AntaresConfig.cmake" + INSTALL_DESTINATION cmake +) +# install config files +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/AntaresConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/AntaresConfigVersion.cmake" + DESTINATION lib/cmake/Antares +) diff --git a/src/packaging/Config.cmake.in b/src/packaging/Config.cmake.in new file mode 100644 index 0000000000..c9bcb039e1 --- /dev/null +++ b/src/packaging/Config.cmake.in @@ -0,0 +1,19 @@ +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +find_dependency(Boost REQUIRED) +find_package(minizip-ng QUIET) #Optional, don't use find_dependency it forces return in case of dep not found +if (minizip-ng_FOUND) + add_library(MINIZIP::minizip ALIAS MINIZIP::minizip-ng) +else () + find_dependency(minizip) + if (NOT minizip_FOUND) + message (FATAL_ERROR "Minizip dependency (minizip or minizip-ng) not found.") + endif () +endif () +find_dependency(ortools REQUIRED) +find_dependency(sirius_solver REQUIRED) + +include("${CMAKE_CURRENT_LIST_DIR}/AntaresTargets.cmake") + +check_required_components(Antares) \ No newline at end of file diff --git a/src/ports/sirius-solver/portfile.cmake b/src/ports/sirius-solver/portfile.cmake new file mode 100644 index 0000000000..287994c152 --- /dev/null +++ b/src/ports/sirius-solver/portfile.cmake @@ -0,0 +1,21 @@ +vcpkg_from_github( + OUT_SOURCE_PATH SOURCE_PATH + REPO "rte-france/sirius-solver" + REF "antares-integration-v1.5" + SHA512 19c6c156861bdeb58c2f17f703124d52020c79f9b81734057bf1bc5dff3dbc464179f99aeab6c8c44a84de1f84ed8f4929f9a919d2bf8bd49ac737f656088e19 + HEAD_REF main +) + +vcpkg_cmake_configure( + SOURCE_PATH "${SOURCE_PATH}/src" +) + +vcpkg_cmake_install() + +vcpkg_cmake_config_fixup(PACKAGE_NAME sirius_solver CONFIG_PATH cmake) + +file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/include") + +vcpkg_copy_pdbs() + +file(INSTALL "${SOURCE_PATH}/LICENSE.TXT" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}" RENAME copyright) diff --git a/src/ports/sirius-solver/vcpkg.json b/src/ports/sirius-solver/vcpkg.json new file mode 100644 index 0000000000..ded804499d --- /dev/null +++ b/src/ports/sirius-solver/vcpkg.json @@ -0,0 +1,16 @@ +{ + "name": "sirius-solver", + "version": "1.5", + "port-version": 0, + "description": "Sirius solver", + "dependencies": [ + { + "name": "vcpkg-cmake", + "host": true + }, + { + "name": "vcpkg-cmake-config", + "host": true + } + ] +} diff --git a/src/script_compilation b/src/script_compilation deleted file mode 100755 index abca8cb18c..0000000000 --- a/src/script_compilation +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -ANTARES_SRC=`pwd` - -cd .. - -git submodule update --init --recursive - -cd src/ext - -#export CC=/usr/local/gcc/4.8/bin/gcc-4.8 -#export CXX=/usr/local/gcc/4.8/bin/g++-4.8 - -#wxWidgets -cd ../wxwidgets -mkdir build_gtk -cd build_gtk -../configure --with-gtk --disable-shared -make - -cd $ANTARES_SRC -cmake -DCMAKE_BUILD_TYPE=release -DCMAKE_AR=/usr/bin/gcc-ar -DCMAKE_RANLIB=/usr/bin/gcc-ranlib . -make diff --git a/src/solver/CMakeLists.txt b/src/solver/CMakeLists.txt index 7372ff3b83..13ab3bfa6c 100644 --- a/src/solver/CMakeLists.txt +++ b/src/solver/CMakeLists.txt @@ -2,74 +2,58 @@ OMESSAGE("Antares Solver") #TODO : see to add bigobj support -if(MSVC) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") -endif(MSVC) +if (MSVC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") +endif (MSVC) -add_subdirectory(infeasible-problem-analysis) -add_subdirectory(variable) +add_subdirectory(application) +add_subdirectory(constraints-builder) add_subdirectory(hydro) +add_subdirectory(infeasible-problem-analysis) +add_subdirectory(lps) +add_subdirectory(misc) +add_subdirectory(optimisation) +add_subdirectory(signal-handling) add_subdirectory(simulation) add_subdirectory(ts-generator) -add_subdirectory(aleatoire) add_subdirectory(utils) -add_subdirectory(optimisation) -add_subdirectory(main) -add_subdirectory(constraints-builder) +add_subdirectory(variable) # # Resource file for Windows # -if(WIN32) - file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.o") - FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.rc.cmake" - "${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.rc") - - if(MINGW) - # resource compilation for mingw - add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/win32/solver.o" - COMMAND windres.exe "-I${CMAKE_CURRENT_SOURCE_DIR}" - "-i${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.rc" - -o "${CMAKE_CURRENT_BINARY_DIR}/win32/solver.o") - set(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/solver.o") - else() - set(SRCS ${SRCS} "win32/solver.rc") - endif() -endif() - +if (WIN32) + file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.o") + FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.rc.cmake" + "${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.rc") + + if (MINGW) + # resource compilation for mingw + add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/win32/solver.o" + COMMAND windres.exe "-I${CMAKE_CURRENT_SOURCE_DIR}" + "-i${CMAKE_CURRENT_SOURCE_DIR}/win32/solver.rc" + -o "${CMAKE_CURRENT_BINARY_DIR}/win32/solver.o") + set(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/solver.o") + else () + set(SRCS ${SRCS} "win32/solver.rc") + endif () +endif () OMESSAGE(" :: application solver") -set(exec_name "antares-${ANTARES_PRG_VERSION}-solver") +set(exec_name "antares-solver") + +add_library(solver-lib INTERFACE + ${SRCS} +) add_executable(antares-solver - misc/options.h - misc/options.cpp - misc/process-priority.cpp - misc/cholesky.h - misc/cholesky.hxx - misc/matrix-dp-make.h - misc/matrix-dp-make.hxx - - misc/system-memory.h - misc/system-memory.cpp - - misc/write-command-line.h - misc/write-command-line.cpp - - ${SRCS} - main.cpp - application.h application.cpp - - signal-handling/common.h - signal-handling/public.h - signal-handling/common.cpp - signal-handling/linux.cpp - signal-handling/windows.cpp - ) + main.cpp + ${SRCS} +) set_target_properties(antares-solver PROPERTIES OUTPUT_NAME ${exec_name}) @@ -81,30 +65,38 @@ set(ANTARES_SOLVER_LIBS Antares::sys Antares::infoCollection Antares::checks + Antares::misc + Antares::optimization-options + Antares::signal-handling + Antares::locale yuni-static-uuid yuni-static-core ${CMAKE_THREADS_LIBS_INIT} ) -set(ANTARES_SOLVER_LIBS ${ANTARES_SOLVER_LIBS} - antares-solver-main-economy - antares-solver-main-adequacy - antares-solver-hydro - antares-solver-aleatoire - antares-solver-variable - antares-solver-simulation - antares-solver-ts-generator - model_antares - antares-core) +set(ANTARES_SOLVER_LIBS ${ANTARES_SOLVER_LIBS} + antares-solver-hydro + antares-solver-variable + antares-solver-simulation + antares-solver-ts-generator + model_antares + antares-core +) + +target_link_libraries(solver-lib + INTERFACE + ${ANTARES_SOLVER_LIBS} +) target_link_libraries(antares-solver - PRIVATE - ${ANTARES_SOLVER_LIBS} - ) + PRIVATE + solver-lib + Antares::application +) target_include_directories(antares-solver - PRIVATE - ${CMAKE_SOURCE_DIR}/solver + PRIVATE + ${CMAKE_SOURCE_DIR}/solver ) import_std_libs(antares-solver) @@ -112,13 +104,13 @@ executable_strip(antares-solver) copy_dependency(sirius_solver antares-solver) - - #TODO : not working inside macro install(TARGETS antares-solver EXPORT antares-solver DESTINATION bin) INSTALL(EXPORT antares-solver - FILE antares-solverConfig.cmake - DESTINATION cmake + FILE antares-solverConfig.cmake + DESTINATION cmake ) + +######### \ No newline at end of file diff --git a/src/solver/Config.cmake.in b/src/solver/Config.cmake.in new file mode 100644 index 0000000000..558e74a2bf --- /dev/null +++ b/src/solver/Config.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/solver-libTargets.cmake") + +check_required_components(solver-lib) \ No newline at end of file diff --git a/src/solver/aleatoire/CMakeLists.txt b/src/solver/aleatoire/CMakeLists.txt deleted file mode 100644 index 609d979cd5..0000000000 --- a/src/solver/aleatoire/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -set(SRC_ALEATOIRE - alea_fonctions.h - alea_sys.h - alea_tirage_au_sort_chroniques.cpp) -source_group("aleatoire" FILES ${SRC_ALEATOIRE}) - - -add_library(antares-solver-aleatoire ${SRC_ALEATOIRE}) - -target_include_directories(antares-solver-aleatoire - PRIVATE - ${CMAKE_SOURCE_DIR}/solver) - -target_link_libraries(antares-solver-aleatoire - PUBLIC - Antares::study -) diff --git a/src/solver/aleatoire/alea_fonctions.h b/src/solver/aleatoire/alea_fonctions.h deleted file mode 100644 index e54d825358..0000000000 --- a/src/solver/aleatoire/alea_fonctions.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../simulation/sim_structure_donnees.h" -#include "antares/study/study.h" - -void ApplyRandomTSnumbers(const Antares::Data::Study& study, - unsigned int year, - uint numSpace); \ No newline at end of file diff --git a/src/solver/aleatoire/alea_sys.h b/src/solver/aleatoire/alea_sys.h deleted file mode 100644 index 434e67decb..0000000000 --- a/src/solver/aleatoire/alea_sys.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_RANDOM_SYSHDR_H__ -#define __SOLVER_RANDOM_SYSHDR_H__ - -#include -#include -#include -#include -#include - -#include "../config.h" -#include -#include "../simulation/simulation.h" - -#endif /* __SOLVER_RANDOM_SYSHDR_H__ */ diff --git a/src/solver/aleatoire/alea_tirage_au_sort_chroniques.cpp b/src/solver/aleatoire/alea_tirage_au_sort_chroniques.cpp deleted file mode 100644 index 3739933de0..0000000000 --- a/src/solver/aleatoire/alea_tirage_au_sort_chroniques.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "../simulation/sim_extern_variables_globales.h" -#include "alea_fonctions.h" -#include - -using namespace Yuni; -using namespace Antares; -using namespace Antares::Data; - -void ApplyRandomTSnumbers(const Study& study, - unsigned int year, - uint numSpace) -{ - // ------------------------------ - // Transmission capacities - // ------------------------------ - // each link - for (unsigned int linkIndex = 0; linkIndex < study.runtime->interconnectionsCount(); ++linkIndex) - { - AreaLink* link = study.runtime->areaLink[linkIndex]; - assert(year < link->timeseriesNumbers.height); - NUMERO_CHRONIQUES_TIREES_PAR_INTERCONNEXION& ptchro - = NumeroChroniquesTireesParInterconnexion[numSpace][linkIndex]; - const uint directWidth = link->directCapacities.width; - [[maybe_unused]] const uint indirectWidth = link->indirectCapacities.width; - assert(directWidth == indirectWidth); - ptchro.TransmissionCapacities - = (directWidth != 1) ? link->timeseriesNumbers[0][year] : 0; // zero-based - } - - // ------------------------------ - //Binding constraints - // ------------------------------ - //Setting 0 for time_series of width 0 is done when using the value. - //To do this here we would have to check every BC for its width - for (const auto& group: study.bindingConstraintsGroups) { - [[maybe_unused]] auto number_of_ts_numbers = group->timeseriesNumbers.height; - assert(year < number_of_ts_numbers); //If only 1 ts_number we suppose only one TS. Any "year" will be converted to "0" later - NumeroChroniquesTireesParGroup[numSpace][group->name()] = group->timeseriesNumbers[0][year]; - } -} diff --git a/src/solver/application.cpp b/src/solver/application.cpp deleted file mode 100644 index 3ef40b7ad5..0000000000 --- a/src/solver/application.cpp +++ /dev/null @@ -1,472 +0,0 @@ -#include "application.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "signal-handling/public.h" - -#include "misc/system-memory.h" -#include "misc/write-command-line.h" - -#include "utils/ortools_utils.h" -#include "../config.h" -#include - -#include -#include -#include - -#include - -using namespace Antares::Check; - -namespace -{ -void printSolvers() -{ - std::cout << "Available solvers :" << std::endl; - for (const auto& solver : getAvailableOrtoolsSolverName()) - { - std::cout << solver << std::endl; - } -} -} // namespace - -namespace Antares::Solver -{ -Application::Application() -{ - resetProcessPriority(); -} - -void Application::prepare(int argc, char* argv[]) -{ - pArgc = argc; - pArgv = argv; - - // Load the local policy settings - LocalPolicy::Open(); - LocalPolicy::CheckRootPrefix(argv[0]); - - Resources::Initialize(argc, argv); - - // Options - Data::StudyLoadOptions options; - options.usedByTheSolver = true; - - // Bind pSettings / options members to command line arguments - // Something like bind("--foo", options.foo); - // So that option.foo will be assigned - // if the user provides --foo . - // CAUTION - // The parser contains references to members of pSettings and options, - // don't de-allocate these. - auto parser = CreateParser(pSettings, options); - // Parse the command line arguments - - switch (auto ret = parser->operator()(argc, argv); ret) - { - using namespace Yuni::GetOpt; - case ReturnCode::error: - throw Error::CommandLineArguments(parser->errors()); - break; - case ReturnCode::help: - // End the program - pStudy = nullptr; - return; - default: - break; - } - - if (options.displayVersion) - { - PrintVersionToStdCout(); - pStudy = nullptr; - return; - } - - if (options.listSolvers) - { - printSolvers(); - pStudy = nullptr; - return; - } - - // Perform some checks - checkAndCorrectSettingsAndOptions(pSettings, options); - - pSettings.checkAndSetStudyFolder(options.studyFolder); - - checkStudyVersion(pSettings.studyFolder); - - // Determine the log filename to use for this simulation - resetLogFilename(); - - // Starting ! -#ifdef GIT_SHA1_SHORT_STRING - logs.checkpoint() << "Antares Solver v" << ANTARES_VERSION_STR << " (" << GIT_SHA1_SHORT_STRING - << ")"; -#else - logs.checkpoint() << "Antares Solver v" << ANTARES_VERSION_STR; -#endif - WriteHostInfoIntoLogs(); - - // Write command-line options into logs - // Incidentally, it also seems to contain the full path to the executable - logs.info(); - WriteCommandLineIntoLogs(argc, argv); - - logs.info() << " :: log filename: " << logs.logfile(); - // Temporary use a callback to count the number of errors and warnings - logs.callback.connect(this, &Application::onLogMessage); - - // Allocate a study - pStudy = std::make_shared(true /* for the solver */); - - // Setting global variables for backward compatibility - pParameters = &(pStudy->parameters); - - // Loading the study - readDataForTheStudy(options); - - // Some more checks require the existence of pParameters, hence of a study. - // Their execution is delayed up to this point. - checkSimplexRangeHydroPricing(pParameters->simplexOptimizationRange, - pParameters->hydroPricing.hpMode); - - checkSimplexRangeUnitCommitmentMode(pParameters->simplexOptimizationRange, - pParameters->unitCommitment.ucMode); - - checkSimplexRangeHydroHeuristic(pParameters->simplexOptimizationRange, pStudy->areas); - - if (pParameters->adqPatchParams.enabled) - pParameters->adqPatchParams.checkAdqPatchParams(pParameters->mode, - pStudy->areas, - pParameters->include.hurdleCosts); - - bool tsGenThermal - = (0 != (pParameters->timeSeriesToGenerate & Antares::Data::TimeSeriesType::timeSeriesThermal)); - - checkMinStablePower(tsGenThermal, pStudy->areas); - - checkFuelCostColumnNumber(pStudy->areas); - checkCO2CostColumnNumber(pStudy->areas); - - // Start the progress meter - pStudy->initializeProgressMeter(pSettings.tsGeneratorsOnly); - if (pSettings.noOutput) - pSettings.displayProgression = false; - - if (pSettings.displayProgression) - { - auto& filename = pStudy->buffer; - filename.clear() << "about-the-study" << Yuni::IO::Separator << "map"; - pStudy->progression.saveToFile(filename, *resultWriter); - pStudy->progression.start(); - } - else - logs.info() << " The progression is disabled"; -} - -void Application::initializeRandomNumberGenerators() -{ - logs.info() << "Initializing random number generators..."; - const auto& parameters = pStudy->parameters; - auto& runtime = *pStudy->runtime; - - for (uint i = 0; i != Data::seedMax; ++i) - { -#ifndef NDEBUG - logs.debug() << " random number generator: " << Data::SeedToCString((Data::SeedIndex)i) - << ", seed: " << parameters.seed[i]; -#endif - runtime.random[i].reset(parameters.seed[i]); - } -} - -void Application::onLogMessage(int level, const Yuni::String& /*message*/) -{ - switch (level) - { - case Yuni::Logs::Verbosity::Warning::level: - ++pWarningCount; - break; - case Yuni::Logs::Verbosity::Error::level: - ++pErrorCount; - break; - case Yuni::Logs::Verbosity::Fatal::level: - ++pErrorCount; - break; - default: - break; - } -} - -void Application::execute() -{ - // pStudy == nullptr e.g when the -h flag is given - if (!pStudy) - return; - - processCaption(Yuni::String() << "antares: running \"" << pStudy->header.caption << "\""); - - SystemMemoryLogger memoryReport; - memoryReport.interval(1000 * 60 * 5); // 5 minutes - memoryReport.start(); - - pStudy->computePThetaInfForThermalClusters(); - - // Run the simulation - switch (pStudy->runtime->mode) - { - case Data::stdmEconomy: - runSimulationInEconomicMode(); - break; - case Data::stdmAdequacy: - runSimulationInAdequacyMode(); - break; - default: - break; - } - // TODO : make an interface class for ISimulation, check writer & queue before - // runSimulationInMode() - - // Importing Time-Series if asked - pStudy->importTimeseriesIntoInput(); - - // Stop the display of the progression - pStudy->progression.stop(); -} - -void Application::resetLogFilename() const -{ - // Assigning the log file - Yuni::String logfile; - logfile << pSettings.studyFolder << Yuni::IO::Separator << "logs"; - - // Making sure that the folder - if (!Yuni::IO::Directory::Create(logfile)) - { - throw FatalError(std::string("Impossible to create the log folder at ") + logfile.c_str() + ". Aborting now."); - } - - // Date/time - logfile << Yuni::IO::Separator << "solver-"; - Yuni::DateTime::TimestampToString(logfile, "%Y%m%d-%H%M%S", 0, false); - logfile << ".log"; - - // Assigning the log filename - logs.logfile(logfile); - - if (!logs.logfileIsOpened()) - { - throw FatalError(std::string("Impossible to create the log file at ") + logfile.c_str()); - } -} - -void Application::processCaption(const Yuni::String& caption) -{ - pArgv = Yuni::Process::Rename(pArgc, pArgv, caption); -} - -void Application::prepareWriter(Antares::Data::Study& study, - Benchmarking::IDurationCollector& duration_collector) -{ - ioQueueService = std::make_shared(); - ioQueueService->maximumThreadCount(1); - ioQueueService->start(); - resultWriter = resultWriterFactory( - study.parameters.resultFormat, study.folderOutput, ioQueueService, duration_collector); -} - -void Application::readDataForTheStudy(Data::StudyLoadOptions& options) -{ - processCaption(Yuni::String() << "antares: loading \"" << pSettings.studyFolder << "\""); - auto& study = *pStudy; - - // Name of the simulation - if (!pSettings.simulationName.empty()) - study.simulationComments.name = pSettings.simulationName; - - // Force some options - options.prepareOutput = !pSettings.noOutput; - options.ignoreConstraints = pSettings.ignoreConstraints; - options.loadOnlyNeeded = true; - - // Load the study from a folder - Benchmarking::Timer timer; - - if (study.loadFromFolder(pSettings.studyFolder, options) && !study.gotFatalError) - { - logs.info() << "The study is loaded."; - logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; - } - - timer.stop(); - pDurationCollector.addDuration("study_loading", timer.get_duration()); - - if (study.gotFatalError) - throw Error::ReadingStudy(); - - if (study.areas.empty()) - { - throw Error::NoAreas(); - } - - // no output ? - study.parameters.noOutput = pSettings.noOutput; - - if (pSettings.forceZipOutput) - { - pParameters->resultFormat = Antares::Data::zipArchive; - } - - // This settings can only be enabled from the solver - // Prepare the output for the study - study.prepareOutput(); - - // Initialize the result writer - prepareWriter(study, pDurationCollector); - - Antares::Solver::initializeSignalHandlers(resultWriter); - - // Save about-the-study files (comments, notes, etc.) - study.saveAboutTheStudy(*resultWriter); - - // Name of the simulation (again, if the value has been overwritten) - if (!pSettings.simulationName.empty()) - study.simulationComments.name = pSettings.simulationName; - - // Removing all callbacks, which are no longer needed - logs.callback.clear(); - logs.info(); - - if (pSettings.noOutput) - { - logs.info() << "The output has been disabled."; - logs.info(); - } - - // Errors - if (pErrorCount || pWarningCount || study.gotFatalError) - { - if (pErrorCount || !pSettings.ignoreWarningsErrors) - { - // The loading of the study produces warnings and/or errors - // As the option '--force' is not given, we can not continue - LogDisplayErrorInfos(pErrorCount, pWarningCount, "The simulation must stop."); - throw FatalError("The simulation must stop."); - } - else - { - LogDisplayErrorInfos( - 0, - pWarningCount, - "As requested, the warnings can be ignored and the simulation will continue", - false /* not an error */); - // Actually importing the log file is useless here. - // However, since we have warnings/errors, it allows to have a piece of - // log when the unexpected happens. - if (!study.parameters.noOutput) - study.importLogsToOutputFolder(*resultWriter); - // empty line - logs.info(); - } - } - - // Checking for filename length limits - if (!pSettings.noOutput) - { - if (!study.checkForFilenameLimits(true)) - throw Error::InvalidFileName(); - - // comments - { - study.buffer.clear() << "simulation-comments.txt"; - - if (!pSettings.commentFile.empty()) - { - resultWriter->addEntryFromFile(study.buffer.c_str(), pSettings.commentFile.c_str()); - - pSettings.commentFile.clear(); - pSettings.commentFile.shrink(); - } - } - } - - // Runtime data dedicated for the solver - if (!study.initializeRuntimeInfos()) - throw Error::RuntimeInfoInitialization(); - - // Apply transformations needed by the solver only (and not the interface for example) - study.performTransformationsBeforeLaunchingSimulation(); - - //alloc global vectors - SIM_AllocationTableaux(study); - - // Random-numbers generators - initializeRandomNumberGenerators(); -} - -void Application::writeExectutionInfo() -{ - if (!pStudy) - return; - - // Last missing duration to get : measure of total simulation duration - pTotalTimer.stop(); - pDurationCollector.addDuration("total", pTotalTimer.get_duration()); - - // If no writer is available, we can't write - if (!resultWriter) - return; - - // Info collectors : they retrieve data from study and simulation - Benchmarking::StudyInfoCollector study_info_collector(*pStudy); - Benchmarking::SimulationInfoCollector simulation_info_collector(pOptimizationInfo); - - // Fill file content with data retrieved by collectors - Benchmarking::FileContent file_content; - pDurationCollector.toFileContent(file_content); - study_info_collector.toFileContent(file_content); - simulation_info_collector.toFileContent(file_content); - - // Flush previous info into a record file - const std::string exec_info_path = "execution_info.ini"; - std::string content = file_content.saveToBufferAsIni(); - resultWriter->addEntryFromBuffer(exec_info_path, content); -} - -Application::~Application() -{ - // Destroy all remaining bouns (callbacks) - destroyBoundEvents(); - - // Release all allocated data - if (!(!pStudy)) - { - logs.info() << LOG_UI_SOLVER_DONE; - - // Copy the log file - if (!pStudy->parameters.noOutput) { - pStudy->importLogsToOutputFolder(*resultWriter); - } - - // release all reference to the current study held by this class - pStudy->clear(); - pStudy = nullptr; - - LocalPolicy::Close(); - } -} -} // namespace Antares::Solver - diff --git a/src/solver/application.h b/src/solver/application.h deleted file mode 100644 index 7740087a73..0000000000 --- a/src/solver/application.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once - -#include "misc/options.h" -#include -#include -#include -#include -#include "simulation/simulation.h" -#include "antares/infoCollection/StudyInfoCollector.h" - -#include -#include - -namespace Antares::Solver -{ -class Application : public Yuni::IEventObserver -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - Application(); - /*! - ** \brief Destructor - */ - ~Application() final; - //@} - - Application(const Application&) = delete; - - Application& operator=(const Application&) = delete; - - /*! - ** \brief Initialize data before launching the simulation - ** - ** \return False if the operation failed. - */ - void prepare(int argc, char* argv[]); - - /*! - ** \brief Execute the simulation - ** - ** \return Exit status - */ - void execute(); - - /*! - ** \brief Reset the process priority (Windows only) - */ - void resetProcessPriority() const; - - void writeExectutionInfo(); - - void installSignalHandlers() const; - -private: - /*! - ** \brief Reset the log filename and open it - */ - void resetLogFilename() const; - - /*! - * \brief Load data of the study from a local or remote folder - */ - void readDataForTheStudy(Antares::Data::StudyLoadOptions& options); - - void runSimulationInAdequacyMode(); - void runSimulationInEconomicMode(); - - void initializeRandomNumberGenerators(); - - void onLogMessage(int level, const YString& message); - - void processCaption(const Yuni::String& caption); - - //! The settings given from the command line - Settings pSettings; - //! The current Antares study - Antares::Data::Study::Ptr pStudy = nullptr; - //! General data related to the current study - Antares::Data::Parameters* pParameters = nullptr; - //! The total number of errors which have been generated - uint pErrorCount = 0; - //! The total muber of warnings which have been generated - uint pWarningCount = 0; - - int pArgc; - char** pArgv; - - // Benchmarking - Benchmarking::Timer pTotalTimer; - Benchmarking::DurationCollector pDurationCollector; - Benchmarking::OptimizationInfo pOptimizationInfo; - - std::shared_ptr ioQueueService; - IResultWriter::Ptr resultWriter = nullptr; - - void prepareWriter(Antares::Data::Study& study, - Benchmarking::IDurationCollector& duration_collector); - -}; // class Application -} // namespace Antares::Solver - diff --git a/src/solver/application/CMakeLists.txt b/src/solver/application/CMakeLists.txt new file mode 100644 index 0000000000..9f554a4b9f --- /dev/null +++ b/src/solver/application/CMakeLists.txt @@ -0,0 +1,40 @@ +set(HEADERS + include/antares/application/application.h + include/antares/application/ScenarioBuilderOwner.h +) +set(SRC_APPLICATION + ${HEADERS} + application.cpp + process-priority.cpp + ScenarioBuilderOwner.cpp +) +source_group("application" FILES ${SRC_APPLICATION}) + +add_library(application + ${SRC_APPLICATION} +) +add_library(Antares::application ALIAS application) + +target_link_libraries(application + PUBLIC + yuni-static-core + Antares::study + Antares::infoCollection + solver-lib + PRIVATE + Antares::logs + Antares::sys + Antares::solverUtils + Antares::signal-handling + Antares::resources + Antares::file-tree-study-loader +) + +target_include_directories(application + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/solver/application/ScenarioBuilderOwner.cpp b/src/solver/application/ScenarioBuilderOwner.cpp new file mode 100644 index 0000000000..69f9d11799 --- /dev/null +++ b/src/solver/application/ScenarioBuilderOwner.cpp @@ -0,0 +1,57 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include +#include +#include "antares/solver/simulation/apply-scenario.h" +#include "antares/solver/simulation/timeseries-numbers.h" +#include "antares/solver/ts-generator/generator.h" +#include "antares/study/study.h" + +Antares::Solver::ScenarioBuilderOwner::ScenarioBuilderOwner(Data::Study& study): + study_(study) +{ +} + +void Antares::Solver::ScenarioBuilderOwner::callScenarioBuilder() +{ + TSGenerator::ResizeGeneratedTimeSeries(study_.areas, study_.parameters); + + // Sampled time-series Numbers + // We will resize all matrix related to the time-series numbers + // This operation can be done once since the number of years is constant + // for a single simulation + study_.resizeAllTimeseriesNumbers(1 + study_.runtime->rangeLimits.year[Data::rangeEnd]); + if (not TimeSeriesNumbers::CheckNumberOfColumns(study_.areas)) + { + throw FatalError( + "Inconsistent number of time-series detected. Please check your input data."); + } + + if (not TimeSeriesNumbers::Generate(study_)) + { + throw FatalError("An unrecoverable error has occurred. Can not continue."); + } + if (study_.parameters.useCustomScenario) + { + ApplyCustomScenario(study_); + } +} diff --git a/src/solver/application/application.cpp b/src/solver/application/application.cpp new file mode 100644 index 0000000000..a55873ea09 --- /dev/null +++ b/src/solver/application/application.cpp @@ -0,0 +1,576 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include "antares/application/application.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "antares/antares/version.h" +#include "antares/config/config.h" +#include "antares/signal-handling/public.h" +#include "antares/solver/misc/system-memory.h" +#include "antares/solver/misc/write-command-line.h" +#include "antares/solver/simulation/adequacy_mode.h" +#include "antares/solver/simulation/economy_mode.h" +#include "antares/solver/simulation/simulation.h" +#include "antares/solver/utils/ortools_utils.h" +#include "antares/study/simulation.h" + +using namespace Antares::Check; + +namespace fs = std::filesystem; + +namespace +{ +void printSolvers() +{ + std::cout << "Available solvers: " << availableOrToolsSolversString() << std::endl; +} +} // namespace + +namespace Antares::Solver +{ +Application::Application() +{ + resetProcessPriority(); +} + +bool Application::parseCommandLine(Data::StudyLoadOptions& options) +{ + auto parser = CreateParser(pSettings, options); + auto ret = parser->operator()(pArgc, pArgv); + switch (ret) + { + case Yuni::GetOpt::ReturnCode::error: + throw Error::CommandLineArguments(parser->errors()); + case Yuni::GetOpt::ReturnCode::help: + pStudy = nullptr; + return false; + default: + return true; + } +} + +bool Application::handleOptions(const Data::StudyLoadOptions& options) +{ + if (options.displayVersion) + { + PrintVersionToStdCout(); + pStudy = nullptr; + return false; + } + + if (options.listSolvers) + { + printSolvers(); + pStudy = nullptr; + return false; + } + return true; +} + +void Application::readDataForTheStudy(Data::StudyLoadOptions& options) +{ + auto& study = *pStudy; + + // Name of the simulation + if (!pSettings.simulationName.empty()) + { + study.simulationComments.name = pSettings.simulationName; + } + + // Force some options + options.prepareOutput = !pSettings.noOutput; + options.ignoreConstraints = pSettings.ignoreConstraints; + options.loadOnlyNeeded = true; + + // Load the study from a folder + Benchmarking::Timer timer; + + std::exception_ptr loadingException; + try + { + pDurationCollector("study_loading") << [this, &study, &options] + { + if (study.loadFromFolder(pSettings.studyFolder, options)) + { + logs.info() << "The study is loaded."; + logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; + } + }; + + if (study.areas.empty()) + { + throw Error::NoAreas(); + } + + // no output ? + study.parameters.noOutput = pSettings.noOutput; + + if (pSettings.forceZipOutput) + { + pParameters->resultFormat = Antares::Data::zipArchive; + } + } + catch (...) + { + loadingException = std::current_exception(); + } + + // For solver + study.parameters.optOptions = options.optOptions; + + // This settings can only be enabled from the solver + // Prepare the output for the study + study.prepareOutput(); + + // Initialize the result writer + prepareWriter(study, pDurationCollector); + + // Some checks may have failed, but we need a writer to copy the logs + // to the output directory + // So we wait until we have initialized the writer to rethrow + if (loadingException) + { + std::rethrow_exception(loadingException); + } + + Antares::Solver::initializeSignalHandlers(resultWriter); + + // Save about-the-study files (comments, notes, etc.) + study.saveAboutTheStudy(*resultWriter); + + // Name of the simulation (again, if the value has been overwritten) + if (!pSettings.simulationName.empty()) + { + study.simulationComments.name = pSettings.simulationName; + } + + // Removing all callbacks, which are no longer needed + logs.callback.clear(); + logs.info(); + + if (pSettings.noOutput) + { + logs.info() << "The output has been disabled."; + logs.info(); + } + + // Errors + if (pErrorCount || pWarningCount) + { + if (pErrorCount || !pSettings.ignoreWarningsErrors) + { + // The loading of the study produces warnings and/or errors + // As the option '--force' is not given, we can not continue + LogDisplayErrorInfos(pErrorCount, pWarningCount, "The simulation must stop."); + throw FatalError("The simulation must stop."); + } + else + { + LogDisplayErrorInfos( + 0, + pWarningCount, + "As requested, the warnings can be ignored and the simulation will continue", + false /* not an error */); + // Actually importing the log file is useless here. + // However, since we have warnings/errors, it allows to have a piece of + // log when the unexpected happens. + if (!study.parameters.noOutput) + { + study.importLogsToOutputFolder(*resultWriter); + } + // empty line + logs.info(); + } + } + + // Checking for filename length limits + if (!pSettings.noOutput) + { + if (!study.checkForFilenameLimits(true)) + { + throw Error::InvalidFileName(); + } + + writeComment(study); + } + + // Runtime data dedicated for the solver + if (!study.initializeRuntimeInfos()) + { + throw Error::RuntimeInfoInitialization(); + } + + // Apply transformations needed by the solver only (and not the interface for example) + study.performTransformationsBeforeLaunchingSimulation(); + + ScenarioBuilderOwner(study).callScenarioBuilder(); + + // alloc global vectors + SIM_AllocationTableaux(study); +} + +void Application::startSimulation(Data::StudyLoadOptions& options) +{ +// Starting ! +#ifdef GIT_SHA1_SHORT_STRING + logs.checkpoint() << "Antares Solver v" << ANTARES_VERSION_STR << " (" << GIT_SHA1_SHORT_STRING + << ")"; +#else + logs.checkpoint() << "Antares Solver v" << ANTARES_VERSION_STR; +#endif + WriteHostInfoIntoLogs(); + + WriteCommandLineIntoLogs(pArgc, pArgv); + + logs.info() << " :: log filename: " << logs.logfile(); + + logs.callback.connect(this, &Application::onLogMessage); + + pStudy = std::make_unique(true /* for the solver */); + + pParameters = &(pStudy->parameters); + readDataForTheStudy(options); + + postParametersChecks(); + + pStudy->initializeProgressMeter(pSettings.tsGeneratorsOnly); + if (pSettings.noOutput) + { + pSettings.displayProgression = false; + } + + if (pSettings.displayProgression) + { + auto& filename = pStudy->buffer; + filename.clear() << "about-the-study" << Yuni::IO::Separator << "map"; + pStudy->progression.saveToFile(filename, *resultWriter); + pStudy->progression.start(); + } + else + { + logs.info() << " The progression is disabled"; + } +} + +void Application::postParametersChecks() const +{ // Some more checks require the existence of pParameters, hence of a study. + // Their execution is delayed up to this point. + checkOrtoolsUsage(pParameters->unitCommitment.ucMode, + pParameters->optOptions.ortoolsUsed, + pParameters->optOptions.ortoolsSolver); + + checkSimplexRangeHydroPricing(pParameters->simplexOptimizationRange, + pParameters->hydroPricing.hpMode); + + checkSimplexRangeUnitCommitmentMode(pParameters->simplexOptimizationRange, + pParameters->unitCommitment.ucMode); + + checkSimplexRangeHydroHeuristic(pParameters->simplexOptimizationRange, pStudy->areas); + + if (pParameters->adqPatchParams.enabled) + { + pParameters->adqPatchParams.checkAdqPatchParams(pParameters->mode, + pStudy->areas, + pParameters->include.hurdleCosts); + } + + bool tsGenThermal = (0 + != (pParameters->timeSeriesToGenerate + & Antares::Data::TimeSeriesType::timeSeriesThermal)); + + checkMinStablePower(tsGenThermal, pStudy->areas); + + checkFuelCostColumnNumber(pStudy->areas); + checkCO2CostColumnNumber(pStudy->areas); +} + +void Application::prepare(int argc, char* argv[]) +{ + pArgc = argc; + pArgv = argv; + + // Load the local policy settings + LocalPolicy::Open(); + LocalPolicy::CheckRootPrefix(argv[0]); + + Resources::Initialize(argc, argv); + + // Options + Data::StudyLoadOptions options; + options.usedByTheSolver = true; + + // Bind pSettings / options members to command line arguments + // Something like bind("--foo", options.foo); + // So that option.foo will be assigned + // if the user provides --foo . + // CAUTION + // The parser contains references to members of pSettings and options, + // don't de-allocate these. + + if (!parseCommandLine(options)) // --help + { + return; + } + + if (!handleOptions(options)) // --version, --list-solvers + { + return; + } + + // Perform some checks + checkAndCorrectSettingsAndOptions(pSettings, options); + + pSettings.checkAndSetStudyFolder(options.studyFolder); + + checkStudyVersion(pSettings.studyFolder); + + // Determine the log filename to use for this simulation + resetLogFilename(); + + startSimulation(options); +} + +void Application::onLogMessage(int level, const std::string& /*message*/) +{ + switch (level) + { + case Yuni::Logs::Verbosity::Warning::level: + ++pWarningCount; + break; + case Yuni::Logs::Verbosity::Error::level: + case Yuni::Logs::Verbosity::Fatal::level: + ++pErrorCount; + break; + default: + break; + } +} + +void Application::execute() +{ + // pStudy == nullptr e.g when the -h flag is given + if (!pStudy) + { + return; + } + + SystemMemoryLogger memoryReport; + memoryReport.interval(1000 * 60 * 5); // 5 minutes + memoryReport.start(); + + pStudy->computePThetaInfForThermalClusters(); + + // Run the simulation + switch (pStudy->runtime->mode) + { + case Data::SimulationMode::Economy: + case Data::SimulationMode::Expansion: + runSimulationInEconomicMode(); + break; + case Data::SimulationMode::Adequacy: + runSimulationInAdequacyMode(); + break; + default: + break; + } + // TODO : make an interface class for ISimulation, check writer & queue before + // runSimulationInMode() + + // Importing Time-Series if asked + pStudy->importTimeseriesIntoInput(); + + // Stop the display of the progression + pStudy->progression.stop(); +} + +void Application::runSimulationInEconomicMode() +{ + Simulation::NullSimulationObserver observer; + Solver::runSimulationInEconomicMode(*pStudy, + pSettings, + pDurationCollector, + *resultWriter, + pOptimizationInfo, + observer); +} + +void Application::runSimulationInAdequacyMode() +{ + Simulation::NullSimulationObserver observer; + Solver::runSimulationInAdequacyMode(*pStudy, + pSettings, + pDurationCollector, + *resultWriter, + pOptimizationInfo, + observer); +} + +static std::string timeToString() +{ + using namespace std::chrono; + auto time = system_clock::to_time_t(system_clock::now()); + std::tm local_time = *std::localtime(&time); + + char time_buffer[256]; + std::strftime(time_buffer, sizeof(time_buffer), "%Y%m%d-%H%M%S", &local_time); + + std::string currentTime = time_buffer; + + return currentTime; +} + +void Application::resetLogFilename() const +{ + fs::path logfile = fs::path(pSettings.studyFolder.c_str()) / "logs"; + + if (!fs::exists(logfile) && !fs::create_directory(logfile)) + { + throw FatalError(std::string("Impossible to create the log folder at ") + logfile.string() + + ". Aborting now."); + } + + logfile /= "solver-"; // append the filename + logfile += timeToString() + ".log"; // complete filename with timestamp and extension + + // Assigning the log filename + logs.logfile(logfile.string()); + + if (!logs.logfileIsOpened()) + { + throw FatalError(std::string("Impossible to create the log file at ") + logfile.string()); + } +} + +void Application::prepareWriter(const Antares::Data::Study& study, + Benchmarking::DurationCollector& duration_collector) +{ + ioQueueService = std::make_shared(); + ioQueueService->maximumThreadCount(1); + ioQueueService->start(); + resultWriter = resultWriterFactory(study.parameters.resultFormat, + study.folderOutput, + ioQueueService, + duration_collector); +} + +void Application::writeComment(Data::Study& study) +{ + study.buffer.clear() << "simulation-comments.txt"; + + if (!pSettings.commentFile.empty()) + { + resultWriter->addEntryFromFile(study.buffer.c_str(), pSettings.commentFile.c_str()); + + pSettings.commentFile.clear(); + } +} + +static void logTotalTime(unsigned duration) +{ + std::chrono::milliseconds d(duration); + auto hours = std::chrono::duration_cast(d); + d -= hours; + auto minutes = std::chrono::duration_cast(d); + d -= minutes; + auto seconds = std::chrono::duration_cast(d); + + logs.info().appendFormat("Total simulation time: %02luh%02lum%02lus", + hours.count(), + minutes.count(), + seconds.count()); +} + +void Application::writeExectutionInfo() +{ + if (!pStudy) + { + return; + } + + pTotalTimer.stop(); + pDurationCollector.addDuration("total", pTotalTimer.get_duration()); + + logTotalTime(pTotalTimer.get_duration()); + + // If no writer is available, we can't write + if (!resultWriter) + { + return; + } + + // Info collectors : they retrieve data from study and simulation + Benchmarking::StudyInfoCollector study_info_collector(*pStudy); + Benchmarking::SimulationInfoCollector simulation_info_collector(pOptimizationInfo); + + // Fill file content with data retrieved by collectors + Benchmarking::FileContent file_content; + pDurationCollector.toFileContent(file_content); + study_info_collector.toFileContent(file_content); + simulation_info_collector.toFileContent(file_content); + + // Flush previous info into a record file + const std::string exec_info_path = "execution_info.ini"; + std::string content = file_content.saveToBufferAsIni(); + resultWriter->addEntryFromBuffer(exec_info_path, content); +} + +Application::~Application() +{ + // Destroy all remaining bouns (callbacks) + destroyBoundEvents(); + + // Release all allocated data + if (pStudy) + { + try + { + logs.info() << LOG_UI_SOLVER_DONE; + } + catch (...) + { + }; // Catching log exception + + // Copy the log file if a result writer is available + if (!pStudy->parameters.noOutput && resultWriter) + { + pStudy->importLogsToOutputFolder(*resultWriter); + } + + // release all reference to the current study held by this class + pStudy->clear(); + pStudy = nullptr; + + LocalPolicy::Close(); + } +} +} // namespace Antares::Solver diff --git a/src/solver/application/include/antares/application/ScenarioBuilderOwner.h b/src/solver/application/include/antares/application/ScenarioBuilderOwner.h new file mode 100644 index 0000000000..f536737be0 --- /dev/null +++ b/src/solver/application/include/antares/application/ScenarioBuilderOwner.h @@ -0,0 +1,44 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +namespace Antares +{ +namespace Data +{ +class Study; +} + +namespace Solver +{ + +class ScenarioBuilderOwner +{ +public: + explicit ScenarioBuilderOwner(Antares::Data::Study& study); + + void callScenarioBuilder(); + +private: + Antares::Data::Study& study_; +}; +} // namespace Solver +} // namespace Antares diff --git a/src/solver/application/include/antares/application/application.h b/src/solver/application/include/antares/application/application.h new file mode 100644 index 0000000000..be114f2d88 --- /dev/null +++ b/src/solver/application/include/antares/application/application.h @@ -0,0 +1,135 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include "antares/infoCollection/StudyInfoCollector.h" +#include "antares/solver/misc/options.h" + +namespace Antares::Solver +{ +class Application final: public Yuni::IEventObserver +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + Application(); + /*! + ** \brief Destructor + */ + ~Application() override; + //@} + + Application(const Application&) = delete; + + Application& operator=(const Application&) = delete; + + /*! + ** \brief Initialize data before launching the simulation + ** + ** \return False if the operation failed. + */ + void prepare(int argc, char* argv[]); + + /*! + ** \brief Execute the simulation + ** + ** \return Exit status + */ + void execute(); + + /*! + ** \brief Reset the process priority (Windows only) + */ + void resetProcessPriority() const; + + void writeExectutionInfo(); + + /** + * @brief /!\ Acquire the study. Leave Application object in an invalid state. + * @return The study + */ + std::unique_ptr acquireStudy() + { + return std::move(pStudy); + } + +private: + /*! + ** \brief Reset the log filename and open it + */ + void resetLogFilename() const; + + /*! + * \brief Load data of the study from a local or remote folder + */ + void readDataForTheStudy(Antares::Data::StudyLoadOptions& options); + + void runSimulationInAdequacyMode(); + void runSimulationInEconomicMode(); + + void onLogMessage(int level, const std::string& message); + + //! The settings given from the command line + Settings pSettings; + //! The current Antares study + std::unique_ptr pStudy; + //! General data related to the current study + Antares::Data::Parameters* pParameters = nullptr; + //! The total number of errors which have been generated + uint pErrorCount = 0; + //! The total muber of warnings which have been generated + uint pWarningCount = 0; + + int pArgc = 0; + char** pArgv = nullptr; + + // Benchmarking + Benchmarking::Timer pTotalTimer; + Benchmarking::DurationCollector pDurationCollector; + Benchmarking::OptimizationInfo pOptimizationInfo; + + std::shared_ptr ioQueueService; + IResultWriter::Ptr resultWriter = nullptr; + + void prepareWriter(const Antares::Data::Study& study, + Benchmarking::DurationCollector& duration_collector); + + void writeComment(Data::Study& study); + void startSimulation(Data::StudyLoadOptions& options); + // Return false if the user requested the version ,available solvers, etc, true otherwise + bool handleOptions(const Data::StudyLoadOptions& options); + // Return false if the user requested help, true otherwise + bool parseCommandLine(Data::StudyLoadOptions& options); + void handleParserReturn(Yuni::GetOpt::Parser* parser); + void postParametersChecks() const; + +}; // class Application +} // namespace Antares::Solver diff --git a/src/solver/application/process-priority.cpp b/src/solver/application/process-priority.cpp new file mode 100644 index 0000000000..a86d30b4c8 --- /dev/null +++ b/src/solver/application/process-priority.cpp @@ -0,0 +1,53 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include + +#include "antares/application/application.h" + +#ifdef YUNI_OS_WINDOWS +#include +#include + +#include + +using namespace Yuni; +using namespace Antares; +#endif + +namespace Antares +{ +namespace Solver +{ +void Application::resetProcessPriority() const +{ +#ifdef YUNI_OS_WINDOWS + if (System::CPU::Count() <= 2) + { + if (not SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS)) + { + logs.info() << " :: impossible to reset the process priority"; + } + } +#endif +} +} // namespace Solver +} // namespace Antares diff --git a/src/solver/constraints-builder/CMakeLists.txt b/src/solver/constraints-builder/CMakeLists.txt index c5b45bbfdf..f9afcd494b 100644 --- a/src/solver/constraints-builder/CMakeLists.txt +++ b/src/solver/constraints-builder/CMakeLists.txt @@ -4,10 +4,10 @@ project(constraints-builder) # set(SRC_CBUILDER cbuilder.cpp - cbuilder.h + include/antares/solver/constraints-builder/cbuilder.h create.cpp - grid.h - grid.hxx + include/antares/solver/constraints-builder/grid.h + include/antares/solver/constraints-builder/grid.hxx load.cpp ) source_group("constraints-builder" FILES ${SRC_CBUILDER}) @@ -25,3 +25,12 @@ target_link_libraries(antares-solver-constraints-builder PRIVATE antares-core PUBLIC Antares::study ) + +target_include_directories(antares-solver-constraints-builder + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/solver/constraints-builder/cbuilder.cpp b/src/solver/constraints-builder/cbuilder.cpp index eebca2d015..2a1e1b8dce 100644 --- a/src/solver/constraints-builder/cbuilder.cpp +++ b/src/solver/constraints-builder/cbuilder.cpp @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ + +#include "antares/solver/constraints-builder/cbuilder.h" + #include -#include "cbuilder.h" -#include "grid.h" +#include -using namespace Yuni; +#include "antares/solver/constraints-builder/grid.h" -//#define SEP Yuni::IO::Separator +namespace fs = std::filesystem; namespace Antares { @@ -50,8 +46,11 @@ Yuni::String linkInfo::getName() const template class Graph::Grid; -CBuilder::CBuilder(Antares::Data::Study::Ptr study) : - pPrefix(CB_PREFIX), pPrefixDelete(CB_PREFIX), pDelete(false), pStudy(study) +CBuilder::CBuilder(Antares::Data::Study& study): + pPrefix(CB_PREFIX), + pPrefixDelete(CB_PREFIX), + pDelete(false), + pStudy(study) { } @@ -75,7 +74,9 @@ uint Antares::CBuilder::cycleCount(linkInfo* lnkI) { uint n = 0; for (auto it = pMesh.begin(); it != pMesh.end(); it++) + { n += (uint)(std::count(it->begin(), it->end(), lnkI)); + } return n; } @@ -84,47 +85,44 @@ bool CBuilder::checkValidityOfNodalLoopFlow(linkInfo* linkInfo, size_t hour) { Data::AreaLink* link = linkInfo->ptr; - for (uint tsIndex = 0; tsIndex < link->indirectCapacities.width; ++tsIndex) + for (uint tsIndex = 0; tsIndex < link->indirectCapacities.timeSeries.width; ++tsIndex) { if ((-1.0 * link->indirectCapacities[tsIndex][hour] - > link->parameters[Data::fhlLoopFlow][hour]) - || (link->directCapacities[tsIndex][hour] - < link->parameters[Data::fhlLoopFlow][hour])) + > link->parameters[Data::fhlLoopFlow][hour]) + || (link->directCapacities[tsIndex][hour] < link->parameters[Data::fhlLoopFlow][hour])) { - logs.error() << "Error on loop flow to NTC comparison validity at hour " - << hour + 1 << " for line " << linkInfo->getName(); + logs.error() << "Error on loop flow to NTC comparison validity at hour " << hour + 1 + << " for line " << linkInfo->getName(); return false; } } if (checkNodalLoopFlow) // check validity of loop flow values (sum = 0 at node) { double sum = 0.0; - for (auto lnk : areaToLinks[link->from]) + for (auto* lnk: areaToLinks[link->from]) { - sum += link->from == lnk->ptr->from - ? -1 * lnk->ptr->parameters[Data::fhlLoopFlow][hour] - : lnk->ptr->parameters[Data::fhlLoopFlow][hour]; + sum += link->from == lnk->ptr->from ? -1 * lnk->ptr->parameters[Data::fhlLoopFlow][hour] + : lnk->ptr->parameters[Data::fhlLoopFlow][hour]; } if (sum != 0.0) { logs.error() << "Error on loop flow sum validity (!= 0) at hour " << hour + 1 - << " on node " << link->from->id; + << " on node " << link->from->id; return false; } sum = 0.0; - for (auto lnk : areaToLinks[link->with]) + for (auto* lnk: areaToLinks[link->with]) { - sum += link->with == lnk->ptr->from - ? -1 * lnk->ptr->parameters[Data::fhlLoopFlow][hour] - : lnk->ptr->parameters[Data::fhlLoopFlow][hour]; + sum += link->with == lnk->ptr->from ? -1 * lnk->ptr->parameters[Data::fhlLoopFlow][hour] + : lnk->ptr->parameters[Data::fhlLoopFlow][hour]; } if (sum != 0.0) { logs.error() << "Error on loop flow sum validity (!= 0) at hour " << hour + 1 - << " on node " << link->with->id; + << " on node " << link->with->id; return false; } } @@ -135,11 +133,10 @@ bool CBuilder::checkValidityOfNodalLoopFlow(linkInfo* linkInfo, size_t hour) bool CBuilder::checkLinkPhaseShift(linkInfo* linkInfo, size_t hour) const { if (Data::AreaLink* link = linkInfo->ptr; - link->parameters[Data::fhlPShiftMinus][hour] - > link->parameters[Data::fhlPShiftPlus][hour]) + link->parameters[Data::fhlPShiftMinus][hour] > link->parameters[Data::fhlPShiftPlus][hour]) { logs.error() << "Error on phase shift calendar validity at hour " << hour + 1 - << " for line " << linkInfo->getName(); + << " for line " << linkInfo->getName(); return false; } return true; @@ -148,9 +145,10 @@ bool CBuilder::checkLinkPhaseShift(linkInfo* linkInfo, size_t hour) const void CBuilder::updateLinkPhaseShift(linkInfo* linkInfo, size_t hour) const { if (Data::AreaLink* link = linkInfo->ptr; - link->parameters[Data::fhlPShiftMinus][hour] - != link->parameters[Data::fhlPShiftPlus][hour]) + link->parameters[Data::fhlPShiftMinus][hour] != link->parameters[Data::fhlPShiftPlus][hour]) + { linkInfo->hasPShiftsEqual = false; + } } bool CBuilder::updateLinks() @@ -175,22 +173,28 @@ bool CBuilder::updateLinks() linkInfo->avgImpedance = link->parameters[columnImpedance][0]; for (size_t hour = 0; hour < HOURS_PER_YEAR - 1; hour++) { - if (link->parameters[columnImpedance][hour + 1] != link->parameters[columnImpedance][hour]) + if (link->parameters[columnImpedance][hour + 1] + != link->parameters[columnImpedance][hour]) { impedances.insert(link->parameters[columnImpedance][hour + 1]); } // check validity of loopflow against NTC if (includeLoopFlow && !checkValidityOfNodalLoopFlow(linkInfo, hour)) + { return false; + } if (!includePhaseShift) + { continue; + } updateLinkPhaseShift(linkInfo, hour); if (!checkLinkPhaseShift(linkInfo, hour)) + { return false; - + } } linkInfo->nImpedanceChanges = (uint)impedances.size(); @@ -214,7 +218,6 @@ bool CBuilder::updateLinks() linkInfo->weight = linkInfo->getWeightWithImpedance(); } return true; - } bool CBuilder::update() @@ -225,15 +228,19 @@ bool CBuilder::update() pMesh.clear(); // Update impedances from study file and compute impedance changes - if(!updateLinks()) + if (!updateLinks()) + { return false; + } for (auto linkInfoIt = pLink.begin(); linkInfoIt != pLink.end(); linkInfoIt++) { if ((*linkInfoIt)->enabled && ((*linkInfoIt)->type == Antares::Data::atAC /*|| (*linkInfoIt)->type == linkInfo::tyACPST*/)) + { enabledACLines.push_back(*linkInfoIt); + } } if (enabledACLines.empty()) @@ -257,7 +264,9 @@ bool CBuilder::update() // build the set of loops which span the grid if (!_grid.buildMesh()) + { return false; + } // create the constraints logs.info() << "Compute Mesh "; @@ -284,7 +293,9 @@ bool CBuilder::runConstraintsBuilder(bool standalone) { // build the set of loops which span the grid if (!update()) + { return false; + } // create the constraints logs.info() << "Write constraints "; @@ -293,7 +304,7 @@ bool CBuilder::runConstraintsBuilder(bool standalone) if (standalone) { - pStudy->saveToFolder(pStudy->folder); + pStudy.saveToFolder(pStudy.folder); } // return result; return result; @@ -302,13 +313,15 @@ bool CBuilder::runConstraintsBuilder(bool standalone) bool CBuilder::deletePreviousConstraints() { if (pPrefixDelete.empty()) + { return true; + } logs.info() << "Deleting previously built network constraints (with prefix " << pPrefixDelete << ")"; - // Data::BindingConstraintsList::iterator it = pStudy->bindingConstraints.begin(); - pStudy->bindingConstraints.removeConstraintsWhoseNameConstains(pPrefixDelete); + // Data::BindingConstraintsList::iterator it = pStudy.bindingConstraints.begin(); + pStudy.bindingConstraints.removeConstraintsWhoseNameConstains(pPrefixDelete); for (auto linkInfoIt = pLink.begin(); linkInfoIt != pLink.end(); linkInfoIt++) { @@ -325,15 +338,13 @@ bool CBuilder::deletePreviousConstraints() bool CBuilder::saveCBuilderToFile(const String& filename) const { - if (!pStudy) - return false; String tmp; IniFile ini; auto* mainSection = ini.addSection(".general"); // Study - mainSection->add("study", pStudy->folder); + mainSection->add("study", pStudy.folder); // Tmp /*wxStringToString(pPathTemp->GetValue(), tmp); @@ -353,36 +364,33 @@ bool CBuilder::saveCBuilderToFile(const String& filename) const if (filename == "") { - YString buffer; + fs::path path = fs::path(pStudy.folder.c_str()) / "settings" / "constraintbuilder.ini"; - buffer.clear() << pStudy->folder << Yuni::IO::Separator << "settings" << Yuni::IO::Separator - << "constraintbuilder.ini"; - return ini.save(buffer); + return ini.save(path.string()); } return ini.save(filename); } -bool CBuilder::completeCBuilderFromFile(const String& filename) +bool CBuilder::completeCBuilderFromFile(const std::string& filename) { - YString buffer; + fs::path path; if (filename == "") { - buffer.clear() << pStudy->folder << Yuni::IO::Separator << "settings" << Yuni::IO::Separator - << "constraintbuilder.ini"; - if (!IO::File::Exists(buffer)) + path = fs::path(pStudy.folder.c_str()) / "settings" / "constraintbuilder.ini"; + if (!fs::exists(path)) { return false; } } else { - buffer = filename; + path = filename; } logs.info() << "Read data"; IniFile ini; - if (ini.open(buffer)) + if (ini.open(path)) { // logs.info() << "Reading " << filename; logs.info() << "Read data (INI file)"; @@ -390,21 +398,16 @@ bool CBuilder::completeCBuilderFromFile(const String& filename) CString<50, false> key; CString<50, false> value; - for (section = ini.firstSection; section != NULL; section = section->next) + for (section = ini.firstSection; section; section = section->next) { if (section->name == ".general") { IniFile::Property* p = section->firstProperty; - for (; p != NULL; p = p->next) + for (; p; p = p->next) { key = p->key; key.toLower(); - if (key == "study") - { - pStudyFolder = p->value; - continue; - } if (key == "prefix") { pPrefix = p->value; @@ -466,7 +469,7 @@ bool CBuilder::completeCBuilderFromFile(const String& filename) int CBuilder::alreadyExistingNetworkConstraints(const Yuni::String& prefix) const { int nSubCount = 0; - for (auto j = pStudy->bindingConstraints.begin(); j != pStudy->bindingConstraints.end(); j++) + for (auto j = pStudy.bindingConstraints.begin(); j != pStudy.bindingConstraints.end(); j++) { std::string name = (*j)->name().c_str(); if (name.find(prefix.to()) == 0) // name starts with the prefix diff --git a/src/solver/constraints-builder/cbuilder.h b/src/solver/constraints-builder/cbuilder.h deleted file mode 100644 index 1135e7fff5..0000000000 --- a/src/solver/constraints-builder/cbuilder.h +++ /dev/null @@ -1,421 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_CONSTRAINTSBUILDER_BUILDER_CBUILDER_H__ -#define __ANTARES_CONSTRAINTSBUILDER_BUILDER_CBUILDER_H__ - -#include -#include -#include -#include "../../libs/antares/study/area/constants.h" -#include "grid.h" - -#define CB_PREFIX "@UTO_" - -namespace Antares -{ -class areaInfo -{ -public: - areaInfo(Data::Area* area) - { - ptr = area; - nodeName = area->name.to(); - } - std::string getName() - { - return nodeName; - } - -public: - Data::Area* ptr; - std::string nodeName; -}; - -class linkInfo -{ -public: - double weight; - bool enabled = true; - Data::AreaLinkName name; - Antares::Data::AssetType type; - double angleLB = 0; - double angleUB = 0; - bool hasPShiftsEqual = true; - - uint nImpedanceChanges; - double avgImpedance; - Data::AreaLink* ptr; - -public: - double getWeightWithImpedance() const; - Yuni::String getName() const; - - linkInfo() = default; - - ~linkInfo() = default; - - struct comparepWeight - { - inline bool operator()(const linkInfo* lhs, const linkInfo* rhs) const - { - return lhs->getWeightWithImpedance() < rhs->getWeightWithImpedance(); - } - }; - struct comparepWeightWithImpedance - { - inline bool operator()(const linkInfo* lhs, const linkInfo* rhs) const - { - return lhs->getWeightWithImpedance() < rhs->getWeightWithImpedance(); - } - }; - struct addpWeight - { - double operator()(double i, const linkInfo* o) const - { - return (o->getWeightWithImpedance() + i); - } - }; - struct addpWeightWithImpedance - { - double operator()(double i, const linkInfo* o) const - { - return (o->getWeightWithImpedance() + i); - } - }; - bool operator<(const linkInfo& other) const - { - return getWeightWithImpedance() < other.getWeightWithImpedance() - ? true - : (getWeightWithImpedance() > other.getWeightWithImpedance() - ? false - : getName() < other.getName()); - } -}; // class linkInfo - -class State -{ -public: - State(std::vector impedancesList, uint time, double infinite = 1000000) : - secondMember(3, time), impedances(impedancesList) - { - secondMember.fillColumn(1, -1 * infinite); - secondMember.fillColumn(0, infinite); - }; - - Matrix secondMember; - std::vector impedances; - std::map WeightMap; -}; - -class Cycle -{ -public: - Cycle(const std::vector& linkList, double infinite = 1000000) : - time(0), loop(linkList), opType(Data::BindingConstraint::opEquality), pInfinite(infinite) - { - uint columnImpedance = (uint)Antares::Data::fhlImpedances; - - std::vector impedances; - Data::AreaLink* previousLine = linkList[0]->ptr; - double currentLineSign = 1; - for (auto line = linkList.begin(); line != linkList.end(); line++) - { - if ((*line)->nImpedanceChanges > 0 - || ((*line)->type == Antares::Data::atAC && (!(*line)->hasPShiftsEqual))) - opType = Data::BindingConstraint::opBoth; - impedances.push_back((*line)->ptr->parameters[columnImpedance][0]); - - time = HOURS_PER_YEAR; /*BC loading always expects 8786 values heigth will - have to be resized*/ - - if (line == linkList.begin()) - { - currentLineSign = 1; - } - else - { - if (previousLine->with == (*line)->ptr->from - || previousLine->from - == (*line)->ptr->with) //[(A/B),(B/C),... ] or [(A,B),(C/A),... ] - { - } - else if (previousLine->from == (*line)->ptr->from - || previousLine->with == (*line)->ptr->with) - { - currentLineSign *= -1; - } - else - assert(0 and "links of the loops do not connect or are not in the right order"); - } - - sign.push_back(currentLineSign); - previousLine = (*line)->ptr; - } - State state(impedances, time, pInfinite); - states.push_back(state); - } - - State& getState(std::vector& impedances) - { - std::vector::iterator stIT - = std::find_if(states.begin(), states.end(), [&impedances](State& s) -> bool { - return s.impedances == impedances; - }); - - if (stIT == states.end()) - { - State state(impedances, time, pInfinite); - states.push_back(state); - stIT = std::find_if(states.begin(), states.end(), [&impedances](State& s) -> bool { - return s.impedances == impedances; - }); - } - return *stIT; - } - - uint time; - std::vector sign; - const std::vector& loop; - std::vector states; - Data::BindingConstraint::Operator opType; - double pInfinite; -}; - -class CBuilder final -{ -public: - typedef std::vector Vector; - typedef std::map WeightMap; - typedef std::map Pattern; - typedef std::vector VectorOfPatterns; - typedef std::map Map; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - CBuilder(Antares::Data::Study::Ptr); - //! Destructor - ~CBuilder(); - //@} - - /*! - ** \brief Independent function to run the constraint generator from a study - */ - bool runConstraintsBuilder(bool standalone = false); - - /*! - ** \brief Complete the settings with the data from the study - */ - bool completeFromStudy(); - - /*! - ** \brief Delete the network constraints - */ - bool deletePreviousConstraints(); - - bool saveCBuilderToFile(const String& filename = "") const; - bool completeCBuilderFromFile(const String& filename = ""); - - /*! - ** \brief check if network constraints already exists in the study - */ - int alreadyExistingNetworkConstraints(const Yuni::String& prefix) const; - - //! find an edge from node names - linkInfo* findLinkInfoFromNodeNames(Data::AreaName& u, Data::AreaName& v) - { - auto linkIT - = std::find_if(pLink.begin(), pLink.end(), [&u, &v](const linkInfo* edgeP) -> bool { - if (edgeP->ptr->from->id == u && edgeP->ptr->with->id == v) - return true; - if (edgeP->ptr->from->id == v && edgeP->ptr->with->id == u) - return true; - else - return false; - }); - if (linkIT != pLink.end()) - return *linkIT; - - return nullptr; - } - - //! build list of edges from area - void buildAreaToLinkInfosMap() - { - areaToLinks.clear(); - for (auto& area : pStudy->areas) - { - auto a = area.second; - std::for_each(pLink.begin(), pLink.end(), [&a, this](linkInfo* edgeP) { - if (edgeP->ptr->from == a || edgeP->ptr->with == a) - this->areaToLinks[a].insert(edgeP); - }); - } - } - - linkInfo* getLink(uint i) - { - if (i < pLink.size()) - return pLink[i]; - return nullptr; - } - - size_t linkCount() - { - return pLink.size(); - } - - bool isCycleDriver(linkInfo*); - - uint cycleCount(linkInfo* lnkI); - - /*! - ** \brief create all the network constraints based on a mesh - */ - bool createConstraints(const std::vector&); - - double setInfinite(const long value) - { - return infiniteSecondMember = value; - } - - bool setCheckNodalLoopFlow(const bool value) - { - return checkNodalLoopFlow = value; - } - - bool setLoopFlowInclusion(const bool value) - { - return includeLoopFlow = value; - } - - bool setPhaseShiftInclusion(const bool value) - { - return includePhaseShift = value; - } - - double getInfinite() - { - return infiniteSecondMember; - } - - bool getCheckNodalLoopFlow() - { - return checkNodalLoopFlow; - } - - bool getLoopFlowInclusion() - { - return includeLoopFlow; - } - - bool getPhaseShiftInclusion() - { - return includePhaseShift; - } - - bool setUpToDate(const bool value) - { - return isUpToDate = value; - } - - bool getUpToDate() - { - return isUpToDate; - } - - bool update(); - - bool updateLinks(); - - bool checkValidityOfNodalLoopFlow(linkInfo* linkInfo, size_t hour); - - void updateLinkPhaseShift(linkInfo* linkInfo, size_t hour) const; - bool checkLinkPhaseShift(linkInfo* linkInfo, size_t hour) const; - - void setCalendarStart(int start) - { - calendarStart = start; - } - - void setCalendarEnd(int end) - { - calendarEnd = end; - } - uint getCalendarStart() - { - return calendarStart; - } - - uint getCalendarEnd() - { - return calendarEnd; - } - -private: - /*! - ** \brief add one constraint to the study - */ - std::shared_ptr addConstraint(const Data::ConstraintName& name, - const Yuni::String& op, - const Yuni::String& type, - const WeightMap& weights, - const double& secondMember); - -public: - Vector pLink; - -private: - YString pStudyFolder; - YString pPrefix; - YString pPrefixDelete; - bool pDelete; - bool includeLoopFlow = true; - bool includePhaseShift = true; - bool isUpToDate = false; - bool checkNodalLoopFlow = true; - double infiniteSecondMember = 1000000; - - uint calendarStart = 1; - uint calendarEnd = 8760; - - std::vector> pMesh; - - std::map> areaToLinks; - - Antares::Data::Study::Ptr pStudy; - - Graph::Grid _grid; - -}; // class cbuilder - -} // namespace Antares - -#endif // __ANTARES_CONSTRAINTSBUILDER_BUILDER_CBUILDER_H__ diff --git a/src/solver/constraints-builder/create.cpp b/src/solver/constraints-builder/create.cpp index 16ad1466c2..6c6fbeb21b 100644 --- a/src/solver/constraints-builder/create.cpp +++ b/src/solver/constraints-builder/create.cpp @@ -1,36 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "cbuilder.h" -#include "../../libs/antares/study/area/constants.h" - -#include -#include -#include #include +#include +#include + +#include "antares/solver/constraints-builder/cbuilder.h" using namespace Yuni; @@ -83,38 +75,33 @@ bool CBuilder::createConstraints(const std::vector& mesh) if (currentCycle.opType == Data::BindingConstraint::opEquality) { ub += ((*line)->ptr->parameters[columnImpedance][hour] - * (*line)->ptr->parameters[columnLoopFlow][hour] - * (int)includeLoopFlow - + (*line)->ptr->parameters[Data::fhlPShiftMinus][hour] - * includePhaseShift) - * currentCycle.sign[i]; + * (*line)->ptr->parameters[columnLoopFlow][hour] * (int)includeLoopFlow + + (*line)->ptr->parameters[Data::fhlPShiftMinus][hour] + * includePhaseShift) + * currentCycle.sign[i]; } else if (currentCycle.opType == Data::BindingConstraint::opBoth && hour + 1 <= calendarEnd && hour + 1 >= calendarStart) { ub += ((*line)->ptr->parameters[columnImpedance][hour] - * (*line)->ptr->parameters[columnLoopFlow][hour] - * (int)includeLoopFlow) - * currentCycle.sign[i] - + std::min( - ((*line)->ptr->parameters[Data::fhlPShiftMinus][hour] - * includePhaseShift) - * currentCycle.sign[i], - ((*line)->ptr->parameters[Data::fhlPShiftPlus][hour] - * includePhaseShift) - * currentCycle.sign[i]); + * (*line)->ptr->parameters[columnLoopFlow][hour] * (int)includeLoopFlow) + * currentCycle.sign[i] + + std::min(((*line)->ptr->parameters[Data::fhlPShiftMinus][hour] + * includePhaseShift) + * currentCycle.sign[i], + ((*line)->ptr->parameters[Data::fhlPShiftPlus][hour] + * includePhaseShift) + * currentCycle.sign[i]); lb += ((*line)->ptr->parameters[columnImpedance][hour] - * (*line)->ptr->parameters[columnLoopFlow][hour] - * (int)includeLoopFlow) - * currentCycle.sign[i] - + std::max( - ((*line)->ptr->parameters[Data::fhlPShiftMinus][hour] - * includePhaseShift) - * currentCycle.sign[i], - ((*line)->ptr->parameters[Data::fhlPShiftPlus][hour] - * includePhaseShift) - * currentCycle.sign[i]); + * (*line)->ptr->parameters[columnLoopFlow][hour] * (int)includeLoopFlow) + * currentCycle.sign[i] + + std::max(((*line)->ptr->parameters[Data::fhlPShiftMinus][hour] + * includePhaseShift) + * currentCycle.sign[i], + ((*line)->ptr->parameters[Data::fhlPShiftPlus][hour] + * includePhaseShift) + * currentCycle.sign[i]); } else { @@ -122,8 +109,8 @@ bool CBuilder::createConstraints(const std::vector& mesh) ub = -1 * infiniteSecondMember; } - wm[(*line)] - = (*line)->ptr->parameters[columnImpedance][hour] * currentCycle.sign[i]; + wm[(*line)] = (*line)->ptr->parameters[columnImpedance][hour] + * currentCycle.sign[i]; } State& st = currentCycle.getState(impedanceVector); @@ -155,15 +142,16 @@ bool CBuilder::createConstraints(const std::vector& mesh) if (cycle->opType == Data::BindingConstraint::opBoth) { name1 << "." << nSubCount; - auto constraint - = addConstraint(name1, - "both", - "hourly", - state->WeightMap, - 0); // vocabulary is not so obvious here (less or greater) + auto constraint = addConstraint( + name1, + "both", + "hourly", + state->WeightMap, + 0); // vocabulary is not so obvious here (less or greater) ret = constraint != nullptr; - state->secondMember.resizeWithoutDataLost( - constraint->RHSTimeSeries().width, constraint->RHSTimeSeries().height, 0); + state->secondMember.resizeWithoutDataLost(constraint->RHSTimeSeries().width, + constraint->RHSTimeSeries().height, + 0); constraint->RHSTimeSeries() = state->secondMember; // iterate the counter @@ -171,15 +159,16 @@ bool CBuilder::createConstraints(const std::vector& mesh) } else { - auto constraint - = addConstraint(name1, - "equal", - "hourly", - state->WeightMap, - 0); // vocabulary is not so obvious here (less or greater) + auto constraint = addConstraint( + name1, + "equal", + "hourly", + state->WeightMap, + 0); // vocabulary is not so obvious here (less or greater) ret = constraint != nullptr; - state->secondMember.resizeWithoutDataLost( - constraint->RHSTimeSeries().width, constraint->RHSTimeSeries().height, 0); + state->secondMember.resizeWithoutDataLost(constraint->RHSTimeSeries().width, + constraint->RHSTimeSeries().height, + 0); constraint->RHSTimeSeries() = state->secondMember; } } @@ -189,14 +178,15 @@ bool CBuilder::createConstraints(const std::vector& mesh) return ret; } -std::shared_ptr CBuilder::addConstraint(const Data::ConstraintName& name, - const String& op, - const String& type, - const WeightMap& weights, - const double& secondMember) +std::shared_ptr CBuilder::addConstraint( + const Data::ConstraintName& name, + const String& op, + const String& type, + const WeightMap& weights, + const double& secondMember) { // Create a new contraint - auto constraint = pStudy->bindingConstraints.add(name); + auto constraint = pStudy.bindingConstraints.add(name); const Data::BindingConstraint::Operator o = Data::BindingConstraint::StringToOperator(op); assert(o != Data::BindingConstraint::opUnknown); const Data::BindingConstraint::Type t = Data::BindingConstraint::StringToType(type); @@ -210,12 +200,14 @@ std::shared_ptr CBuilder::addConstraint(const // weights for (auto j = weights.begin(); j != weights.end(); j++) { - if (!Math::Zero(j->second)) + if (!Utils::isZero(j->second)) + { constraint->weight(j->first->ptr, j->second); + } } // second members - if (!Math::Zero(secondMember)) + if (!Utils::isZero(secondMember)) { constraint->RHSTimeSeries().fill(secondMember); constraint->RHSTimeSeries().markAsModified(); diff --git a/src/solver/constraints-builder/grid.h b/src/solver/constraints-builder/grid.h deleted file mode 100644 index 09c689729d..0000000000 --- a/src/solver/constraints-builder/grid.h +++ /dev/null @@ -1,379 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef CONSTRAINTSBUILDER_BUILDER_GRID_H -#define CONSTRAINTSBUILDER_BUILDER_GRID_H - -#include -#include -#include -#include - -//#include -//#include -//#include - -namespace Antares -{ -namespace Graph -{ -template -class Node -{ -public: - Node(NodeT* data) - { - nodeProperties = data; - } - - virtual ~Node() = default; - - virtual std::string getName() - { - return name; - }; - - virtual void setName(std::string newName) - { - name = newName; - }; - -public: - std::string name; - NodeT* nodeProperties; -}; - -template -class Edge -{ -public: - Edge(Node* from, Node* to) - { - originNode = from; - destinationNode = to; - } - - long getWeight() const - { - return weight; - } - void setWeight(long w) - { - weight = w; - } - Node* getOrigin() - { - return originNode; - } - Node* getDestination() - { - return destinationNode; - } - void setOrigin(Node* from) - { - originNode = from; - } - void setDestination(Node* to) - { - destinationNode = to; - } - -private: - long weight; - Node* originNode; - Node* destinationNode; - -public: - struct addpWeight - { - long operator()(long i, const Edge* o) const - { - return (o->getWeight() + i); - } - }; - - struct compareWeight - { - bool operator()(const Edge* lhs, const Edge* rhs) const - { - return lhs->getWeight() < rhs->getWeight(); - } - }; -}; - -/*! -** \brief Antares Grid (graph) -*/ -template -class Grid -{ -public: - typedef Antares::Graph::Node* NodeP; - typedef Antares::Graph::Edge* EdgeP; - typedef std::vector VectorNodeP; - typedef std::vector VectorEdgeP; - typedef std::map MapNodes; - typedef std::vector EdgeIncidence; - -public: - //! \name Constructor & Destructor - //@{ - //! Constructor - Grid(); - //! Destructor - ~Grid(); - //@} - - //! Add one node to the graph - NodeP addNode(NodeT&, std::string); - - //! Add one edge to the graph - EdgeP addEdge(NodeP, NodeP, long weight = 0); - - uint getNumberOfConnectedComponents(); - - VectorEdgeP findShortestPath(NodeP node1, NodeP node2) const; - - //! find an edge from node names - EdgeP findEdgeFromNodeNames(std::string u, std::string v) - { - auto edgeIT = std::find_if( - pEdgesList.begin(), pEdgesList.end(), [&u, &v](const EdgeP& edgeP) -> bool { - if (edgeP->getOrigin()->getName() == u && edgeP->getDestination()->getName() == v) - return true; - if (edgeP->getDestination()->getName() == u && edgeP->getOrigin()->getName() == v) - return true; - else - return false; - }); - if (edgeIT != pEdgesList.end()) - return *edgeIT; - - return nullptr; - } - - EdgeP findDrivingEdgeFromNodeNames(std::string u, std::string v) - { - auto edgeIT = std::find_if( - pMinSpanningTree.begin(), pMinSpanningTree.end(), [&u, &v](const EdgeP& edgeP) -> bool { - if (edgeP->getOrigin()->getName() == u && edgeP->getDestination()->getName() == v) - return true; - if (edgeP->getDestination()->getName() == u && edgeP->getOrigin()->getName() == v) - return true; - else - return false; - }); - if (edgeIT != pMinSpanningTree.end()) - return *edgeIT; - - return nullptr; - } - - // remove an edge from the graph - void removeEdge(EdgeP e) - { - auto edgeIT = std::find(pEdgesList.begin(), pEdgesList.end(), e); - auto edge = *edgeIT; - if (edgeIT != pEdgesList.end()) - { - pEdgesList.erase(edgeIT); - - adjency[e->getOrigin()].erase(e->getDestination()); - adjency[e->getDestination()].erase(e->getOrigin()); - - delete edge; - } - } - - //! find a node from it's name - NodeP findNodeFromName(std::string name) - { - auto nodeIT = std::find_if(pNodesList.begin(), pNodesList.end(), [&name](NodeP& n) -> bool { - return n->getName() == name; - }); - if (nodeIT != pNodesList.end()) - return *nodeIT; - else - return nullptr; - } - - /*! - ** \brief Kruskal algorithm - ** - ** Search for the minimum spanning tree of the graph - ** Saved in pMinSpanningTree - */ - void kruskal(); - - /*! - ** \brief Get minimum spanning tree - ** - */ - /*VectorEdgeData getMinSpanningTree() - { - VectorEdgeData minSpanningTree(pMinSpanningTree.size()); - auto end = pMinSpanningTree.end(); - for (auto e = pMinSpanningTree.begin(); e != end; e++) - { - minSpanningTree.push_back((*e)->edgeProperties); - } - return minSpanningTree; - }*/ - - /*! - ** \brief Build pMesh - ** - ** the smallest set of loops meshing the graph - */ - bool buildMesh(); - - /*! - ** \brief Get the min cycle basis mesh - ** - ** the smallest set of loops meshing the graph - */ - const std::vector>& getMeshIndexMatrix() - { - return meshIndexMatrix; - } - - VectorEdgeP twoLevelPath(VectorNodeP vN); - - /*! - ** \brief get a Gid where edges and nodes are duplicated - ** - */ - bool getDuplicatedGrid(Grid&); - - /*! - ** \brief get a clone of the Grid - ** - */ - bool cloneGrid(Grid&); - - const VectorEdgeP& getEdges() - { - return pEdgesList; - } - -public: - EdgeIncidence getIncidenceVector(VectorEdgeP vE) - { - EdgeIncidence Ei(pEdgesList.size(), false); - for (uint i = 0; i < pEdgesList.size(); i++) - { - if (std::find(vE.begin(), vE.end(), pEdgesList[i]) != vE.end()) - Ei[i] = true; - } - return Ei; - } - - EdgeIncidence getIncidenceVector(EdgeP vE) - { - EdgeIncidence Ei(pEdgesList.size(), false); - for (uint i = 0; i < pEdgesList.size(); i++) - { - if (vE == pEdgesList[i]) - { - Ei[i] = true; - break; - } - } - return Ei; - } - - VectorEdgeP getEdgeVectorFromIncidence(EdgeIncidence vI) - { - VectorEdgeP vE; - for (uint i = 0; i < pEdgesList.size(); i++) - { - if (vI[i] == true) - vE.push_back(pEdgesList[i]); - } - return vE; - } - - EdgeIncidence incidenceXOR(EdgeIncidence& e1, EdgeIncidence& e2) - { - EdgeIncidence Ei(e1.size(), false); - std::transform(e1.begin(), e1.end(), e2.begin(), Ei.begin(), std::bit_xor()); - - return Ei; - } - - int incidenceInnerProduct(EdgeIncidence& e1, EdgeIncidence& e2) - { - int r1 = std::inner_product(e1.begin(), e1.end(), e2.begin(), 0); - return r1 % 2; - } - - void clear() - { - for (auto it = pNodesList.begin(); it != pNodesList.end(); it++) - { - delete (*it); - } - pNodesList.clear(); - - for (auto it = pEdgesList.begin(); it != pEdgesList.end(); it++) - { - delete (*it); - } - pEdgesList.clear(); - - pMinSpanningTree.clear(); - pMesh.clear(); - meshIndexMatrix.clear(); - adjency.clear(); - } - -private: - //! \definition of the graph - //@{ - //! list of nodes - VectorNodeP pNodesList; - //! list of edges - VectorEdgeP pEdgesList; - //@} - - //! Minimum Spanning Tree of the graph - VectorEdgeP pMinSpanningTree; - //! Smallest set of loops meshing all the graph - std::vector pMesh; - - std::vector> meshIndexMatrix; - - double inf; - - //! adjency list - std::map> adjency; -}; - -} // namespace Graph -} // namespace Antares - -#include "grid.hxx" -#endif // CONSTRAINTSBUILDER_BUILDER_GRID_H diff --git a/src/solver/constraints-builder/grid.hxx b/src/solver/constraints-builder/grid.hxx deleted file mode 100644 index 657f2c1eaa..0000000000 --- a/src/solver/constraints-builder/grid.hxx +++ /dev/null @@ -1,483 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#include "grid.h" -#include "cbuilder.h" -#include -#include -#include -#include -#include -#include - -using namespace Yuni; - -namespace Antares -{ -namespace Graph -{ -template -Grid::Grid() : inf(0) -{ -} - -template -Grid::~Grid() -{ - for (auto i = pEdgesList.begin(); i != pEdgesList.end(); i++) - delete (*i); - for (auto i = pNodesList.begin(); i != pNodesList.end(); i++) - delete (*i); -} - -template -typename Grid::NodeP Grid::addNode(NodeT& n, std::string id) -{ - auto nodeIT - = std::find_if(pNodesList.begin(), pNodesList.end(), [&id](const NodeP& nodeP) -> bool { - return nodeP->getName() == id; - }); - - if (nodeIT == pNodesList.end()) - { - NodeP newNode = new Graph::Node(&n); - newNode->setName(id); - pNodesList.push_back(newNode); - return newNode; - } - else - { - return *nodeIT; - } -} - -template -typename Grid::EdgeP Grid::addEdge(NodeP n1, NodeP n2, long weight) -{ - std::string s1(n1->getName()); - std::string s2(n2->getName()); - EdgeP edgePtr = findEdgeFromNodeNames(s1, s2); - if (edgePtr == nullptr) - { - EdgeP newEdge = new Edge(n1, n2); - inf += weight; - newEdge->setWeight(weight); - - // add edge to the list - pEdgesList.push_back(newEdge); - - // redefine inf - inf += weight; - - // update adjency - adjency[newEdge->getOrigin()].insert(std::make_pair(newEdge->getDestination(), newEdge)); - adjency[newEdge->getDestination()].insert(std::make_pair(newEdge->getOrigin(), newEdge)); - - return newEdge; - } - else - return edgePtr; -} - -template -uint Grid::getNumberOfConnectedComponents() -{ - // create union-find set - MapNodes uf; - - for (auto i = pNodesList.begin(); i != pNodesList.end(); i++) - { - uf.insert(std::make_pair(*i, *i)); - } - - // algorithm - for (auto i = pEdgesList.begin(); i != pEdgesList.end(); i++) - { - // if the two areas are not yet connected - if (uf[(*i)->getOrigin()] != uf[(*i)->getDestination()]) - { - // update uf - NodeP cset(uf[(*i)->getDestination()]); - for (auto j = pNodesList.begin(); j != pNodesList.end(); j++) - { - if (uf[*j] == cset) - { - uf[*j] = uf[(*i)->getOrigin()]; - } - } - } - } - - std::unordered_map cVec; - for (auto cIT = uf.begin(); cIT != uf.end(); cIT++) - { - cVec[cIT->second] = true; - } - - return (uint)(cVec.size()); -} - -template -void Grid::kruskal() -{ - // clear spanning tree - pMinSpanningTree.clear(); - - // create union-find set - MapNodes uf; - - for (auto i = pNodesList.begin(); i != pNodesList.end(); i++) - { - uf.insert(std::make_pair(*i, *i)); - } - - // create temporary sorted vector of Link - VectorEdgeP tempEdgesList = pEdgesList; - std::stable_sort( - tempEdgesList.begin(), tempEdgesList.end(), typename Graph::Edge::compareWeight()); - - // algorithm - for (auto i = tempEdgesList.begin(); i != tempEdgesList.end(); i++) - { - // if the two areas are not yet connected - if (uf[(*i)->getOrigin()] != uf[(*i)->getDestination()]) - { - pMinSpanningTree.push_back(*i); - - // update uf - NodeP cset(uf[(*i)->getDestination()]); - for (auto j = pNodesList.begin(); j != pNodesList.end(); j++) - { - if (uf[*j] == cset) - { - uf[*j] = uf[(*i)->getOrigin()]; - } - } - } - } -} - -template -bool Grid::buildMesh() -{ - // build the minimum spanning tree - kruskal(); - - if (pMinSpanningTree.empty()) - return false; - - // clear the spanning cycle base - pMesh.clear(); - meshIndexMatrix.clear(); - - // initialization - std::vector linksToBeAdded; - for (auto i = pEdgesList.begin(); i != pEdgesList.end(); i++) - { - // check if the link already belong to the skeleton - if (std::find(pMinSpanningTree.begin(), pMinSpanningTree.end(), (*i)) - == pMinSpanningTree.end()) - linksToBeAdded.push_back(*i); - } - - std::vector incidenceMatrix(linksToBeAdded.size()); - for (uint i = 0; i < linksToBeAdded.size(); i++) - { - incidenceMatrix[i] = getIncidenceVector(linksToBeAdded[i]); - } - - for (uint i = 0; i < linksToBeAdded.size(); i++) - { - logs.info() << "Searching basis (loop " << i + 1 << "/" << linksToBeAdded.size() << ")"; - // build the graph with two copies (+/-) for each node and edge - Grid polarisedDuplicate; - getDuplicatedGrid(polarisedDuplicate); - VectorEdgeP v = getEdgeVectorFromIncidence(incidenceMatrix[i]); - VectorEdgeP Ci; - //! vecteur contenant les sommets adjacents aux arêtes Ei - VectorNodeP adjacentNodes; - // retrait des arêtes (u,v) qui sont dans Ei et remplacement dans le graphe dupliqué - // par(u+,v-) et (u-,v+) - for (uint j = 0; j < v.size(); j++) - { - if (std::find(adjacentNodes.begin(), adjacentNodes.end(), v[j]->getOrigin()) - == adjacentNodes.end()) - adjacentNodes.push_back(v[j]->getOrigin()); - if (std::find(adjacentNodes.begin(), adjacentNodes.end(), v[j]->getDestination()) - == adjacentNodes.end()) - adjacentNodes.push_back(v[j]->getDestination()); - - EdgeP ei = polarisedDuplicate.findEdgeFromNodeNames( - v[j]->getOrigin()->getName() + "+", v[j]->getDestination()->getName() + "+"); - - NodeP ni1 = polarisedDuplicate.findNodeFromName(v[j]->getOrigin()->getName() + "+"); - NodeP ni2 - = polarisedDuplicate.findNodeFromName(v[j]->getDestination()->getName() + "-"); - - polarisedDuplicate.addEdge(ni1, ni2, ei->getWeight()); - polarisedDuplicate.removeEdge(ei); - - ei = polarisedDuplicate.findEdgeFromNodeNames(v[j]->getOrigin()->getName() + "-", - v[j]->getDestination()->getName() + "-"); - - ni1 = polarisedDuplicate.findNodeFromName(v[j]->getOrigin()->getName() + "-"); - ni2 = polarisedDuplicate.findNodeFromName(v[j]->getDestination()->getName() + "+"); - - polarisedDuplicate.addEdge(ni1, ni2, ei->getWeight()); - polarisedDuplicate.removeEdge(ei); - } - - //! extraction du chemin sur deux niveaux - v = polarisedDuplicate.twoLevelPath(adjacentNodes); - - //! définition du cycle correspondant dans le graph d'origine (non signé) - Ci.clear(); - std::vector edgeIndices; - for (typename VectorEdgeP::iterator e = v.begin(); e != v.end(); e++) - { - auto name1 = (*e)->getOrigin()->getName(); - name1 = name1.substr(0, name1.length() - 1); - auto name2 = (*e)->getDestination()->getName(); - name2 = name2.substr(0, name2.length() - 1); - EdgeP ei = findEdgeFromNodeNames(name1, name2); - Ci.push_back(ei); - - auto eIT = std::find(pEdgesList.begin(), pEdgesList.end(), ei); - int pos = (int)std::distance(pEdgesList.begin(), eIT); - edgeIndices.push_back(pos); - } - - pMesh.push_back(Ci); - EdgeIncidence I = getIncidenceVector(Ci); - meshIndexMatrix.push_back(edgeIndices); - // remplacement par la différence symétrique des des jeux d'arêtes - for (uint j = i + 1; j < linksToBeAdded.size(); j++) - { - if (incidenceInnerProduct(I, incidenceMatrix[j]) == 1) - { - incidenceMatrix[j] = incidenceXOR(incidenceMatrix[i], incidenceMatrix[j]); - } - } - } - - return true; -} - -/*! -** \brief get a Grid where each edge and node is duplicated and signed -** \param a reference to a virgin grid object -*/ -template -bool Grid::getDuplicatedGrid(Grid& grid) -{ - // duplicate nodes - for (typename VectorNodeP::iterator node = pNodesList.begin(); node != pNodesList.end(); node++) - { - { //+ - grid.addNode((*(*node)->nodeProperties), (*node)->getName() + "+"); - } - - { //- - grid.addNode((*(*node)->nodeProperties), (*node)->getName() + "-"); - } - } - - // Duplicate edges - for (typename VectorEdgeP::iterator e = pEdgesList.begin(); e != pEdgesList.end(); e++) - { - { //+ - auto nodeOrigIT = std::find_if( - grid.pNodesList.begin(), grid.pNodesList.end(), [&e](const NodeP& nodeP) -> bool { - return nodeP->getName() == (*e)->getOrigin()->getName() + "+"; - }); - - auto nodeDestIT = std::find_if( - grid.pNodesList.begin(), grid.pNodesList.end(), [&e](const NodeP& nodeP) -> bool { - return nodeP->getName() == (*e)->getDestination()->getName() + "+"; - }); - - grid.addEdge(*nodeOrigIT, *nodeDestIT, (*e)->getWeight()); - } - - { //- - auto nodeOrigIT = std::find_if( - grid.pNodesList.begin(), grid.pNodesList.end(), [&e](const NodeP& nodeP) -> bool { - return nodeP->getName() == (*e)->getOrigin()->getName() + "-"; - }); - - auto nodeDestIT = std::find_if( - grid.pNodesList.begin(), grid.pNodesList.end(), [&e](const NodeP& nodeP) -> bool { - return nodeP->getName() == (*e)->getDestination()->getName() + "-"; - }); - - grid.addEdge(*nodeOrigIT, *nodeDestIT, (*e)->getWeight()); - } - } - return true; -} - -/*! -** \brief get a clone of the grid -** \param a reference to a virgin grid object -*/ -template -bool Grid::cloneGrid(Grid& grid) -{ - // duplicate nodes - for (typename VectorNodeP::iterator node = pNodesList.begin(); node != pNodesList.end(); node++) - { - { - grid.addNode((*(*node)->nodeProperties), (*node)->getName()); - } - } - - // duplicate edges - for (typename VectorEdgeP::iterator e = pEdgesList.begin(); e != pEdgesList.end(); e++) - { - { //+ - auto nodeOrigIT = std::find_if( - grid.pNodesList.begin(), grid.pNodesList.end(), [&e](const NodeP& nodeP) -> bool { - return nodeP->getName() == (*e)->getOrigin()->getName(); - }); - - auto nodeDestIT = std::find_if( - grid.pNodesList.begin(), grid.pNodesList.end(), [&e](const NodeP& nodeP) -> bool { - return nodeP->getName() == (*e)->getDestination()->getName(); - }); - - grid.addEdge(*nodeOrigIT, *nodeDestIT, (*e)->getWeight()); - } - } - return true; -} - -template -typename Grid::VectorEdgeP Grid::twoLevelPath(VectorNodeP vN) -{ - VectorEdgeP SP, minSP; - double minLength = DBL_MAX, length; - for (typename VectorNodeP::iterator n = vN.begin(); n != vN.end(); n++) - { - SP = findShortestPath(findNodeFromName((*n)->getName() + "+"), - findNodeFromName((*n)->getName() + "-")); - length = std::accumulate( - SP.begin(), SP.end(), (long)0, typename Graph::Edge::addpWeight()); - if (length < minLength) - { - minLength = length; - minSP = SP; - } - } - - return minSP; -} - -//! Find shortest path between the two nodes (Djikstra) -template -typename Grid::VectorEdgeP Grid::findShortestPath(NodeP node1, NodeP node2) const -{ - assert(node1 != node2); - - // Dijkstra (lots of computation which could be optimised) - // initialization - std::map dist; - std::map prev; - - //decorate to avoid warnings at compile - [[maybe_unused]] bool checkNode1(false), checkNode2(false); - VectorNodeP nodes = pNodesList; - - for (auto i = nodes.begin(); i != nodes.end(); i++) - { - dist[(*i)] = inf; - prev[(*i)] = 0; - if ((*i) == node1) - { - checkNode1 = true; - } - else if ((*i) == node2) - { - checkNode2 = true; - } - } - assert(checkNode1 && checkNode2); - dist[node1] = 0; - // search for shortest path - bool targetFound(0); - while (!targetFound) - { - // look for closest element u belonging in nodes - std::pair u(nullptr, inf - 1); - typename Grid::VectorNodeP::iterator ui; - for (auto i = nodes.begin(); i != nodes.end(); i++) - { - if (dist[(*i)] < u.second) - { - u.first = (*i); - u.second = dist[(*i)]; - ui = i; - } - } - - // see if destination node has been f - if (u.first == node2) - { - targetFound = true; - break; - } - - // remove u from the list of nodes - nodes.erase(ui); - - // update the neighoubours of u - for (auto i = adjency.at(u.first).begin(); i != adjency.at(u.first).end(); i++) - { - if (i->second == nullptr) - assert(0); - - if ((u.second + i->second->getWeight()) < dist[i->first]) - { - dist[i->first] = u.second + i->second->getWeight(); - prev[i->first] = u.first; - } - } - } - - // rebuild path - Grid::VectorEdgeP path; - Grid::NodeP currentNode = node2; - - while (!prev[currentNode] == 0) - { - path.push_back(adjency.at(currentNode).at(prev[currentNode])); - currentNode = prev[currentNode]; - } - - return path; -} - -} // namespace Graph -} // namespace Antares diff --git a/src/solver/constraints-builder/include/antares/solver/constraints-builder/cbuilder.h b/src/solver/constraints-builder/include/antares/solver/constraints-builder/cbuilder.h new file mode 100644 index 0000000000..833f9e82e6 --- /dev/null +++ b/src/solver/constraints-builder/include/antares/solver/constraints-builder/cbuilder.h @@ -0,0 +1,448 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_CONSTRAINTSBUILDER_BUILDER_CBUILDER_H__ +#define __ANTARES_CONSTRAINTSBUILDER_BUILDER_CBUILDER_H__ + +#include +#include + +#include +#include "antares/solver/constraints-builder/grid.h" +#include "antares/study/area/constants.h" + +#define CB_PREFIX "@UTO_" + +namespace Antares +{ +class areaInfo +{ +public: + areaInfo(Data::Area* area) + { + ptr = area; + nodeName = area->name.to(); + } + + std::string getName() + { + return nodeName; + } + +public: + Data::Area* ptr; + std::string nodeName; +}; + +class linkInfo +{ +public: + double weight; + bool enabled = true; + Data::AreaLinkName name; + Antares::Data::AssetType type; + double angleLB = 0; + double angleUB = 0; + bool hasPShiftsEqual = true; + + uint nImpedanceChanges; + double avgImpedance; + Data::AreaLink* ptr; + +public: + double getWeightWithImpedance() const; + Yuni::String getName() const; + + linkInfo() = default; + + ~linkInfo() = default; + + struct comparepWeight + { + inline bool operator()(const linkInfo* lhs, const linkInfo* rhs) const + { + return lhs->getWeightWithImpedance() < rhs->getWeightWithImpedance(); + } + }; + + struct comparepWeightWithImpedance + { + inline bool operator()(const linkInfo* lhs, const linkInfo* rhs) const + { + return lhs->getWeightWithImpedance() < rhs->getWeightWithImpedance(); + } + }; + + struct addpWeight + { + double operator()(double i, const linkInfo* o) const + { + return (o->getWeightWithImpedance() + i); + } + }; + + struct addpWeightWithImpedance + { + double operator()(double i, const linkInfo* o) const + { + return (o->getWeightWithImpedance() + i); + } + }; + + bool operator<(const linkInfo& other) const + { + return getWeightWithImpedance() < other.getWeightWithImpedance() + ? true + : (getWeightWithImpedance() > other.getWeightWithImpedance() + ? false + : getName() < other.getName()); + } +}; // class linkInfo + +class State +{ +public: + State(std::vector impedancesList, uint time, double infinite = 1000000): + secondMember(3, time), + impedances(impedancesList) + { + secondMember.fillColumn(1, -1 * infinite); + secondMember.fillColumn(0, infinite); + } + + Matrix secondMember; + std::vector impedances; + std::map WeightMap; +}; + +class Cycle +{ +public: + Cycle(const std::vector& linkList, double infinite = 1000000): + time(0), + loop(linkList), + opType(Data::BindingConstraint::opEquality), + pInfinite(infinite) + { + uint columnImpedance = (uint)Antares::Data::fhlImpedances; + + std::vector impedances; + Data::AreaLink* previousLine = linkList[0]->ptr; + double currentLineSign = 1; + for (auto line = linkList.begin(); line != linkList.end(); line++) + { + if ((*line)->nImpedanceChanges > 0 + || ((*line)->type == Antares::Data::atAC && (!(*line)->hasPShiftsEqual))) + { + opType = Data::BindingConstraint::opBoth; + } + impedances.push_back((*line)->ptr->parameters[columnImpedance][0]); + + time = HOURS_PER_YEAR; /*BC loading always expects 8786 values heigth will + have to be resized*/ + + if (line == linkList.begin()) + { + currentLineSign = 1; + } + else + { + if (previousLine->with == (*line)->ptr->from + || previousLine->from + == (*line)->ptr->with) //[(A/B),(B/C),... ] or [(A,B),(C/A),... ] + { + } + else if (previousLine->from == (*line)->ptr->from + || previousLine->with == (*line)->ptr->with) + { + currentLineSign *= -1; + } + else + { + assert(0 and "links of the loops do not connect or are not in the right order"); + } + } + + sign.push_back(currentLineSign); + previousLine = (*line)->ptr; + } + State state(impedances, time, pInfinite); + states.push_back(state); + } + + State& getState(std::vector& impedances) + { + std::vector::iterator stIT = std::find_if(states.begin(), + states.end(), + [&impedances](State& s) -> bool + { return s.impedances == impedances; }); + + if (stIT == states.end()) + { + State state(impedances, time, pInfinite); + states.push_back(state); + stIT = std::find_if(states.begin(), + states.end(), + [&impedances](State& s) -> bool + { return s.impedances == impedances; }); + } + return *stIT; + } + + uint time; + std::vector sign; + const std::vector& loop; + std::vector states; + Data::BindingConstraint::Operator opType; + double pInfinite; +}; + +class CBuilder final +{ +public: + typedef std::vector Vector; + typedef std::map WeightMap; + typedef std::map Pattern; + typedef std::vector VectorOfPatterns; + typedef std::map Map; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + CBuilder(Antares::Data::Study&); + //! Destructor + ~CBuilder(); + //@} + + /*! + ** \brief Independent function to run the constraint generator from a study + */ + bool runConstraintsBuilder(bool standalone = false); + + /*! + ** \brief Complete the settings with the data from the study + */ + bool completeFromStudy(); + + /*! + ** \brief Delete the network constraints + */ + bool deletePreviousConstraints(); + + bool saveCBuilderToFile(const String& filename = "") const; + bool completeCBuilderFromFile(const std::string& filename = ""); + + /*! + ** \brief check if network constraints already exists in the study + */ + int alreadyExistingNetworkConstraints(const Yuni::String& prefix) const; + + //! find an edge from node names + linkInfo* findLinkInfoFromNodeNames(Data::AreaName& u, Data::AreaName& v) + { + auto linkIT = std::find_if(pLink.begin(), + pLink.end(), + [&u, &v](const linkInfo* edgeP) -> bool + { + if (edgeP->ptr->from->id == u && edgeP->ptr->with->id == v) + { + return true; + } + if (edgeP->ptr->from->id == v && edgeP->ptr->with->id == u) + { + return true; + } + else + { + return false; + } + }); + if (linkIT != pLink.end()) + { + return *linkIT; + } + + return nullptr; + } + + //! build list of edges from area + void buildAreaToLinkInfosMap() + { + areaToLinks.clear(); + for (auto& area: pStudy.areas) + { + auto a = area.second; + std::for_each(pLink.begin(), + pLink.end(), + [&a, this](linkInfo* edgeP) + { + if (edgeP->ptr->from == a || edgeP->ptr->with == a) + { + this->areaToLinks[a].insert(edgeP); + } + }); + } + } + + linkInfo* getLink(uint i) + { + if (i < pLink.size()) + { + return pLink[i]; + } + return nullptr; + } + + size_t linkCount() + { + return pLink.size(); + } + + bool isCycleDriver(linkInfo*); + + uint cycleCount(linkInfo* lnkI); + + /*! + ** \brief create all the network constraints based on a mesh + */ + bool createConstraints(const std::vector&); + + double setInfinite(const long value) + { + return infiniteSecondMember = value; + } + + bool setCheckNodalLoopFlow(const bool value) + { + return checkNodalLoopFlow = value; + } + + bool setLoopFlowInclusion(const bool value) + { + return includeLoopFlow = value; + } + + bool setPhaseShiftInclusion(const bool value) + { + return includePhaseShift = value; + } + + double getInfinite() + { + return infiniteSecondMember; + } + + bool getCheckNodalLoopFlow() + { + return checkNodalLoopFlow; + } + + bool getLoopFlowInclusion() + { + return includeLoopFlow; + } + + bool getPhaseShiftInclusion() + { + return includePhaseShift; + } + + bool setUpToDate(const bool value) + { + return isUpToDate = value; + } + + bool getUpToDate() + { + return isUpToDate; + } + + bool update(); + + bool updateLinks(); + + bool checkValidityOfNodalLoopFlow(linkInfo* linkInfo, size_t hour); + + void updateLinkPhaseShift(linkInfo* linkInfo, size_t hour) const; + bool checkLinkPhaseShift(linkInfo* linkInfo, size_t hour) const; + + void setCalendarStart(int start) + { + calendarStart = start; + } + + void setCalendarEnd(int end) + { + calendarEnd = end; + } + + uint getCalendarStart() + { + return calendarStart; + } + + uint getCalendarEnd() + { + return calendarEnd; + } + +private: + /*! + ** \brief add one constraint to the study + */ + std::shared_ptr addConstraint( + const Data::ConstraintName& name, + const Yuni::String& op, + const Yuni::String& type, + const WeightMap& weights, + const double& secondMember); + +public: + Vector pLink; + +private: + std::string pPrefix; + std::string pPrefixDelete; + bool pDelete; + bool includeLoopFlow = true; + bool includePhaseShift = true; + bool isUpToDate = false; + bool checkNodalLoopFlow = true; + double infiniteSecondMember = 1000000; + + uint calendarStart = 1; + uint calendarEnd = 8760; + + std::vector> pMesh; + + std::map> areaToLinks; + + Antares::Data::Study& pStudy; + + Graph::Grid _grid; + +}; // class cbuilder + +} // namespace Antares + +#endif // __ANTARES_CONSTRAINTSBUILDER_BUILDER_CBUILDER_H__ diff --git a/src/solver/constraints-builder/include/antares/solver/constraints-builder/grid.h b/src/solver/constraints-builder/include/antares/solver/constraints-builder/grid.h new file mode 100644 index 0000000000..3f69322359 --- /dev/null +++ b/src/solver/constraints-builder/include/antares/solver/constraints-builder/grid.h @@ -0,0 +1,412 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef CONSTRAINTSBUILDER_BUILDER_GRID_H +#define CONSTRAINTSBUILDER_BUILDER_GRID_H + +#include + +#include +#include + +#include + +// #include +// #include +// #include + +namespace Antares +{ +namespace Graph +{ +template +class Node +{ +public: + Node(NodeT* data) + { + nodeProperties = data; + } + + virtual ~Node() = default; + + virtual std::string getName() + { + return name; + } + + virtual void setName(std::string newName) + { + name = newName; + } + +public: + std::string name; + NodeT* nodeProperties; +}; + +template +class Edge +{ +public: + Edge(Node* from, Node* to) + { + originNode = from; + destinationNode = to; + } + + long getWeight() const + { + return weight; + } + + void setWeight(long w) + { + weight = w; + } + + Node* getOrigin() + { + return originNode; + } + + Node* getDestination() + { + return destinationNode; + } + + void setOrigin(Node* from) + { + originNode = from; + } + + void setDestination(Node* to) + { + destinationNode = to; + } + +private: + long weight; + Node* originNode; + Node* destinationNode; + +public: + struct addpWeight + { + long operator()(long i, const Edge* o) const + { + return (o->getWeight() + i); + } + }; + + struct compareWeight + { + bool operator()(const Edge* lhs, const Edge* rhs) const + { + return lhs->getWeight() < rhs->getWeight(); + } + }; +}; + +/*! +** \brief Antares Grid (graph) +*/ +template +class Grid +{ +public: + typedef Antares::Graph::Node* NodeP; + typedef Antares::Graph::Edge* EdgeP; + typedef std::vector VectorNodeP; + typedef std::vector VectorEdgeP; + typedef std::map MapNodes; + typedef std::vector EdgeIncidence; + +public: + //! \name Constructor & Destructor + //@{ + //! Constructor + Grid(); + //! Destructor + ~Grid(); + //@} + + //! Add one node to the graph + NodeP addNode(NodeT&, std::string); + + //! Add one edge to the graph + EdgeP addEdge(NodeP, NodeP, long weight = 0); + + uint getNumberOfConnectedComponents(); + + VectorEdgeP findShortestPath(NodeP node1, NodeP node2) const; + + //! find an edge from node names + EdgeP findEdgeFromNodeNames(std::string u, std::string v) + { + auto edgeIT = std::find_if(pEdgesList.begin(), + pEdgesList.end(), + [&u, &v](const EdgeP& edgeP) -> bool + { + if (edgeP->getOrigin()->getName() == u + && edgeP->getDestination()->getName() == v) + { + return true; + } + if (edgeP->getDestination()->getName() == u + && edgeP->getOrigin()->getName() == v) + { + return true; + } + else + { + return false; + } + }); + if (edgeIT != pEdgesList.end()) + { + return *edgeIT; + } + + return nullptr; + } + + EdgeP findDrivingEdgeFromNodeNames(std::string u, std::string v) + { + auto edgeIT = std::find_if(pMinSpanningTree.begin(), + pMinSpanningTree.end(), + [&u, &v](const EdgeP& edgeP) -> bool + { + if (edgeP->getOrigin()->getName() == u + && edgeP->getDestination()->getName() == v) + { + return true; + } + if (edgeP->getDestination()->getName() == u + && edgeP->getOrigin()->getName() == v) + { + return true; + } + else + { + return false; + } + }); + if (edgeIT != pMinSpanningTree.end()) + { + return *edgeIT; + } + + return nullptr; + } + + // remove an edge from the graph + void removeEdge(EdgeP e) + { + auto edgeIT = std::find(pEdgesList.begin(), pEdgesList.end(), e); + auto edge = *edgeIT; + if (edgeIT != pEdgesList.end()) + { + pEdgesList.erase(edgeIT); + + adjency[e->getOrigin()].erase(e->getDestination()); + adjency[e->getDestination()].erase(e->getOrigin()); + + delete edge; + } + } + + //! find a node from it's name + NodeP findNodeFromName(std::string name) + { + auto nodeIT = std::find_if(pNodesList.begin(), + pNodesList.end(), + [&name](NodeP& n) -> bool { return n->getName() == name; }); + if (nodeIT != pNodesList.end()) + { + return *nodeIT; + } + else + { + return nullptr; + } + } + + /*! + ** \brief Kruskal algorithm + ** + ** Search for the minimum spanning tree of the graph + ** Saved in pMinSpanningTree + */ + void kruskal(); + + /*! + ** \brief Get minimum spanning tree + ** + */ + /*VectorEdgeData getMinSpanningTree() + { + VectorEdgeData minSpanningTree(pMinSpanningTree.size()); + auto end = pMinSpanningTree.end(); + for (auto e = pMinSpanningTree.begin(); e != end; e++) + { + minSpanningTree.push_back((*e)->edgeProperties); + } + return minSpanningTree; + }*/ + + /*! + ** \brief Build pMesh + ** + ** the smallest set of loops meshing the graph + */ + bool buildMesh(); + + /*! + ** \brief Get the min cycle basis mesh + ** + ** the smallest set of loops meshing the graph + */ + const std::vector>& getMeshIndexMatrix() + { + return meshIndexMatrix; + } + + VectorEdgeP twoLevelPath(VectorNodeP vN); + + /*! + ** \brief get a Gid where edges and nodes are duplicated + ** + */ + bool getDuplicatedGrid(Grid&); + + /*! + ** \brief get a clone of the Grid + ** + */ + bool cloneGrid(Grid&); + + const VectorEdgeP& getEdges() + { + return pEdgesList; + } + +public: + EdgeIncidence getIncidenceVector(VectorEdgeP vE) + { + EdgeIncidence Ei(pEdgesList.size(), false); + for (uint i = 0; i < pEdgesList.size(); i++) + { + if (std::find(vE.begin(), vE.end(), pEdgesList[i]) != vE.end()) + { + Ei[i] = true; + } + } + return Ei; + } + + EdgeIncidence getIncidenceVector(EdgeP vE) + { + EdgeIncidence Ei(pEdgesList.size(), false); + for (uint i = 0; i < pEdgesList.size(); i++) + { + if (vE == pEdgesList[i]) + { + Ei[i] = true; + break; + } + } + return Ei; + } + + VectorEdgeP getEdgeVectorFromIncidence(EdgeIncidence vI) + { + VectorEdgeP vE; + for (uint i = 0; i < pEdgesList.size(); i++) + { + if (vI[i] == true) + { + vE.push_back(pEdgesList[i]); + } + } + return vE; + } + + EdgeIncidence incidenceXOR(EdgeIncidence& e1, EdgeIncidence& e2) + { + EdgeIncidence Ei(e1.size(), false); + std::transform(e1.begin(), e1.end(), e2.begin(), Ei.begin(), std::bit_xor()); + + return Ei; + } + + int incidenceInnerProduct(EdgeIncidence& e1, EdgeIncidence& e2) + { + int r1 = std::inner_product(e1.begin(), e1.end(), e2.begin(), 0); + return r1 % 2; + } + + void clear() + { + for (auto it = pNodesList.begin(); it != pNodesList.end(); it++) + { + delete (*it); + } + pNodesList.clear(); + + for (auto it = pEdgesList.begin(); it != pEdgesList.end(); it++) + { + delete (*it); + } + pEdgesList.clear(); + + pMinSpanningTree.clear(); + pMesh.clear(); + meshIndexMatrix.clear(); + adjency.clear(); + } + +private: + //! \definition of the graph + //@{ + //! list of nodes + VectorNodeP pNodesList; + //! list of edges + VectorEdgeP pEdgesList; + //@} + + //! Minimum Spanning Tree of the graph + VectorEdgeP pMinSpanningTree; + //! Smallest set of loops meshing all the graph + std::vector pMesh; + + std::vector> meshIndexMatrix; + + double inf; + + //! adjency list + std::map> adjency; +}; + +} // namespace Graph +} // namespace Antares + +#include "grid.hxx" +#endif // CONSTRAINTSBUILDER_BUILDER_GRID_H diff --git a/src/solver/constraints-builder/include/antares/solver/constraints-builder/grid.hxx b/src/solver/constraints-builder/include/antares/solver/constraints-builder/grid.hxx new file mode 100644 index 0000000000..4313bf9b29 --- /dev/null +++ b/src/solver/constraints-builder/include/antares/solver/constraints-builder/grid.hxx @@ -0,0 +1,510 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include +#include +#include +#include +#include + +#include "antares/solver/constraints-builder/cbuilder.h" +#include "antares/solver/constraints-builder/grid.h" + +using namespace Yuni; + +namespace Antares +{ +namespace Graph +{ +template +Grid::Grid(): + inf(0) +{ +} + +template +Grid::~Grid() +{ + for (auto i = pEdgesList.begin(); i != pEdgesList.end(); i++) + { + delete (*i); + } + for (auto i = pNodesList.begin(); i != pNodesList.end(); i++) + { + delete (*i); + } +} + +template +typename Grid::NodeP Grid::addNode(NodeT& n, std::string id) +{ + auto nodeIT = std::find_if(pNodesList.begin(), + pNodesList.end(), + [&id](const NodeP& nodeP) -> bool + { return nodeP->getName() == id; }); + + if (nodeIT == pNodesList.end()) + { + NodeP newNode = new Graph::Node(&n); + newNode->setName(id); + pNodesList.push_back(newNode); + return newNode; + } + else + { + return *nodeIT; + } +} + +template +typename Grid::EdgeP Grid::addEdge(NodeP n1, NodeP n2, long weight) +{ + std::string s1(n1->getName()); + std::string s2(n2->getName()); + EdgeP edgePtr = findEdgeFromNodeNames(s1, s2); + if (edgePtr == nullptr) + { + EdgeP newEdge = new Edge(n1, n2); + inf += weight; + newEdge->setWeight(weight); + + // add edge to the list + pEdgesList.push_back(newEdge); + + // redefine inf + inf += weight; + + // update adjency + adjency[newEdge->getOrigin()].insert(std::make_pair(newEdge->getDestination(), newEdge)); + adjency[newEdge->getDestination()].insert(std::make_pair(newEdge->getOrigin(), newEdge)); + + return newEdge; + } + else + { + return edgePtr; + } +} + +template +uint Grid::getNumberOfConnectedComponents() +{ + // create union-find set + MapNodes uf; + + for (auto i = pNodesList.begin(); i != pNodesList.end(); i++) + { + uf.insert(std::make_pair(*i, *i)); + } + + // algorithm + for (auto i = pEdgesList.begin(); i != pEdgesList.end(); i++) + { + // if the two areas are not yet connected + if (uf[(*i)->getOrigin()] != uf[(*i)->getDestination()]) + { + // update uf + NodeP cset(uf[(*i)->getDestination()]); + for (auto j = pNodesList.begin(); j != pNodesList.end(); j++) + { + if (uf[*j] == cset) + { + uf[*j] = uf[(*i)->getOrigin()]; + } + } + } + } + + std::unordered_map cVec; + for (auto cIT = uf.begin(); cIT != uf.end(); cIT++) + { + cVec[cIT->second] = true; + } + + return (uint)(cVec.size()); +} + +template +void Grid::kruskal() +{ + // clear spanning tree + pMinSpanningTree.clear(); + + // create union-find set + MapNodes uf; + + for (auto i = pNodesList.begin(); i != pNodesList.end(); i++) + { + uf.insert(std::make_pair(*i, *i)); + } + + // create temporary sorted vector of Link + VectorEdgeP tempEdgesList = pEdgesList; + std::stable_sort(tempEdgesList.begin(), + tempEdgesList.end(), + typename Graph::Edge::compareWeight()); + + // algorithm + for (auto i = tempEdgesList.begin(); i != tempEdgesList.end(); i++) + { + // if the two areas are not yet connected + if (uf[(*i)->getOrigin()] != uf[(*i)->getDestination()]) + { + pMinSpanningTree.push_back(*i); + + // update uf + NodeP cset(uf[(*i)->getDestination()]); + for (auto j = pNodesList.begin(); j != pNodesList.end(); j++) + { + if (uf[*j] == cset) + { + uf[*j] = uf[(*i)->getOrigin()]; + } + } + } + } +} + +template +bool Grid::buildMesh() +{ + // build the minimum spanning tree + kruskal(); + + if (pMinSpanningTree.empty()) + { + return false; + } + + // clear the spanning cycle base + pMesh.clear(); + meshIndexMatrix.clear(); + + // initialization + std::vector linksToBeAdded; + for (auto i = pEdgesList.begin(); i != pEdgesList.end(); i++) + { + // check if the link already belong to the skeleton + if (std::find(pMinSpanningTree.begin(), pMinSpanningTree.end(), (*i)) + == pMinSpanningTree.end()) + { + linksToBeAdded.push_back(*i); + } + } + + std::vector incidenceMatrix(linksToBeAdded.size()); + for (uint i = 0; i < linksToBeAdded.size(); i++) + { + incidenceMatrix[i] = getIncidenceVector(linksToBeAdded[i]); + } + + for (uint i = 0; i < linksToBeAdded.size(); i++) + { + logs.info() << "Searching basis (loop " << i + 1 << "/" << linksToBeAdded.size() << ")"; + // build the graph with two copies (+/-) for each node and edge + Grid polarisedDuplicate; + getDuplicatedGrid(polarisedDuplicate); + VectorEdgeP v = getEdgeVectorFromIncidence(incidenceMatrix[i]); + VectorEdgeP Ci; + //! vecteur contenant les sommets adjacents aux arêtes Ei + VectorNodeP adjacentNodes; + // retrait des arêtes (u,v) qui sont dans Ei et remplacement dans le graphe dupliqué + // par(u+,v-) et (u-,v+) + for (uint j = 0; j < v.size(); j++) + { + if (std::find(adjacentNodes.begin(), adjacentNodes.end(), v[j]->getOrigin()) + == adjacentNodes.end()) + { + adjacentNodes.push_back(v[j]->getOrigin()); + } + if (std::find(adjacentNodes.begin(), adjacentNodes.end(), v[j]->getDestination()) + == adjacentNodes.end()) + { + adjacentNodes.push_back(v[j]->getDestination()); + } + + EdgeP ei = polarisedDuplicate.findEdgeFromNodeNames(v[j]->getOrigin()->getName() + "+", + v[j]->getDestination()->getName() + + "+"); + + NodeP ni1 = polarisedDuplicate.findNodeFromName(v[j]->getOrigin()->getName() + "+"); + NodeP ni2 = polarisedDuplicate.findNodeFromName(v[j]->getDestination()->getName() + + "-"); + + polarisedDuplicate.addEdge(ni1, ni2, ei->getWeight()); + polarisedDuplicate.removeEdge(ei); + + ei = polarisedDuplicate.findEdgeFromNodeNames(v[j]->getOrigin()->getName() + "-", + v[j]->getDestination()->getName() + "-"); + + ni1 = polarisedDuplicate.findNodeFromName(v[j]->getOrigin()->getName() + "-"); + ni2 = polarisedDuplicate.findNodeFromName(v[j]->getDestination()->getName() + "+"); + + polarisedDuplicate.addEdge(ni1, ni2, ei->getWeight()); + polarisedDuplicate.removeEdge(ei); + } + + //! extraction du chemin sur deux niveaux + v = polarisedDuplicate.twoLevelPath(adjacentNodes); + + //! définition du cycle correspondant dans le graph d'origine (non signé) + Ci.clear(); + std::vector edgeIndices; + for (typename VectorEdgeP::iterator e = v.begin(); e != v.end(); e++) + { + auto name1 = (*e)->getOrigin()->getName(); + name1 = name1.substr(0, name1.length() - 1); + auto name2 = (*e)->getDestination()->getName(); + name2 = name2.substr(0, name2.length() - 1); + EdgeP ei = findEdgeFromNodeNames(name1, name2); + Ci.push_back(ei); + + auto eIT = std::find(pEdgesList.begin(), pEdgesList.end(), ei); + int pos = (int)std::distance(pEdgesList.begin(), eIT); + edgeIndices.push_back(pos); + } + + pMesh.push_back(Ci); + EdgeIncidence I = getIncidenceVector(Ci); + meshIndexMatrix.push_back(edgeIndices); + // remplacement par la différence symétrique des des jeux d'arêtes + for (uint j = i + 1; j < linksToBeAdded.size(); j++) + { + if (incidenceInnerProduct(I, incidenceMatrix[j]) == 1) + { + incidenceMatrix[j] = incidenceXOR(incidenceMatrix[i], incidenceMatrix[j]); + } + } + } + + return true; +} + +/*! +** \brief get a Grid where each edge and node is duplicated and signed +** \param a reference to a virgin grid object +*/ +template +bool Grid::getDuplicatedGrid(Grid& grid) +{ + // duplicate nodes + for (typename VectorNodeP::iterator node = pNodesList.begin(); node != pNodesList.end(); node++) + { + { //+ + grid.addNode((*(*node)->nodeProperties), (*node)->getName() + "+"); + } + + { //- + grid.addNode((*(*node)->nodeProperties), (*node)->getName() + "-"); + } + } + + // Duplicate edges + for (typename VectorEdgeP::iterator e = pEdgesList.begin(); e != pEdgesList.end(); e++) + { + { //+ + auto nodeOrigIT = std::find_if(grid.pNodesList.begin(), + grid.pNodesList.end(), + [&e](const NodeP& nodeP) -> bool { + return nodeP->getName() + == (*e)->getOrigin()->getName() + "+"; + }); + + auto nodeDestIT = std::find_if(grid.pNodesList.begin(), + grid.pNodesList.end(), + [&e](const NodeP& nodeP) -> bool { + return nodeP->getName() + == (*e)->getDestination()->getName() + "+"; + }); + + grid.addEdge(*nodeOrigIT, *nodeDestIT, (*e)->getWeight()); + } + + { //- + auto nodeOrigIT = std::find_if(grid.pNodesList.begin(), + grid.pNodesList.end(), + [&e](const NodeP& nodeP) -> bool { + return nodeP->getName() + == (*e)->getOrigin()->getName() + "-"; + }); + + auto nodeDestIT = std::find_if(grid.pNodesList.begin(), + grid.pNodesList.end(), + [&e](const NodeP& nodeP) -> bool { + return nodeP->getName() + == (*e)->getDestination()->getName() + "-"; + }); + + grid.addEdge(*nodeOrigIT, *nodeDestIT, (*e)->getWeight()); + } + } + return true; +} + +/*! +** \brief get a clone of the grid +** \param a reference to a virgin grid object +*/ +template +bool Grid::cloneGrid(Grid& grid) +{ + // duplicate nodes + for (typename VectorNodeP::iterator node = pNodesList.begin(); node != pNodesList.end(); node++) + { + { + grid.addNode((*(*node)->nodeProperties), (*node)->getName()); + } + } + + // duplicate edges + for (typename VectorEdgeP::iterator e = pEdgesList.begin(); e != pEdgesList.end(); e++) + { + { //+ + auto nodeOrigIT = std::find_if(grid.pNodesList.begin(), + grid.pNodesList.end(), + [&e](const NodeP& nodeP) -> bool { + return nodeP->getName() + == (*e)->getOrigin()->getName(); + }); + + auto nodeDestIT = std::find_if(grid.pNodesList.begin(), + grid.pNodesList.end(), + [&e](const NodeP& nodeP) -> bool { + return nodeP->getName() + == (*e)->getDestination()->getName(); + }); + + grid.addEdge(*nodeOrigIT, *nodeDestIT, (*e)->getWeight()); + } + } + return true; +} + +template +typename Grid::VectorEdgeP Grid::twoLevelPath(VectorNodeP vN) +{ + VectorEdgeP SP, minSP; + double minLength = DBL_MAX, length; + for (typename VectorNodeP::iterator n = vN.begin(); n != vN.end(); n++) + { + SP = findShortestPath(findNodeFromName((*n)->getName() + "+"), + findNodeFromName((*n)->getName() + "-")); + length = std::accumulate(SP.begin(), + SP.end(), + (long)0, + typename Graph::Edge::addpWeight()); + if (length < minLength) + { + minLength = length; + minSP = SP; + } + } + + return minSP; +} + +//! Find shortest path between the two nodes (Djikstra) +template +typename Grid::VectorEdgeP Grid::findShortestPath(NodeP node1, NodeP node2) const +{ + assert(node1 != node2); + + // Dijkstra (lots of computation which could be optimised) + // initialization + std::map dist; + std::map prev; + + // decorate to avoid warnings at compile + [[maybe_unused]] bool checkNode1(false), checkNode2(false); + VectorNodeP nodes = pNodesList; + + for (auto i = nodes.begin(); i != nodes.end(); i++) + { + dist[(*i)] = inf; + prev[(*i)] = 0; + if ((*i) == node1) + { + checkNode1 = true; + } + else if ((*i) == node2) + { + checkNode2 = true; + } + } + assert(checkNode1 && checkNode2); + dist[node1] = 0; + // search for shortest path + bool targetFound(0); + while (!targetFound) + { + // look for closest element u belonging in nodes + std::pair u(nullptr, inf - 1); + typename Grid::VectorNodeP::iterator ui; + for (auto i = nodes.begin(); i != nodes.end(); i++) + { + if (dist[(*i)] < u.second) + { + u.first = (*i); + u.second = dist[(*i)]; + ui = i; + } + } + + // see if destination node has been f + if (u.first == node2) + { + targetFound = true; + break; + } + + // remove u from the list of nodes + nodes.erase(ui); + + // update the neighoubours of u + for (auto i = adjency.at(u.first).begin(); i != adjency.at(u.first).end(); i++) + { + if (i->second == nullptr) + { + assert(0); + } + + if ((u.second + i->second->getWeight()) < dist[i->first]) + { + dist[i->first] = u.second + i->second->getWeight(); + prev[i->first] = u.first; + } + } + } + + // rebuild path + Grid::VectorEdgeP path; + Grid::NodeP currentNode = node2; + + while (prev[currentNode] != nullptr) + { + path.push_back(adjency.at(currentNode).at(prev[currentNode])); + currentNode = prev[currentNode]; + } + + return path; +} + +} // namespace Graph +} // namespace Antares diff --git a/src/solver/constraints-builder/load.cpp b/src/solver/constraints-builder/load.cpp index aa61fffa6c..22d8632cda 100644 --- a/src/solver/constraints-builder/load.cpp +++ b/src/solver/constraints-builder/load.cpp @@ -1,36 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "cbuilder.h" -#include -#include "../../config.h" -#include "../../libs/antares/study/area/constants.h" #include -//#include // bourrin -> � modifier -//#include "../../ui/simulator/application/study.h" + +#include +#include "antares/config/config.h" +#include "antares/solver/constraints-builder/cbuilder.h" +#include "antares/study/area/constants.h" using namespace Yuni; @@ -41,8 +34,8 @@ namespace Antares bool CBuilder::completeFromStudy() { uint nCount(1); - const Data::Area::Map::iterator end = pStudy->areas.end(); - for (Data::Area::Map::iterator i = pStudy->areas.begin(); i != end; ++i) + const Data::Area::Map::iterator end = pStudy.areas.end(); + for (Data::Area::Map::iterator i = pStudy.areas.begin(); i != end; ++i) { Data::Area& area = *(i->second); const Data::AreaLink::Map::iterator end = area.links.end(); diff --git a/src/solver/hydro/CMakeLists.txt b/src/solver/hydro/CMakeLists.txt index 8656eb100a..657c52e17a 100644 --- a/src/solver/hydro/CMakeLists.txt +++ b/src/solver/hydro/CMakeLists.txt @@ -1,78 +1,94 @@ project(hydro) set(SRC_EXT_SOLVER_H2O_DAILY - daily/h2o_j_construire_les_contraintes.cpp - daily/h2o_j_construire_les_variables.cpp - daily/h2o_j_donnees_mensuelles.h - daily/h2o_j_donnees_optimisation.h - daily/h2o_j_fonctions.h - daily/h2o_j_free.cpp - daily/h2o_j_initialiser_les_bornes_des_variables.cpp - daily/h2o_j_initialiser_les_second_membre.cpp - daily/h2o_j_instanciation.cpp - daily/h2o_j_optimiser_un_mois.cpp - daily/h2o_j_resoudre_le_probleme_lineaire.cpp - daily/h2o_j_lisser_les_sur_turbines.cpp - daily/h2o_j_ajouter_bruit_au_cout.cpp + daily/h2o_j_construire_les_contraintes.cpp + daily/h2o_j_construire_les_variables.cpp + include/antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h + include/antares/solver/hydro/daily/h2o_j_donnees_optimisation.h + include/antares/solver/hydro/daily/h2o_j_fonctions.h + daily/h2o_j_free.cpp + daily/h2o_j_initialiser_les_bornes_des_variables.cpp + daily/h2o_j_initialiser_les_second_membre.cpp + daily/h2o_j_instanciation.cpp + daily/h2o_j_optimiser_un_mois.cpp + daily/h2o_j_resoudre_le_probleme_lineaire.cpp + daily/h2o_j_lisser_les_sur_turbines.cpp + daily/h2o_j_ajouter_bruit_au_cout.cpp ) set(SRC_EXT_SOLVER_H2O_MONTHLY - monthly/h2o_m_construire_les_contraintes.cpp - monthly/h2o_m_construire_les_variables.cpp - monthly/h2o_m_donnees_annuelles.h - monthly/h2o_m_donnees_optimisation.h - monthly/h2o_m_fonctions.h - monthly/h2o_m_free.cpp - monthly/h2o_m_initialiser_les_bornes_des_variables.cpp - monthly/h2o_m_initialiser_les_second_membre.cpp - monthly/h2o_m_instanciation.cpp - monthly/h2o_m_optimiser_une_annee.cpp - monthly/h2o_m_ajouter_bruit.cpp - monthly/h2o_m_resoudre_le_probleme_lineaire.cpp + monthly/h2o_m_construire_les_contraintes.cpp + monthly/h2o_m_construire_les_variables.cpp + include/antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h + include/antares/solver/hydro/monthly/h2o_m_donnees_optimisation.h + include/antares/solver/hydro/monthly/h2o_m_fonctions.h + monthly/h2o_m_free.cpp + monthly/h2o_m_initialiser_les_bornes_des_variables.cpp + monthly/h2o_m_initialiser_les_second_membre.cpp + monthly/h2o_m_instanciation.cpp + monthly/h2o_m_optimiser_une_annee.cpp + monthly/h2o_m_ajouter_bruit.cpp + monthly/h2o_m_resoudre_le_probleme_lineaire.cpp ) set(SRC_EXT_SOLVER_H2O2_DAILY - daily2/h2o2_j_construire_les_contraintes.cpp - daily2/h2o2_j_construire_les_variables.cpp - daily2/h2o2_j_donnees_mensuelles.h - daily2/h2o2_j_donnees_optimisation.h - daily2/h2o2_j_fonctions.h - daily2/h2o2_j_free.cpp - daily2/h2o2_j_initialiser_les_bornes_des_variables.cpp - daily2/h2o2_j_initialiser_les_second_membre.cpp - daily2/h2o2_j_instanciation.cpp - daily2/h2o2_j_optimiser_un_mois.cpp - daily2/h2o2_j_resoudre_le_probleme_lineaire.cpp - daily2/h2o2_j_optim_costs.cpp - daily2/h2o2_j_apply_costs.cpp + daily2/h2o2_j_construire_les_contraintes.cpp + daily2/h2o2_j_construire_les_variables.cpp + include/antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h + include/antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h + include/antares/solver/hydro/daily2/h2o2_j_fonctions.h + daily2/h2o2_j_free.cpp + daily2/h2o2_j_initialiser_les_bornes_des_variables.cpp + daily2/h2o2_j_initialiser_les_second_membre.cpp + daily2/h2o2_j_instanciation.cpp + daily2/h2o2_j_optimiser_un_mois.cpp + daily2/h2o2_j_resoudre_le_probleme_lineaire.cpp + daily2/h2o2_j_optim_costs.cpp + daily2/h2o2_j_apply_costs.cpp ) set(SRC_MANAGEMENT - management.h - management/management.h - management/management.cpp - management/monthly.cpp - management/daily.cpp + include/antares/solver/hydro/management/management.h + management/management.cpp + include/antares/solver/hydro/management/PrepareInflows.h + management/PrepareInflows.cpp + management/monthly.cpp + management/daily.cpp + include/antares/solver/hydro/management/MinGenerationScaling.h + management/MinGenerationScaling.cpp + include/antares/solver/hydro/management/HydroInputsChecker.h + management/HydroInputsChecker.cpp + include/antares/solver/hydro/management/hydro-final-reservoir-level-functions.h + management/hydro-final-reservoir-level-functions.cpp ) - add_library(antares-solver-hydro - ${SRC_EXT_SOLVER_H2O_DAILY} - ${SRC_EXT_SOLVER_H2O_MONTHLY} - ${SRC_EXT_SOLVER_H2O2_DAILY} - ${SRC_MANAGEMENT} ) + ${SRC_EXT_SOLVER_H2O_DAILY} + ${SRC_EXT_SOLVER_H2O_MONTHLY} + ${SRC_EXT_SOLVER_H2O2_DAILY} + ${SRC_MANAGEMENT}) + +add_library(Antares::hydro ALIAS antares-solver-hydro) target_link_libraries(antares-solver-hydro - PRIVATE - model_antares - antares-solver-variable - Antares::study - Antares::mersenne - PUBLIC sirius_solver) + PRIVATE + model_antares + antares-solver-variable + Antares::study + Antares::mersenne + PUBLIC + sirius_solver + Antares::date + Antares::result_writer -target_include_directories(antares-solver-hydro - PRIVATE - ${CMAKE_SOURCE_DIR}/solver) +) +target_include_directories(antares-solver-hydro + PUBLIC + $ +) +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/solver/hydro/daily/h2o_j_ajouter_bruit_au_cout.cpp b/src/solver/hydro/daily/h2o_j_ajouter_bruit_au_cout.cpp index 8585b5cdb2..84f4a6ed9d 100644 --- a/src/solver/hydro/daily/h2o_j_ajouter_bruit_au_cout.cpp +++ b/src/solver/hydro/daily/h2o_j_ajouter_bruit_au_cout.cpp @@ -1,6 +1,26 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" namespace Constants { @@ -22,8 +42,8 @@ void H2O_J_AjouterBruitAuCout(DONNEES_MENSUELLES& donnesMensuelles) { for (int j = 0; j < ProblemeLineairePartieFixe[i].NombreDeVariables; j++) { - ProblemeLineairePartieFixe[i].CoutLineaire[j] - += noiseGenerator() * Constants::noiseAmplitude; + ProblemeLineairePartieFixe[i].CoutLineaire[j] += noiseGenerator() + * Constants::noiseAmplitude; } ProblemeLineairePartieFixe[i] diff --git a/src/solver/hydro/daily/h2o_j_construire_les_contraintes.cpp b/src/solver/hydro/daily/h2o_j_construire_les_contraintes.cpp index fbb3cad8ce..346f5e092e 100644 --- a/src/solver/hydro/daily/h2o_j_construire_les_contraintes.cpp +++ b/src/solver/hydro/daily/h2o_j_construire_les_contraintes.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" void H2O_J_ConstruireLesContraintes(int NbPdt, std::vector& NumeroDeVariableTurbine, diff --git a/src/solver/hydro/daily/h2o_j_construire_les_variables.cpp b/src/solver/hydro/daily/h2o_j_construire_les_variables.cpp index cca46ab312..98ab62116c 100644 --- a/src/solver/hydro/daily/h2o_j_construire_les_variables.cpp +++ b/src/solver/hydro/daily/h2o_j_construire_les_variables.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifdef __CPLUSPLUS @@ -36,16 +30,17 @@ extern "C" } #endif -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" -void H2O_j_ConstruireLesVariables(int NbPdt, - std::vector& NumeroDeVariableTurbine, - std::vector& Xmin, - std::vector& Xmax, - std::vector& TypeDeVariable, - std::vector& AdresseOuPlacerLaValeurDesVariablesOptimisees, - CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables) +void H2O_j_ConstruireLesVariables( + int NbPdt, + std::vector& NumeroDeVariableTurbine, + std::vector& Xmin, + std::vector& Xmax, + std::vector& TypeDeVariable, + std::vector& AdresseOuPlacerLaValeurDesVariablesOptimisees, + CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables) { int Var = 0; @@ -62,14 +57,14 @@ void H2O_j_ConstruireLesVariables(int NbPdt, Xmin[Var] = 0.0; Xmax[Var] = LINFINI; TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = nullptr; Var++; CorrespondanceDesVariables.NumeroDeLaVariableXi = Var; Xmin[Var] = 0.0; Xmax[Var] = LINFINI; TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = nullptr; Var++; return; diff --git a/src/solver/hydro/daily/h2o_j_donnees_mensuelles.h b/src/solver/hydro/daily/h2o_j_donnees_mensuelles.h deleted file mode 100644 index 4b294a0c9f..0000000000 --- a/src/solver/hydro/daily/h2o_j_donnees_mensuelles.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __SOLVER_H2O_J_DONNEES_ANNEE__ -#define __SOLVER_H2O_J_DONNEES_ANNEE__ - -#define OUI 1 -#define NON 0 -#define EMERGENCY_SHUT_DOWN 2 - -#include "h2o_j_donnees_optimisation.h" - -/*************************************************************************************************/ -/* Structure contenant les champs a renseigner par l'appelant */ - -struct DONNEES_MENSUELLES -{ - /* En entree: seules les donnees ci-dessous doivent etre renseignees par l'appelant apres - avoir appele H2O_J_Instanciation */ - int NombreDeJoursDuMois; /* A renseigner par l'appelant */ - double TurbineDuMois; /* A renseigner par l'appelant (c'est le turbine opt du mois) */ - std::vector TurbineMax; /* A renseigner par l'appelant : 1 valeur par jour */ - std::vector TurbineMin; - std::vector TurbineCible; /* A renseigner par l'appelant : 1 valeur par jour */ - /* Les resultats */ - char - ResultatsValides; /* Vaut: - OUI si la solution est exploitable pour le reservoir - NON s'il y a eu un probleme dans la resolution - EMERGENCY_SHUT_DOWN si la resolution du probleme a donne lieu a une erreur interne - */ - std::vector Turbine; /* Resultat a recuperer par l'appelant */ - - /******************************************************************************************/ - /* Problemes internes (utilise uniquement par l'optimisation) */ - PROBLEME_HYDRAULIQUE ProblemeHydraulique; -}; - -#endif diff --git a/src/solver/hydro/daily/h2o_j_donnees_optimisation.h b/src/solver/hydro/daily/h2o_j_donnees_optimisation.h deleted file mode 100644 index 7038184313..0000000000 --- a/src/solver/hydro/daily/h2o_j_donnees_optimisation.h +++ /dev/null @@ -1,145 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_H2O_J_STRUCTURE_INTERNE__ -#define __SOLVER_H2O_J_STRUCTURE_INTERNE__ - -#ifdef __CPLUSPLUS -extern "C" -{ -#endif - -#include "spx_definition_arguments.h" -#include "spx_fonctions.h" - -#ifdef __CPLUSPLUS -} -#endif - -#define LINFINI 1.e+80 - -#define JOURS_28 28 -#define JOURS_29 29 -#define JOURS_30 30 -#define JOURS_31 31 -#define NOMBRE_DE_TYPE_DE_MOIS 4 - -#include -#include - -/*--------------------------------------------------------------------------------------*/ -/* Matrice des contraintes: il y aura une seule instance pour tous les reservoirs */ -/* Dans ce struct il n'y a que des donnees qui sont lues et surtout pas ecrites */ -/* Ce struct est instancie une seule fois */ -struct PROBLEME_LINEAIRE_PARTIE_FIXE -{ - int NombreDeVariables; - std::vector CoutLineaire; - std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les suivantes - (voir le fichier spx_constantes_externes.h mais ne jamais utiliser les - valeurs explicites des constantes): VARIABLE_FIXE , - VARIABLE_BORNEE_DES_DEUX_COTES , - VARIABLE_BORNEE_INFERIEUREMENT , - VARIABLE_BORNEE_SUPERIEUREMENT , - VARIABLE_NON_BORNEE - */ - /* La matrice des contraintes */ - int NombreDeContraintes; - std::vector Sens; - std::vector IndicesDebutDeLigne; - std::vector NombreDeTermesDesLignes; - std::vector CoefficientsDeLaMatriceDesContraintes; - std::vector IndicesColonnes; - int NombreDeTermesAlloues; -}; - -/* Partie variable renseignee avant le lancement de l'optimisation de chaque reservoir */ -struct PROBLEME_LINEAIRE_PARTIE_VARIABLE -{ - /* Donnees variables de la matrice des contraintes */ - /* On met quand-meme les bornes dans la partie variable pour le cas ou on voudrait avoir - un jour des bornes min et max variables dans le temps et en fonction des reservoirs */ - std::vector Xmin; - std::vector Xmax; - std::vector SecondMembre; - /* Tableau de pointeur a des doubles. Ce tableau est parallele a X, il permet - de renseigner directement les structures de description du reseau avec les - resultats contenus dans X */ - std::vector AdresseOuPlacerLaValeurDesVariablesOptimisees; - /* Resultat */ - std::vector X; - /* En Entree ou en Sortie */ - int ExistenceDUneSolution; /* En sortie, vaut : - OUI_SPX s'il y a une solution, - NON_SPX s'il n'y a pas de solution - admissible SPX_ERREUR_INTERNE si probleme a l'execution - (saturation memoire par exemple), et dans ce cas il n'y a pas de - solution SPX_MATRICE_DE_BASE_SINGULIERE si on n'a pas pu - construire de matrice de base reguliere, et dans ce cas il n'y a - pas de solution - */ - - std::vector PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector CoutsReduits; /* Vecteur a passer au Simplexe pour recuperer les couts reduits */ - std::vector CoutsMarginauxDesContraintes; /* Vecteur a passer au Simplexe pour recuperer les couts - marginaux */ -}; - -/* Les correspondances fixes des contraintes */ -struct CORRESPONDANCE_DES_CONTRAINTES -{ - int NumeroDeContrainteDEnergieMensuelle; - std::vector NumeroDeContrainteSurXi; -}; - -/* Les correspondances des variables */ -struct CORRESPONDANCE_DES_VARIABLES -{ - std::vector NumeroDeVariableTurbine; /* Turbines */ - int NumeroDeLaVariableMu; /* Variable de deversement (total sur la periode) */ - int NumeroDeLaVariableXi; /* Variable decrivant l'ecart max au turbine cible quand le turbine - est inferieur au turbine cible */ -}; - -/* Structure uniquement exploitee par l'optimisation (donc a ne pas acceder depuis l'exterieur) */ -struct PROBLEME_HYDRAULIQUE -{ - char LesCoutsOntEteInitialises; /* Vaut OUI ou NON */ - - int NombreDeProblemes; - std::vector NbJoursDUnProbleme; - - std::vector CorrespondanceDesVariables; - std::vector CorrespondanceDesContraintes; - - std::vector ProblemeLineairePartieFixe; - std::vector ProblemeLineairePartieVariable; - - std::vector ProblemeSpx; /* Il y en a 1 par reservoir. Un probleme couvre 1 mois */ -}; - -#endif diff --git a/src/solver/hydro/daily/h2o_j_fonctions.h b/src/solver/hydro/daily/h2o_j_fonctions.h deleted file mode 100644 index 5614e98d12..0000000000 --- a/src/solver/hydro/daily/h2o_j_fonctions.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __SOLVER_H2O_J_FONCTIONS__ -#define __SOLVER_H2O_J_FONCTIONS__ - -DONNEES_MENSUELLES* H2O_J_Instanciation(void); - -void H2O_J_OptimiserUnMois(DONNEES_MENSUELLES*); -void H2O_J_Free(DONNEES_MENSUELLES*); -void H2O_J_ConstruireLesContraintes(int, - std::vector&, - int, - int, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - CORRESPONDANCE_DES_CONTRAINTES&); -void H2O_j_ConstruireLesVariables(int, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - CORRESPONDANCE_DES_VARIABLES&); -void H2O_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES*, int); -void H2O_J_InitialiserLeSecondMembre(DONNEES_MENSUELLES*, int); -void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES*, int); -void H2O_J_LisserLesSurTurbines(DONNEES_MENSUELLES*, int); -void H2O_J_AjouterBruitAuCout(DONNEES_MENSUELLES&); - -#endif /* __SOLVER_H2O_J_FONCTIONS__ */ diff --git a/src/solver/hydro/daily/h2o_j_free.cpp b/src/solver/hydro/daily/h2o_j_free.cpp index d19196ab49..5e7ac826ca 100644 --- a/src/solver/hydro/daily/h2o_j_free.cpp +++ b/src/solver/hydro/daily/h2o_j_free.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifdef __CPLUSPLUS @@ -37,8 +31,8 @@ extern "C" } #endif -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" void H2O_J_Free(DONNEES_MENSUELLES* DonneesMensuelles) { @@ -48,7 +42,9 @@ void H2O_J_Free(DONNEES_MENSUELLES* DonneesMensuelles) { PROBLEME_SPX* ProbSpx = (PROBLEME_SPX*)ProblemeHydraulique.ProblemeSpx[i]; if (ProbSpx) + { SPX_LibererProbleme(ProbSpx); + } } return; diff --git a/src/solver/hydro/daily/h2o_j_initialiser_les_bornes_des_variables.cpp b/src/solver/hydro/daily/h2o_j_initialiser_les_bornes_des_variables.cpp index 913c2a02a9..50f6e72bd5 100644 --- a/src/solver/hydro/daily/h2o_j_initialiser_les_bornes_des_variables.cpp +++ b/src/solver/hydro/daily/h2o_j_initialiser_les_bornes_des_variables.cpp @@ -1,34 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" #include +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" + void H2O_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES* DonneesMensuelles, int NumeroDeProbleme) { @@ -41,16 +36,17 @@ void H2O_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES* DonneesMensuelle const int NbPdt = ProblemeHydraulique.NbJoursDUnProbleme[NumeroDeProbleme]; - const CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables[NumeroDeProbleme]; + const CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables = ProblemeHydraulique + .CorrespondanceDesVariables + [NumeroDeProbleme]; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable[NumeroDeProbleme]; + = ProblemeHydraulique.ProblemeLineairePartieVariable[NumeroDeProbleme]; std::vector& Xmin = ProblemeLineairePartieVariable.Xmin; std::vector& Xmax = ProblemeLineairePartieVariable.Xmax; std::vector& AdresseOuPlacerLaValeurDesVariablesOptimisees - = ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees; + = ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees; for (int Pdt = 0; Pdt < NbPdt; Pdt++) { diff --git a/src/solver/hydro/daily/h2o_j_initialiser_les_second_membre.cpp b/src/solver/hydro/daily/h2o_j_initialiser_les_second_membre.cpp index 0035235297..13d5ae7b88 100644 --- a/src/solver/hydro/daily/h2o_j_initialiser_les_second_membre.cpp +++ b/src/solver/hydro/daily/h2o_j_initialiser_les_second_membre.cpp @@ -1,45 +1,41 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" void H2O_J_InitialiserLeSecondMembre(DONNEES_MENSUELLES* DonneesMensuelles, int NumeroDeProbleme) { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesMensuelles->ProblemeHydraulique; - CORRESPONDANCE_DES_CONTRAINTES& CorrespondanceDesContraintes - = ProblemeHydraulique.CorrespondanceDesContraintes[NumeroDeProbleme]; + CORRESPONDANCE_DES_CONTRAINTES& CorrespondanceDesContraintes = ProblemeHydraulique + .CorrespondanceDesContraintes + [NumeroDeProbleme]; - int NumeroDeContrainteDEnergieMensuelle - = CorrespondanceDesContraintes.NumeroDeContrainteDEnergieMensuelle; + int NumeroDeContrainteDEnergieMensuelle = CorrespondanceDesContraintes + .NumeroDeContrainteDEnergieMensuelle; - std::vector& SecondMembre - = ProblemeHydraulique.ProblemeLineairePartieVariable[NumeroDeProbleme].SecondMembre; + std::vector& SecondMembre = ProblemeHydraulique + .ProblemeLineairePartieVariable[NumeroDeProbleme] + .SecondMembre; SecondMembre[NumeroDeContrainteDEnergieMensuelle] = DonneesMensuelles->TurbineDuMois; diff --git a/src/solver/hydro/daily/h2o_j_instanciation.cpp b/src/solver/hydro/daily/h2o_j_instanciation.cpp index f9b6f06beb..175743432a 100644 --- a/src/solver/hydro/daily/h2o_j_instanciation.cpp +++ b/src/solver/hydro/daily/h2o_j_instanciation.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" DONNEES_MENSUELLES* H2O_J_Instanciation(void) { @@ -62,16 +56,16 @@ DONNEES_MENSUELLES* H2O_J_Instanciation(void) ProblemeHydraulique.ProblemeSpx.assign(NombreDeProblemes, nullptr); std::vector& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables; + = ProblemeHydraulique.CorrespondanceDesVariables; std::vector& CorrespondanceDesContraintes - = ProblemeHydraulique.CorrespondanceDesContraintes; + = ProblemeHydraulique.CorrespondanceDesContraintes; std::vector& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; + = ProblemeHydraulique.ProblemeLineairePartieFixe; std::vector& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable; + = ProblemeHydraulique.ProblemeLineairePartieVariable; for (int i = 0; i < NombreDeProblemes; i++) { diff --git a/src/solver/hydro/daily/h2o_j_lisser_les_sur_turbines.cpp b/src/solver/hydro/daily/h2o_j_lisser_les_sur_turbines.cpp index 5a5c5ea66f..5813a1df88 100644 --- a/src/solver/hydro/daily/h2o_j_lisser_les_sur_turbines.cpp +++ b/src/solver/hydro/daily/h2o_j_lisser_les_sur_turbines.cpp @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" - #include +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" + #define ZERO 1.e-9 void H2O_J_LisserLesSurTurbines(DONNEES_MENSUELLES* DonneesMensuelles, int NumeroDeProbleme) @@ -46,14 +40,22 @@ void H2O_J_LisserLesSurTurbines(DONNEES_MENSUELLES* DonneesMensuelles, int Numer double SurTurbineARepartir = 0.0; for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { flag[Pdt] = (Turbine[Pdt] - TurbineCible[Pdt] > ZERO); + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { if (flag[Pdt]) + { SurTurbineARepartir += Turbine[Pdt] - TurbineCible[Pdt]; + } + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) - flag[Pdt] = (TurbineMax[Pdt] - TurbineCible[Pdt] > ZERO);; + { + flag[Pdt] = (TurbineMax[Pdt] - TurbineCible[Pdt] > ZERO); + }; int NbCycles = 0; BoucleDeRepartition: @@ -61,28 +63,42 @@ void H2O_J_LisserLesSurTurbines(DONNEES_MENSUELLES* DonneesMensuelles, int Numer const int Np = std::count(flag.begin(), flag.end(), true); if (Np == 0) + { return; + } double MargeMin = 0.; for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { MargeMin += TurbineMax[Pdt]; + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { if (flag[Pdt] && TurbineMax[Pdt] - TurbineCible[Pdt] < MargeMin) + { MargeMin = TurbineMax[Pdt] - TurbineCible[Pdt]; + } + } double Xmoy = SurTurbineARepartir / Np; double SurTurbine; if (Xmoy <= MargeMin) + { SurTurbine = Xmoy; + } else + { SurTurbine = MargeMin; + } bool limiteAtteinte = false; for (int Pdt = 0; Pdt < NbPdt; Pdt++) { if (!flag[Pdt]) + { continue; + } Turbine[Pdt] = TurbineCible[Pdt] + SurTurbine; if (TurbineMax[Pdt] - Turbine[Pdt] <= ZERO) @@ -97,7 +113,9 @@ void H2O_J_LisserLesSurTurbines(DONNEES_MENSUELLES* DonneesMensuelles, int Numer { NbCycles++; if (NbCycles <= NbPdt) + { goto BoucleDeRepartition; + } } return; diff --git a/src/solver/hydro/daily/h2o_j_optimiser_un_mois.cpp b/src/solver/hydro/daily/h2o_j_optimiser_un_mois.cpp index 73caf5b7cf..07b507284c 100644 --- a/src/solver/hydro/daily/h2o_j_optimiser_un_mois.cpp +++ b/src/solver/hydro/daily/h2o_j_optimiser_un_mois.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" void H2O_J_OptimiserUnMois(DONNEES_MENSUELLES* DonneesMensuelles) { diff --git a/src/solver/hydro/daily/h2o_j_resoudre_le_probleme_lineaire.cpp b/src/solver/hydro/daily/h2o_j_resoudre_le_probleme_lineaire.cpp index 48a9be0802..1786428cef 100644 --- a/src/solver/hydro/daily/h2o_j_resoudre_le_probleme_lineaire.cpp +++ b/src/solver/hydro/daily/h2o_j_resoudre_le_probleme_lineaire.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_j_donnees_mensuelles.h" -#include "h2o_j_fonctions.h" +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" #ifdef _MSC_VER #define SNPRINTF sprintf_s @@ -41,10 +35,11 @@ void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES* DonneesMensuelles, int PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesMensuelles->ProblemeHydraulique; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable[NumeroDeProbleme]; + = ProblemeHydraulique.ProblemeLineairePartieVariable[NumeroDeProbleme]; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe[NumeroDeProbleme]; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe + [NumeroDeProbleme]; PROBLEME_SPX* ProbSpx = ProblemeHydraulique.ProblemeSpx[NumeroDeProbleme]; std::unique_ptr Probleme = std::make_unique(); @@ -84,8 +79,9 @@ void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES* DonneesMensuelles, int Probleme->IndicesDebutDeLigne = ProblemeLineairePartieFixe.IndicesDebutDeLigne.data(); Probleme->NombreDeTermesDesLignes = ProblemeLineairePartieFixe.NombreDeTermesDesLignes.data(); Probleme->IndicesColonnes = ProblemeLineairePartieFixe.IndicesColonnes.data(); - Probleme->CoefficientsDeLaMatriceDesContraintes - = ProblemeLineairePartieFixe.CoefficientsDeLaMatriceDesContraintes.data(); + Probleme->CoefficientsDeLaMatriceDesContraintes = ProblemeLineairePartieFixe + .CoefficientsDeLaMatriceDesContraintes + .data(); Probleme->Sens = ProblemeLineairePartieFixe.Sens.data(); Probleme->SecondMembre = ProblemeLineairePartieVariable.SecondMembre.data(); @@ -104,15 +100,19 @@ void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES* DonneesMensuelles, int Probleme->UtiliserCoutMax = NON_SPX; Probleme->CoutMax = 0.0; - Probleme->CoutsMarginauxDesContraintes - = ProblemeLineairePartieVariable.CoutsMarginauxDesContraintes.data(); + Probleme->CoutsMarginauxDesContraintes = ProblemeLineairePartieVariable + .CoutsMarginauxDesContraintes.data(); Probleme->CoutsReduits = ProblemeLineairePartieVariable.CoutsReduits.data(); #ifndef NDEBUG if (PremierPassage) + { Probleme->AffichageDesTraces = NON_SPX; + } else + { Probleme->AffichageDesTraces = OUI_SPX; + } #else Probleme->AffichageDesTraces = NON_SPX; #endif @@ -122,17 +122,20 @@ void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES* DonneesMensuelles, int ProbSpx = SPX_Simplexe(Probleme.get(), ProbSpx); if (ProbSpx) + { ProblemeHydraulique.ProblemeSpx[NumeroDeProbleme] = ProbSpx; + } ProblemeLineairePartieVariable.ExistenceDUneSolution = Probleme->ExistenceDUneSolution; - if (ProblemeLineairePartieVariable.ExistenceDUneSolution != OUI_SPX && PremierPassage && ProbSpx) + if (ProblemeLineairePartieVariable.ExistenceDUneSolution != OUI_SPX && PremierPassage + && ProbSpx) { if (ProblemeLineairePartieVariable.ExistenceDUneSolution != SPX_ERREUR_INTERNE) { SPX_LibererProbleme(ProbSpx); - ProbSpx = NULL; + ProbSpx = nullptr; PremierPassage = false; goto RESOLUTION; } @@ -149,9 +152,12 @@ void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES* DonneesMensuelles, int for (int Var = 0; Var < ProblemeLineairePartieFixe.NombreDeVariables; Var++) { - double* pt = ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + double* pt = ProblemeLineairePartieVariable + .AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; if (pt) + { *pt = ProblemeLineairePartieVariable.X[Var]; + } } } else diff --git a/src/solver/hydro/daily2/h2o2_j_apply_costs.cpp b/src/solver/hydro/daily2/h2o2_j_apply_costs.cpp index fef95fe20b..33eb6a42d4 100644 --- a/src/solver/hydro/daily2/h2o2_j_apply_costs.cpp +++ b/src/solver/hydro/daily2/h2o2_j_apply_costs.cpp @@ -1,39 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" -#include "h2o2_j_donnees_optimisation.h" -#include "h2o2_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" void H2O2_J_apply_costs(const Hydro_problem_costs& h2o2_costs, DONNEES_MENSUELLES_ETENDUES& problem) { int NombreDeProblemes = problem.ProblemeHydrauliqueEtendu.NombreDeProblemes; - auto& ProblemeLineaireEtenduPartieFixe - = problem.ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieFixe; + auto& ProblemeLineaireEtenduPartieFixe = problem.ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieFixe; auto& CorrespondanceDesVariables = problem.ProblemeHydrauliqueEtendu.CorrespondanceDesVariables; const auto& NbJoursDUnProbleme = problem.ProblemeHydrauliqueEtendu.NbJoursDUnProbleme; @@ -42,27 +36,37 @@ void H2O2_J_apply_costs(const Hydro_problem_costs& h2o2_costs, DONNEES_MENSUELLE int NbPdt = NbJoursDUnProbleme[pb_num]; for (int var = 0; var < ProblemeLineaireEtenduPartieFixe[pb_num].NombreDeVariables; var++) + { ProblemeLineaireEtenduPartieFixe[pb_num].CoutLineaire[var] = 0.0; + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { ProblemeLineaireEtenduPartieFixe[pb_num] .CoutLineaire[CorrespondanceDesVariables[pb_num].NumeroVar_niveauxFinJours[Pdt]] = h2o2_costs.get_end_days_levels_cost(); + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { ProblemeLineaireEtenduPartieFixe[pb_num] .CoutLineaire[CorrespondanceDesVariables[pb_num].NumeroVar_overflow[Pdt]] = h2o2_costs.get_overflow_cost(); + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { ProblemeLineaireEtenduPartieFixe[pb_num] .CoutLineaire[CorrespondanceDesVariables[pb_num].NumeroVar_deviations[Pdt]] = h2o2_costs.get_deviations_cost(); + } for (int Pdt = 0; Pdt < NbPdt; Pdt++) + { ProblemeLineaireEtenduPartieFixe[pb_num] .CoutLineaire[CorrespondanceDesVariables[pb_num].NumeroVar_violations[Pdt]] = h2o2_costs.get_violations_cost(); + } ProblemeLineaireEtenduPartieFixe[pb_num] .CoutLineaire[CorrespondanceDesVariables[pb_num].NumeroVar_waste] diff --git a/src/solver/hydro/daily2/h2o2_j_construire_les_contraintes.cpp b/src/solver/hydro/daily2/h2o2_j_construire_les_contraintes.cpp index 57cdddd6af..3dfd3db66b 100644 --- a/src/solver/hydro/daily2/h2o2_j_construire_les_contraintes.cpp +++ b/src/solver/hydro/daily2/h2o2_j_construire_les_contraintes.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" -#include "h2o2_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" void H2O2_J_ConstruireLesContraintes( int NbPdt, diff --git a/src/solver/hydro/daily2/h2o2_j_construire_les_variables.cpp b/src/solver/hydro/daily2/h2o2_j_construire_les_variables.cpp index 3543e733e2..37123dfd8c 100644 --- a/src/solver/hydro/daily2/h2o2_j_construire_les_variables.cpp +++ b/src/solver/hydro/daily2/h2o2_j_construire_les_variables.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifdef __CPLUSPLUS @@ -36,7 +30,7 @@ extern "C" } #endif -#include "h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" void H2O2_j_ConstruireLesVariables( int NbPdt, @@ -55,8 +49,8 @@ void H2O2_j_ConstruireLesVariables( Xmin[Var] = 0.0; Xmax[Var] = 0.0; TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesMensuellesEtendues.Turbine[Pdt]); + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesMensuellesEtendues.Turbine[Pdt]); Var++; } @@ -66,8 +60,8 @@ void H2O2_j_ConstruireLesVariables( Xmin[Var] = 0.0; Xmax[Var] = 1.0; TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesMensuellesEtendues.niveauxFinJours[Pdt]); + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesMensuellesEtendues.niveauxFinJours[Pdt]); Var++; } @@ -84,8 +78,8 @@ void H2O2_j_ConstruireLesVariables( Xmin[Var] = 0.0; Xmax[Var] = LINFINI; TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesMensuellesEtendues.overflows[Pdt]); + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesMensuellesEtendues.overflows[Pdt]); Var++; } @@ -95,8 +89,8 @@ void H2O2_j_ConstruireLesVariables( Xmin[Var] = 0.0; Xmax[Var] = LINFINI; TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesMensuellesEtendues.deviations[Pdt]); + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesMensuellesEtendues.deviations[Pdt]); Var++; } @@ -106,8 +100,8 @@ void H2O2_j_ConstruireLesVariables( Xmin[Var] = 0.0; Xmax[Var] = LINFINI; TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesMensuellesEtendues.violations[Pdt]); + AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesMensuellesEtendues.violations[Pdt]); Var++; } diff --git a/src/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h b/src/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h deleted file mode 100644 index aae31e224e..0000000000 --- a/src/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __SOLVER_H2O2_J_DONNEES_ANNEE__ -#define __SOLVER_H2O2_J_DONNEES_ANNEE__ - -#define OUI 1 -#define NON 0 -#define EMERGENCY_SHUT_DOWN 2 - -#include "h2o2_j_donnees_optimisation.h" - -/*************************************************************************************************/ -/* Structure contenant les champs a renseigner par l'appelant */ -/*************************************************************************************************/ - -typedef struct -{ - /* En entree: seules les donnees ci-dessous doivent etre renseignees par l'appelant apres - avoir appele H2O2_J_Instanciation */ - int NombreDeJoursDuMois; /* A renseigner par l'appelant */ - double TurbineDuMois; /* A renseigner par l'appelant (somme des turbines cibles du mois) */ - std::vector TurbineMax; /* A renseigner par l'appelant : 1 valeur par jour */ - std::vector TurbineMin; /*Minimum Hourly Hydro-Storage Generation*/ - std::vector TurbineCible; /* A renseigner par l'appelant : 1 valeur par jour */ - double reservoirCapacity; - double NiveauInitialDuMois; - std::vector niveauBas; - std::vector apports; - - /* Les resultats */ - char ResultatsValides; /* Vaut: - OUI si la solution est exploitable pour - le reservoir NON s'il y a eu un probleme dans la resolution - EMERGENCY_SHUT_DOWN si la resolution du - probleme a donne lieu a une erreur interne - */ - std::vector Turbine; /* Resultat a recuperer par l'appelant */ - std::vector niveauxFinJours; - std::vector overflows; - std::vector deviations; - std::vector violations; - double deviationMax; - double violationMax; - double waste; - - double CoutSolution; - - /******************************************************************************************/ - - /* Problemes internes (utilise uniquement par l'optimisation) */ - PROBLEME_HYDRAULIQUE_ETENDU ProblemeHydrauliqueEtendu; -} DONNEES_MENSUELLES_ETENDUES; - -#endif diff --git a/src/solver/hydro/daily2/h2o2_j_fonctions.h b/src/solver/hydro/daily2/h2o2_j_fonctions.h deleted file mode 100644 index a96934ca41..0000000000 --- a/src/solver/hydro/daily2/h2o2_j_fonctions.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __SOLVER_H2O2_J_FONCTIONS__ -#define __SOLVER_H2O2_J_FONCTIONS__ - -DONNEES_MENSUELLES_ETENDUES H2O2_J_Instanciation(); -void H2O2_J_OptimiserUnMois(DONNEES_MENSUELLES_ETENDUES&); -void H2O2_J_Free(DONNEES_MENSUELLES_ETENDUES&); -void H2O2_J_ConstruireLesContraintes(int, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - CORRESPONDANCE_DES_VARIABLES_PB_ETENDU&); -void H2O2_j_ConstruireLesVariables(int, - DONNEES_MENSUELLES_ETENDUES&, - std::vector&, - std::vector&, - std::vector&, - std::vector&, - CORRESPONDANCE_DES_VARIABLES_PB_ETENDU&); -void H2O2_J_apply_costs(const Hydro_problem_costs&, DONNEES_MENSUELLES_ETENDUES&); -void H2O2_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES_ETENDUES&, int); -void H2O2_J_InitialiserLeSecondMembre(DONNEES_MENSUELLES_ETENDUES&, int); -void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES&, int); - -#endif /* __SOLVER_H2O2_J_FONCTIONS__ */ diff --git a/src/solver/hydro/daily2/h2o2_j_free.cpp b/src/solver/hydro/daily2/h2o2_j_free.cpp index 39fd211fd0..c6c0d10342 100644 --- a/src/solver/hydro/daily2/h2o2_j_free.cpp +++ b/src/solver/hydro/daily2/h2o2_j_free.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifdef __CPLUSPLUS @@ -37,8 +31,8 @@ extern "C" } #endif -#include "h2o2_j_donnees_mensuelles.h" -#include "h2o2_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" void H2O2_J_Free(DONNEES_MENSUELLES_ETENDUES& DonneesMensuelles) { @@ -49,7 +43,9 @@ void H2O2_J_Free(DONNEES_MENSUELLES_ETENDUES& DonneesMensuelles) { auto ProbSpx = ProblemeHydrauliqueEtendu.ProblemeSpx[i]; if (ProbSpx) + { SPX_LibererProbleme(ProbSpx); + } } return; diff --git a/src/solver/hydro/daily2/h2o2_j_initialiser_les_bornes_des_variables.cpp b/src/solver/hydro/daily2/h2o2_j_initialiser_les_bornes_des_variables.cpp index 1419d54a2a..61aae129c8 100644 --- a/src/solver/hydro/daily2/h2o2_j_initialiser_les_bornes_des_variables.cpp +++ b/src/solver/hydro/daily2/h2o2_j_initialiser_les_bornes_des_variables.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" void H2O2_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES_ETENDUES& DonneesMensuelles, int NumeroDeProbleme) @@ -37,10 +31,11 @@ void H2O2_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES_ETENDUES& Donnee int NbPdt = ProblemeHydrauliqueEtendu.NbJoursDUnProbleme[NumeroDeProbleme]; - auto& CorrespondanceDesVariables - = ProblemeHydrauliqueEtendu.CorrespondanceDesVariables[NumeroDeProbleme]; - auto& ProblemeLineaireEtenduPartieVariable - = ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieVariable[NumeroDeProbleme]; + auto& CorrespondanceDesVariables = ProblemeHydrauliqueEtendu + .CorrespondanceDesVariables[NumeroDeProbleme]; + auto& ProblemeLineaireEtenduPartieVariable = ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieVariable + [NumeroDeProbleme]; auto& NumeroVar_Turbine = CorrespondanceDesVariables.NumeroVar_Turbine; diff --git a/src/solver/hydro/daily2/h2o2_j_initialiser_les_second_membre.cpp b/src/solver/hydro/daily2/h2o2_j_initialiser_les_second_membre.cpp index 982136eb45..fb4359d64c 100644 --- a/src/solver/hydro/daily2/h2o2_j_initialiser_les_second_membre.cpp +++ b/src/solver/hydro/daily2/h2o2_j_initialiser_les_second_membre.cpp @@ -1,39 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" void H2O2_J_InitialiserLeSecondMembre(DONNEES_MENSUELLES_ETENDUES& DonneesMensuelles, int NumeroDeProbleme) { auto& ProblemeHydrauliqueEtendu = DonneesMensuelles.ProblemeHydrauliqueEtendu; - auto& ProblemeLineairePartieVariable - = ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieVariable[NumeroDeProbleme]; + auto& ProblemeLineairePartieVariable = ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieVariable + [NumeroDeProbleme]; auto& SecondMembre = ProblemeLineairePartieVariable.SecondMembre; int NbPdt = ProblemeHydrauliqueEtendu.NbJoursDUnProbleme[NumeroDeProbleme]; diff --git a/src/solver/hydro/daily2/h2o2_j_instanciation.cpp b/src/solver/hydro/daily2/h2o2_j_instanciation.cpp index 89b5e22119..acc8e3bd93 100644 --- a/src/solver/hydro/daily2/h2o2_j_instanciation.cpp +++ b/src/solver/hydro/daily2/h2o2_j_instanciation.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" -#include "h2o2_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" DONNEES_MENSUELLES_ETENDUES H2O2_J_Instanciation() { @@ -66,10 +60,10 @@ DONNEES_MENSUELLES_ETENDUES H2O2_J_Instanciation() ProblemeHydrauliqueEtendu.ProblemeSpx.assign(NombreDeProblemes, nullptr); auto& CorrespondanceDesVariables = ProblemeHydrauliqueEtendu.CorrespondanceDesVariables; - auto& ProblemeLineaireEtenduPartieFixe - = ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieFixe; - auto& ProblemeLineaireEtenduPartieVariable - = ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieVariable; + auto& ProblemeLineaireEtenduPartieFixe = ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieFixe; + auto& ProblemeLineaireEtenduPartieVariable = ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieVariable; for (int i = 0; i < NombreDeProblemes; i++) { diff --git a/src/solver/hydro/daily2/h2o2_j_optim_costs.cpp b/src/solver/hydro/daily2/h2o2_j_optim_costs.cpp index 6a26a68f0a..52bb9b29ff 100644 --- a/src/solver/hydro/daily2/h2o2_j_optim_costs.cpp +++ b/src/solver/hydro/daily2/h2o2_j_optim_costs.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_optimisation.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h" #include "antares/study/fwd.h" Hydro_problem_costs::Hydro_problem_costs(const Data::Parameters& parameters) diff --git a/src/solver/hydro/daily2/h2o2_j_optimiser_un_mois.cpp b/src/solver/hydro/daily2/h2o2_j_optimiser_un_mois.cpp index c791b2d8ae..23e2fe8b33 100644 --- a/src/solver/hydro/daily2/h2o2_j_optimiser_un_mois.cpp +++ b/src/solver/hydro/daily2/h2o2_j_optimiser_un_mois.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" -#include "h2o2_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" void H2O2_J_OptimiserUnMois(DONNEES_MENSUELLES_ETENDUES& DonneesMensuelles) { diff --git a/src/solver/hydro/daily2/h2o2_j_resoudre_le_probleme_lineaire.cpp b/src/solver/hydro/daily2/h2o2_j_resoudre_le_probleme_lineaire.cpp index 75a5741d8d..a0366dce53 100644 --- a/src/solver/hydro/daily2/h2o2_j_resoudre_le_probleme_lineaire.cpp +++ b/src/solver/hydro/daily2/h2o2_j_resoudre_le_probleme_lineaire.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o2_j_donnees_mensuelles.h" -#include "h2o2_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" #ifdef _MSC_VER #define SNPRINTF sprintf_s @@ -39,10 +33,11 @@ void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES& DonneesMensu { auto& ProblemeHydrauliqueEtendu = DonneesMensuelles.ProblemeHydrauliqueEtendu; - auto& ProblemeLineaireEtenduPartieVariable - = ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieVariable[NumeroDeProbleme]; - auto& ProblemeLineaireEtenduPartieFixe - = ProblemeHydrauliqueEtendu.ProblemeLineaireEtenduPartieFixe[NumeroDeProbleme]; + auto& ProblemeLineaireEtenduPartieVariable = ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieVariable + [NumeroDeProbleme]; + auto& ProblemeLineaireEtenduPartieFixe = ProblemeHydrauliqueEtendu + .ProblemeLineaireEtenduPartieFixe[NumeroDeProbleme]; PROBLEME_SPX* ProbSpx = ProblemeHydrauliqueEtendu.ProblemeSpx[NumeroDeProbleme]; auto Probleme = std::make_unique(); @@ -80,10 +75,12 @@ void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES& DonneesMensu Probleme->NombreDeContraintes = ProblemeLineaireEtenduPartieFixe.NombreDeContraintes; Probleme->IndicesDebutDeLigne = ProblemeLineaireEtenduPartieFixe.IndicesDebutDeLigne.data(); - Probleme->NombreDeTermesDesLignes = ProblemeLineaireEtenduPartieFixe.NombreDeTermesDesLignes.data(); + Probleme->NombreDeTermesDesLignes = ProblemeLineaireEtenduPartieFixe.NombreDeTermesDesLignes + .data(); Probleme->IndicesColonnes = ProblemeLineaireEtenduPartieFixe.IndicesColonnes.data(); - Probleme->CoefficientsDeLaMatriceDesContraintes - = ProblemeLineaireEtenduPartieFixe.CoefficientsDeLaMatriceDesContraintes.data(); + Probleme->CoefficientsDeLaMatriceDesContraintes = ProblemeLineaireEtenduPartieFixe + .CoefficientsDeLaMatriceDesContraintes + .data(); Probleme->Sens = ProblemeLineaireEtenduPartieFixe.Sens.data(); Probleme->SecondMembre = ProblemeLineaireEtenduPartieVariable.SecondMembre.data(); @@ -93,7 +90,8 @@ void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES& DonneesMensu Probleme->FaireDuScaling = OUI_SPX; Probleme->StrategieAntiDegenerescence = AGRESSIF; - Probleme->PositionDeLaVariable = ProblemeLineaireEtenduPartieVariable.PositionDeLaVariable.data(); + Probleme->PositionDeLaVariable = ProblemeLineaireEtenduPartieVariable.PositionDeLaVariable + .data(); Probleme->NbVarDeBaseComplementaires = 0; Probleme->ComplementDeLaBase = ProblemeLineaireEtenduPartieVariable.ComplementDeLaBase.data(); @@ -102,15 +100,19 @@ void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES& DonneesMensu Probleme->UtiliserCoutMax = NON_SPX; Probleme->CoutMax = 0.0; - Probleme->CoutsMarginauxDesContraintes - = ProblemeLineaireEtenduPartieVariable.CoutsMarginauxDesContraintes.data(); + Probleme->CoutsMarginauxDesContraintes = ProblemeLineaireEtenduPartieVariable + .CoutsMarginauxDesContraintes.data(); Probleme->CoutsReduits = ProblemeLineaireEtenduPartieVariable.CoutsReduits.data(); #ifndef NDEBUG if (premierPassage) + { Probleme->AffichageDesTraces = NON_SPX; + } else + { Probleme->AffichageDesTraces = OUI_SPX; + } #else Probleme->AffichageDesTraces = NON_SPX; #endif @@ -120,18 +122,20 @@ void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES& DonneesMensu ProbSpx = SPX_Simplexe(Probleme.get(), ProbSpx); if (ProbSpx) + { ProblemeHydrauliqueEtendu.ProblemeSpx[NumeroDeProbleme] = ProbSpx; + } ProblemeLineaireEtenduPartieVariable.ExistenceDUneSolution = Probleme->ExistenceDUneSolution; - if (ProblemeLineaireEtenduPartieVariable.ExistenceDUneSolution != OUI_SPX - && premierPassage && ProbSpx) + if (ProblemeLineaireEtenduPartieVariable.ExistenceDUneSolution != OUI_SPX && premierPassage + && ProbSpx) { if (ProblemeLineaireEtenduPartieVariable.ExistenceDUneSolution != SPX_ERREUR_INTERNE) { SPX_LibererProbleme(ProbSpx); - ProbSpx = NULL; + ProbSpx = nullptr; premierPassage = false; goto RESOLUTION; } @@ -146,16 +150,20 @@ void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES& DonneesMensu { DonneesMensuelles.CoutSolution = 0.0; for (int Var = 0; Var < Probleme->NombreDeVariables; Var++) + { DonneesMensuelles.CoutSolution += Probleme->CoutLineaire[Var] * Probleme->X[Var]; + } DonneesMensuelles.ResultatsValides = OUI; for (int Var = 0; Var < ProblemeLineaireEtenduPartieFixe.NombreDeVariables; Var++) { double* pt = ProblemeLineaireEtenduPartieVariable - .AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + .AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; if (pt) + { *pt = ProblemeLineaireEtenduPartieVariable.X[Var]; + } } } else diff --git a/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h b/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h new file mode 100644 index 0000000000..4dfa33c7ec --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h @@ -0,0 +1,57 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __SOLVER_H2O_J_DONNEES_ANNEE__ +#define __SOLVER_H2O_J_DONNEES_ANNEE__ + +#define OUI 1 +#define NON 0 +#define EMERGENCY_SHUT_DOWN 2 + +#include "h2o_j_donnees_optimisation.h" + +/*************************************************************************************************/ +/* Structure contenant les champs a renseigner par l'appelant */ + +struct DONNEES_MENSUELLES +{ + /* En entree: seules les donnees ci-dessous doivent etre renseignees par l'appelant apres + avoir appele H2O_J_Instanciation */ + int NombreDeJoursDuMois; /* A renseigner par l'appelant */ + double TurbineDuMois; /* A renseigner par l'appelant (c'est le turbine opt du mois) */ + std::vector TurbineMax; /* A renseigner par l'appelant : 1 valeur par jour */ + std::vector TurbineMin; + std::vector TurbineCible; /* A renseigner par l'appelant : 1 valeur par jour */ + /* Les resultats */ + char + ResultatsValides; /* Vaut: + OUI si la solution est exploitable pour le reservoir + NON s'il y a eu un probleme dans la resolution + EMERGENCY_SHUT_DOWN si la resolution du probleme a donne lieu a une erreur interne + */ + std::vector Turbine; /* Resultat a recuperer par l'appelant */ + + /******************************************************************************************/ + /* Problemes internes (utilise uniquement par l'optimisation) */ + PROBLEME_HYDRAULIQUE ProblemeHydraulique; +}; + +#endif diff --git a/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_donnees_optimisation.h b/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_donnees_optimisation.h new file mode 100644 index 0000000000..e3e1b8cf9b --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_donnees_optimisation.h @@ -0,0 +1,143 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_H2O_J_STRUCTURE_INTERNE__ +#define __SOLVER_H2O_J_STRUCTURE_INTERNE__ + +#ifdef __CPLUSPLUS +extern "C" +{ +#endif + +#include "spx_definition_arguments.h" +#include "spx_fonctions.h" + +#ifdef __CPLUSPLUS +} +#endif + +#define LINFINI 1.e+80 + +#define JOURS_28 28 +#define JOURS_29 29 +#define JOURS_30 30 +#define JOURS_31 31 +#define NOMBRE_DE_TYPE_DE_MOIS 4 + +#include +#include + +/*--------------------------------------------------------------------------------------*/ +/* Matrice des contraintes: il y aura une seule instance pour tous les reservoirs */ +/* Dans ce struct il n'y a que des donnees qui sont lues et surtout pas ecrites */ +/* Ce struct est instancie une seule fois */ +struct PROBLEME_LINEAIRE_PARTIE_FIXE +{ + int NombreDeVariables; + std::vector CoutLineaire; + std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les + suivantes (voir le fichier spx_constantes_externes.h mais ne jamais + utiliser les valeurs explicites des constantes): VARIABLE_FIXE , + VARIABLE_BORNEE_DES_DEUX_COTES , + VARIABLE_BORNEE_INFERIEUREMENT , + VARIABLE_BORNEE_SUPERIEUREMENT , + VARIABLE_NON_BORNEE + */ + /* La matrice des contraintes */ + int NombreDeContraintes; + std::vector Sens; + std::vector IndicesDebutDeLigne; + std::vector NombreDeTermesDesLignes; + std::vector CoefficientsDeLaMatriceDesContraintes; + std::vector IndicesColonnes; + int NombreDeTermesAlloues; +}; + +/* Partie variable renseignee avant le lancement de l'optimisation de chaque reservoir */ +struct PROBLEME_LINEAIRE_PARTIE_VARIABLE +{ + /* Donnees variables de la matrice des contraintes */ + /* On met quand-meme les bornes dans la partie variable pour le cas ou on voudrait avoir + un jour des bornes min et max variables dans le temps et en fonction des reservoirs */ + std::vector Xmin; + std::vector Xmax; + std::vector SecondMembre; + /* Tableau de pointeur a des doubles. Ce tableau est parallele a X, il permet + de renseigner directement les structures de description du reseau avec les + resultats contenus dans X */ + std::vector AdresseOuPlacerLaValeurDesVariablesOptimisees; + /* Resultat */ + std::vector X; + /* En Entree ou en Sortie */ + int ExistenceDUneSolution; /* En sortie, vaut : + OUI_SPX s'il y a une solution, + NON_SPX s'il n'y a pas de solution + admissible SPX_ERREUR_INTERNE si probleme a l'execution + (saturation memoire par exemple), et dans ce cas il n'y a pas de + solution SPX_MATRICE_DE_BASE_SINGULIERE si on n'a pas pu + construire de matrice de base reguliere, et dans ce cas il n'y a + pas de solution + */ + + std::vector + PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + CoutsReduits; /* Vecteur a passer au Simplexe pour recuperer les couts reduits */ + std::vector CoutsMarginauxDesContraintes; /* Vecteur a passer au Simplexe pour recuperer + les couts marginaux */ +}; + +/* Les correspondances fixes des contraintes */ +struct CORRESPONDANCE_DES_CONTRAINTES +{ + int NumeroDeContrainteDEnergieMensuelle; + std::vector NumeroDeContrainteSurXi; +}; + +/* Les correspondances des variables */ +struct CORRESPONDANCE_DES_VARIABLES +{ + std::vector NumeroDeVariableTurbine; /* Turbines */ + int NumeroDeLaVariableMu; /* Variable de deversement (total sur la periode) */ + int NumeroDeLaVariableXi; /* Variable decrivant l'ecart max au turbine cible quand le turbine + est inferieur au turbine cible */ +}; + +/* Structure uniquement exploitee par l'optimisation (donc a ne pas acceder depuis l'exterieur) */ +struct PROBLEME_HYDRAULIQUE +{ + char LesCoutsOntEteInitialises; /* Vaut OUI ou NON */ + + int NombreDeProblemes; + std::vector NbJoursDUnProbleme; + + std::vector CorrespondanceDesVariables; + std::vector CorrespondanceDesContraintes; + + std::vector ProblemeLineairePartieFixe; + std::vector ProblemeLineairePartieVariable; + + std::vector + ProblemeSpx; /* Il y en a 1 par reservoir. Un probleme couvre 1 mois */ +}; + +#endif diff --git a/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_fonctions.h b/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_fonctions.h new file mode 100644 index 0000000000..0e2b98a1c9 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/daily/h2o_j_fonctions.h @@ -0,0 +1,52 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __SOLVER_H2O_J_FONCTIONS__ +#define __SOLVER_H2O_J_FONCTIONS__ + +DONNEES_MENSUELLES* H2O_J_Instanciation(void); + +void H2O_J_OptimiserUnMois(DONNEES_MENSUELLES*); +void H2O_J_Free(DONNEES_MENSUELLES*); +void H2O_J_ConstruireLesContraintes(int, + std::vector&, + int, + int, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + CORRESPONDANCE_DES_CONTRAINTES&); +void H2O_j_ConstruireLesVariables(int, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + CORRESPONDANCE_DES_VARIABLES&); +void H2O_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES*, int); +void H2O_J_InitialiserLeSecondMembre(DONNEES_MENSUELLES*, int); +void H2O_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES*, int); +void H2O_J_LisserLesSurTurbines(DONNEES_MENSUELLES*, int); +void H2O_J_AjouterBruitAuCout(DONNEES_MENSUELLES&); + +#endif /* __SOLVER_H2O_J_FONCTIONS__ */ diff --git a/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h b/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h new file mode 100644 index 0000000000..fe77e78cde --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h @@ -0,0 +1,73 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __SOLVER_H2O2_J_DONNEES_ANNEE__ +#define __SOLVER_H2O2_J_DONNEES_ANNEE__ + +#define OUI 1 +#define NON 0 +#define EMERGENCY_SHUT_DOWN 2 + +#include "antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h" + +/*************************************************************************************************/ +/* Structure contenant les champs a renseigner par l'appelant */ +/*************************************************************************************************/ + +typedef struct +{ + /* En entree: seules les donnees ci-dessous doivent etre renseignees par l'appelant apres + avoir appele H2O2_J_Instanciation */ + int NombreDeJoursDuMois; /* A renseigner par l'appelant */ + double TurbineDuMois; /* A renseigner par l'appelant (somme des turbines cibles du mois) */ + std::vector TurbineMax; /* A renseigner par l'appelant : 1 valeur par jour */ + std::vector TurbineMin; /*Minimum Hourly Hydro-Storage Generation*/ + std::vector TurbineCible; /* A renseigner par l'appelant : 1 valeur par jour */ + double reservoirCapacity; + double NiveauInitialDuMois; + std::vector niveauBas; + std::vector apports; + + /* Les resultats */ + char ResultatsValides; /* Vaut: + OUI si la solution est exploitable pour + le reservoir NON s'il y a eu un probleme dans la resolution + EMERGENCY_SHUT_DOWN si la resolution du + probleme a donne lieu a une erreur interne + */ + std::vector Turbine; /* Resultat a recuperer par l'appelant */ + std::vector niveauxFinJours; + std::vector overflows; + std::vector deviations; + std::vector violations; + double deviationMax; + double violationMax; + double waste; + + double CoutSolution; + + /******************************************************************************************/ + + /* Problemes internes (utilise uniquement par l'optimisation) */ + PROBLEME_HYDRAULIQUE_ETENDU ProblemeHydrauliqueEtendu; +} DONNEES_MENSUELLES_ETENDUES; + +#endif diff --git a/src/solver/hydro/daily2/h2o2_j_donnees_optimisation.h b/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h similarity index 75% rename from src/solver/hydro/daily2/h2o2_j_donnees_optimisation.h rename to src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h index b64abc1dd1..0d38a3bc13 100644 --- a/src/solver/hydro/daily2/h2o2_j_donnees_optimisation.h +++ b/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_donnees_optimisation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_H2O2_J_STRUCTURE_INTERNE__ #define __SOLVER_H2O2_J_STRUCTURE_INTERNE__ @@ -39,9 +33,10 @@ extern "C" } #endif -#include "../daily/h2o_j_donnees_optimisation.h" -#include #include +#include + +#include "../daily/h2o_j_donnees_optimisation.h" #define LINFINI 1.e+80 @@ -59,10 +54,9 @@ typedef struct { int NombreDeVariables; std::vector CoutLineaire; - std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les suivantes - (voir le fichier spx_constantes_externes.h - mais ne jamais utiliser les valeurs explicites des constantes): - VARIABLE_FIXE , + std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les + suivantes (voir le fichier spx_constantes_externes.h mais ne jamais + utiliser les valeurs explicites des constantes): VARIABLE_FIXE , VARIABLE_BORNEE_DES_DEUX_COTES , VARIABLE_BORNEE_INFERIEUREMENT , VARIABLE_BORNEE_SUPERIEUREMENT , @@ -104,11 +98,14 @@ typedef struct pas de solution */ - std::vector PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector CoutsReduits; /* Vecteur a passer au Simplexe pour recuperer les couts reduits */ - std::vector CoutsMarginauxDesContraintes; /* Vecteur a passer au Simplexe pour recuperer les couts - marginaux */ + std::vector + PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + CoutsReduits; /* Vecteur a passer au Simplexe pour recuperer les couts reduits */ + std::vector CoutsMarginauxDesContraintes; /* Vecteur a passer au Simplexe pour recuperer + les couts marginaux */ } PROBLEME_LINEAIRE_ETENDU_PARTIE_VARIABLE; /* Les correspondances des variables */ @@ -117,15 +114,15 @@ typedef struct std::vector NumeroVar_Turbine; /* Turbines */ std::vector NumeroVar_niveauxFinJours; // Niveaux fin jours - int NumeroVar_waste; // Waste - std::vector NumeroVar_overflow; // Deversements (ecarts journaliers entre niveaux et les 100 % du - // reservoir) - std::vector NumeroVar_deviations; // Deviations (ecarts journaliers entre turbin?s et cr?dits cibles - // brutes) - std::vector NumeroVar_violations; // Violations (ecarts journaliers entre niveaux et courbes guides sup - // et inf) - int NumeroVar_deviationMax; // Deviation max sur le mois - int NumeroVar_violationMax; // Violation max sur le mois + int NumeroVar_waste; // Waste + std::vector NumeroVar_overflow; // Deversements (ecarts journaliers entre niveaux et les + // 100 % du reservoir) + std::vector NumeroVar_deviations; // Deviations (ecarts journaliers entre turbin?s et + // cr?dits cibles brutes) + std::vector NumeroVar_violations; // Violations (ecarts journaliers entre niveaux et + // courbes guides sup et inf) + int NumeroVar_deviationMax; // Deviation max sur le mois + int NumeroVar_violationMax; // Violation max sur le mois } CORRESPONDANCE_DES_VARIABLES_PB_ETENDU; /* Structure uniquement exploitee par l'optimisation (donc a ne pas acceder depuis l'exterieur) */ @@ -141,7 +138,8 @@ typedef struct std::vector ProblemeLineaireEtenduPartieFixe; std::vector ProblemeLineaireEtenduPartieVariable; - std::vector ProblemeSpx; /* Il y en a 1 par reservoir. Un probleme couvre 1 mois */ + std::vector + ProblemeSpx; /* Il y en a 1 par reservoir. Un probleme couvre 1 mois */ } PROBLEME_HYDRAULIQUE_ETENDU; namespace Antares::Constants @@ -159,26 +157,32 @@ class Hydro_problem_costs { return end_days_levels + noiseGenerator() * Constants::noiseAmplitude; } + inline double get_overflow_cost() const { return overflow + noiseGenerator() * Constants::noiseAmplitude; } + inline double get_deviations_cost() const { return deviations + noiseGenerator() * Constants::noiseAmplitude; } + inline double get_violations_cost() const { return violations + noiseGenerator() * Constants::noiseAmplitude; } + inline double get_waste_cost() const { return waste + noiseGenerator() * Constants::noiseAmplitude; } + inline double get_deviationMax_cost() const { return deviationMax + noiseGenerator() * Constants::noiseAmplitude; } + inline double get_violationMax_cost() const { return violationMax + noiseGenerator() * Constants::noiseAmplitude; diff --git a/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_fonctions.h b/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_fonctions.h new file mode 100644 index 0000000000..5c016aa347 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/daily2/h2o2_j_fonctions.h @@ -0,0 +1,47 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __SOLVER_H2O2_J_FONCTIONS__ +#define __SOLVER_H2O2_J_FONCTIONS__ + +DONNEES_MENSUELLES_ETENDUES H2O2_J_Instanciation(); +void H2O2_J_OptimiserUnMois(DONNEES_MENSUELLES_ETENDUES&); +void H2O2_J_Free(DONNEES_MENSUELLES_ETENDUES&); +void H2O2_J_ConstruireLesContraintes(int, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + CORRESPONDANCE_DES_VARIABLES_PB_ETENDU&); +void H2O2_j_ConstruireLesVariables(int, + DONNEES_MENSUELLES_ETENDUES&, + std::vector&, + std::vector&, + std::vector&, + std::vector&, + CORRESPONDANCE_DES_VARIABLES_PB_ETENDU&); +void H2O2_J_apply_costs(const Hydro_problem_costs&, DONNEES_MENSUELLES_ETENDUES&); +void H2O2_J_InitialiserLesBornesdesVariables(DONNEES_MENSUELLES_ETENDUES&, int); +void H2O2_J_InitialiserLeSecondMembre(DONNEES_MENSUELLES_ETENDUES&, int); +void H2O2_J_ResoudreLeProblemeLineaire(DONNEES_MENSUELLES_ETENDUES&, int); + +#endif /* __SOLVER_H2O2_J_FONCTIONS__ */ diff --git a/src/solver/hydro/include/antares/solver/hydro/management/HydroInputsChecker.h b/src/solver/hydro/include/antares/solver/hydro/management/HydroInputsChecker.h new file mode 100644 index 0000000000..0308779170 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/management/HydroInputsChecker.h @@ -0,0 +1,63 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include +#include "antares/date/date.h" +#include "antares/solver/hydro/management/MinGenerationScaling.h" +#include "antares/solver/hydro/management/PrepareInflows.h" +#include "antares/study/study.h" + +namespace Antares +{ + +class HydroInputsChecker +{ +public: + explicit HydroInputsChecker(Antares::Data::Study& study); + void Execute(uint year); + +private: + Data::AreaList& areas_; + const Data::Parameters& parameters_; + const Date::Calendar& calendar_; + Data::SimulationMode simulationMode_; + const uint firstYear_; + const uint endYear_; + PrepareInflows prepareInflows_; + MinGenerationScaling minGenerationScaling_; + const Data::TimeSeries::TS& scenarioInitialHydroLevels_; + const Data::TimeSeries::TS& scenarioFinalHydroLevels_; + + //! return false if checkGenerationPowerConsistency or checkMinGeneration returns false + bool checkMonthlyMinGeneration(uint year, const Data::Area& area) const; + //! check Yearly minimum generation is lower than available inflows + bool checkYearlyMinGeneration(uint year, const Data::Area& area) const; + //! check Weekly minimum generation is lower than available inflows + bool checkWeeklyMinGeneration(uint year, const Data::Area& area) const; + //! check Hourly minimum generation is lower than available inflows + bool checkGenerationPowerConsistency(uint year) const; + //! return false if checkGenerationPowerConsistency or checkMinGeneration returns false + bool checksOnGenerationPowerBounds(uint year) const; + //! check minimum generation is lower than available inflows + bool checkMinGeneration(uint year) const; +}; + +} // namespace Antares diff --git a/src/solver/hydro/include/antares/solver/hydro/management/MinGenerationScaling.h b/src/solver/hydro/include/antares/solver/hydro/management/MinGenerationScaling.h new file mode 100644 index 0000000000..31feb6fa53 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/management/MinGenerationScaling.h @@ -0,0 +1,41 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include "antares/date/date.h" + +namespace Antares +{ + +//! Prepare minimum generation scaling for each area +class MinGenerationScaling +{ +public: + MinGenerationScaling(Data::AreaList& areas, const Date::Calendar& calendar); + void Run(uint year); + +private: + Data::AreaList& areas_; + const Date::Calendar& calendar_; +}; + +} // namespace Antares diff --git a/src/solver/hydro/include/antares/solver/hydro/management/PrepareInflows.h b/src/solver/hydro/include/antares/solver/hydro/management/PrepareInflows.h new file mode 100644 index 0000000000..79b7eae0a5 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/management/PrepareInflows.h @@ -0,0 +1,43 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include +#include "antares/date/date.h" + +namespace Antares +{ + +//! Prepare inflows scaling for each area +class PrepareInflows +{ +public: + PrepareInflows(Data::AreaList& areas, const Date::Calendar& calendar); + void Run(uint year); + +private: + void LoadInflows(uint year); + //! prepare data for Final reservoir level + void ChangeInflowsToAccommodateFinalLevels(uint year); + Data::AreaList& areas_; + const Date::Calendar& calendar_; +}; + +} // namespace Antares diff --git a/src/solver/hydro/include/antares/solver/hydro/management/hydro-final-reservoir-level-functions.h b/src/solver/hydro/include/antares/solver/hydro/management/hydro-final-reservoir-level-functions.h new file mode 100644 index 0000000000..9ded556947 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/management/hydro-final-reservoir-level-functions.h @@ -0,0 +1,41 @@ +/* +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ +#ifndef __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ +#define __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ + +#include "antares/study/study.h" + +namespace Antares::Solver +{ +void CheckFinalReservoirLevelsConfiguration(Data::AreaList& areas, + const Data::Parameters& parameters, + const Data::TimeSeries::TS& scenarioInitialHydroLevels, + const Data::TimeSeries::TS& scenarioFinalHydroLevels, + uint year); +} // namespace Antares::Solver + +#endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ diff --git a/src/solver/hydro/include/antares/solver/hydro/management/management.h b/src/solver/hydro/include/antares/solver/hydro/management/management.h new file mode 100644 index 0000000000..8f4cf12d01 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/management/management.h @@ -0,0 +1,123 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_HYDRO_MANAGEMENT_MANAGEMENT_H__ +#define __ANTARES_SOLVER_HYDRO_MANAGEMENT_MANAGEMENT_H__ + +#include + +#include + +#include +#include +#include +#include "antares/date/date.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/writer/i_writer.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +class State; +} + +double randomReservoirLevel(double min, double avg, double max, MersenneTwister& random); +double BetaVariable(double a, double b, MersenneTwister& random); +double GammaVariable(double a, MersenneTwister& random); + +} // namespace Solver + +typedef struct +{ + std::vector HydrauliqueModulableQuotidien; /* indice par jour */ + std::vector NiveauxReservoirsDebutJours; // Niveaux (quotidiens) du reservoir de début + // de jour (en cas de gestion des reservoirs). + std::vector NiveauxReservoirsFinJours; // Niveaux (quotidiens) du reservoir de fin + // de jour (en cas de gestion des reservoirs). +} VENTILATION_HYDRO_RESULTS_BY_AREA; + +using HYDRO_VENTILATION_RESULTS = std::vector; +using HydroSpecificMap = std::unordered_map; + +class HydroManagement final +{ +public: + HydroManagement(const Data::AreaList& areas, + const Data::Parameters& params, + const Date::Calendar& calendar, + Solver::IResultWriter& resultWriter); + + //! Perform the hydro ventilation + void makeVentilation(double* randomReservoirLevel, + uint y, + Antares::Data::Area::ScratchMap& scratchmap); + + const HYDRO_VENTILATION_RESULTS& ventilationResults() + { + return ventilationResults_; + } + +private: + //! Prepare the net demand for each area + void prepareNetDemand(uint year, + Data::SimulationMode mode, + const Antares::Data::Area::ScratchMap& scratchmap, + HydroSpecificMap& hydro_specific_map); + //! Prepare the effective demand for each area + void prepareEffectiveDemand(uint year, HydroSpecificMap& hydro_specific_map) const; + //! Monthly Optimal generations + void prepareMonthlyOptimalGenerations(const double* random_reservoir_level, + uint y, + HydroSpecificMap& hydro_specific_map); + + //! Monthly target generations + // note: inflows may have two different types, if in swap mode or not + // \return The total inflow for the whole year + double prepareMonthlyTargetGenerations( + Data::Area& area, + Antares::Data::AreaDependantHydroManagementData& data, + Antares::Data::TimeDependantHydroManagementData& hydro_specific); + + void prepareDailyOptimalGenerations(uint y, + Antares::Data::Area::ScratchMap& scratchmap, + HydroSpecificMap& hydro_specific_map); + + void prepareDailyOptimalGenerations( + Data::Area& area, + uint y, + Antares::Data::Area::ScratchMap& scratchmap, + Antares::Data::TimeDependantHydroManagementData& hydro_specific); + +private: + const Data::AreaList& areas_; + const Date::Calendar& calendar_; + const Data::Parameters& parameters_; + unsigned int maxNbYearsInParallel_ = 0; + Solver::IResultWriter& resultWriter_; + + HYDRO_VENTILATION_RESULTS ventilationResults_; +}; // class HydroManagement +} // namespace Antares + +#endif // __ANTARES_SOLVER_HYDRO_MANAGEMENT_MANAGEMENT_H__ diff --git a/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h b/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h new file mode 100644 index 0000000000..5a984a7978 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h @@ -0,0 +1,66 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#ifndef __SOLVER_H2O_M_DONNEES_ANNEE__ +#define __SOLVER_H2O_M_DONNEES_ANNEE__ + +#define OUI 1 +#define NON 0 +#define EMERGENCY_SHUT_DOWN 2 + +#include "h2o_m_donnees_optimisation.h" + +/*************************************************************************************************/ +/* Structure contenant les champs a renseigner par l'appelant */ + +typedef struct +{ + /* En entree: seules les donnees ci-dessous doivent etre renseignees par l'appelant apres + avoir appele " H2O_M_Instanciation " */ + /* Commence a 0 pour le 1er janvier et se termine a 11 pour le 1er decembre */ + double CoutDepassementVolume; /* A renseigner par l'appelant : 1 valeur */ + double CoutViolMaxDuVolumeMin; // A renseigner par l'appelant : 1 valeur + double VolumeInitial; /* A renseigner par l'appelant : 1 valeur */ + std::vector TurbineMax; /* A renseigner par l'appelant : 1 valeur par mois */ + std::vector TurbineMin; + std::vector TurbineCible; /* A renseigner par l'appelant : 1 valeur par mois */ + std::vector Apport; /* A renseigner par l'appelant : 1 valeur par mois */ + /* Pour decrire la bande de volumes permise */ + std::vector VolumeMin; /* A renseigner par l'appelant : 1 valeur par mois */ + std::vector VolumeMax; /* A renseigner par l'appelant : 1 valeur par mois */ + + /* Les resultats */ + char + ResultatsValides; /* Vaut: + OUI si la solution est exploitable pour le reservoir + NON s'il y a eu un probleme dans la resolution + EMERGENCY_SHUT_DOWN si la resolution du probleme a donne lieu a une erreur interne + */ + std::vector Turbine; /* Resultat a recuperer par l'appelant */ + std::vector Volume; /* Resultat a recuperer par l'appelant */ + + /******************************************************************************************/ + /* Problemes internes (utilise uniquement par l'optimisation) */ + PROBLEME_HYDRAULIQUE ProblemeHydraulique; + int NombreDePasDeTemps; /* 12 */ +} DONNEES_ANNUELLES; + +#endif diff --git a/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_donnees_optimisation.h b/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_donnees_optimisation.h new file mode 100644 index 0000000000..c3117ad3cd --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_donnees_optimisation.h @@ -0,0 +1,136 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_H2O_M_STRUCTURE_INTERNE__ +#define __SOLVER_H2O_M_STRUCTURE_INTERNE__ + +#ifdef __CPLUSPLUS +extern "C" +{ +#endif + +#include "spx_definition_arguments.h" +#include "spx_fonctions.h" + +#ifdef __CPLUSPLUS +} +#endif + +#include + +#define LINFINI 1.e+80 + +/*--------------------------------------------------------------------------------------*/ +/* Matrice des contraintes: il y aura une seule instance pour tous les reservoirs */ +/* Dans ce struct il n'y a que des donnees qui sont lues et surtout pas ecrites */ +/* Ce struct est instancie une seule fois */ +typedef struct +{ + int NombreDeVariables; + std::vector CoutLineaire; + std::vector CoutLineaireBruite; /* Ajout de bruit pour forcer l'unicité des solutions */ + std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les + suivantes (voir le fichier spx_constantes_externes.h mais ne jamais + utiliser les valeurs explicites des constantes): VARIABLE_FIXE , + VARIABLE_BORNEE_DES_DEUX_COTES , + VARIABLE_BORNEE_INFERIEUREMENT , + VARIABLE_BORNEE_SUPERIEUREMENT , + VARIABLE_NON_BORNEE + */ + /* La matrice des contraintes */ + int NombreDeContraintes; + std::vector Sens; + std::vector IndicesDebutDeLigne; + std::vector NombreDeTermesDesLignes; + std::vector CoefficientsDeLaMatriceDesContraintes; + std::vector IndicesColonnes; + int NombreDeTermesAlloues; +} PROBLEME_LINEAIRE_PARTIE_FIXE; + +/* Partie variable renseignee avant le lancement de l'optimisation de chaque reservoir */ +typedef struct +{ + /* Donnees variables de la matrice des contraintes */ + /* On met quand-meme les bornes dans la partie variable pour le cas ou on voudrait avoir + un jour des bornes min et max variables dans le temps et en fonction des reservoirs */ + std::vector Xmin; + std::vector Xmax; + std::vector SecondMembre; + /* Tableau de pointeur a des doubles. Ce tableau est parallele a X, il permet + de renseigner directement les structures de description du reseau avec les + resultats contenus dans X */ + std::vector AdresseOuPlacerLaValeurDesVariablesOptimisees; + /* Resultat */ + std::vector X; + /* En Entree ou en Sortie */ + int ExistenceDUneSolution; /* En sortie, vaut : + OUI_SPX s'il y a une solution, + NON_SPX s'il n'y a pas de solution + admissible SPX_ERREUR_INTERNE si probleme a l'execution + (saturation memoire par exemple), et dans ce cas il n'y a pas de + solution SPX_MATRICE_DE_BASE_SINGULIERE si on n'a pas pu + construire de matrice de base reguliere, et dans ce cas il n'y a + pas de solution + */ + + std::vector + PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + CoutsReduits; /* Vecteur a passer au Simplexe pour recuperer les couts reduits */ + std::vector CoutsMarginauxDesContraintes; /* Vecteur a passer au Simplexe pour recuperer + les couts marginaux */ +} PROBLEME_LINEAIRE_PARTIE_VARIABLE; + +/* Les correspondances des variables */ +typedef struct +{ + std::vector NumeroDeVariableVolume; /* Volumes */ + std::vector NumeroDeVariableTurbine; /* Turbines */ + std::vector NumeroDeVariableDepassementVolumeMax; /* Depassement du volume max */ + std::vector NumeroDeVariableDepassementVolumeMin; /* Depassement du volume min */ + int NumeroDeLaVariableViolMaxVolumeMin; // Depassement max du volume min + std::vector + NumeroDeVariableDEcartPositifAuTurbineCible; /* Ecart positif au volume cible */ + std::vector + NumeroDeVariableDEcartNegatifAuTurbineCible; /* Ecart negatif au volume cible */ + int NumeroDeLaVariableXi; /* Variable decrivant l'ecart max au turbine cible */ +} CORRESPONDANCE_DES_VARIABLES; + +/* Structure uniquement exploitee par l'optimisation (donc a ne pas acceder depuis l'exterieur) */ +typedef struct +{ + int NombreDeReservoirs; + char LesCoutsOntEteInitialises; /* Vaut OUI ou NON */ + + CORRESPONDANCE_DES_VARIABLES CorrespondanceDesVariables; + + PROBLEME_LINEAIRE_PARTIE_FIXE ProblemeLineairePartieFixe; + PROBLEME_LINEAIRE_PARTIE_VARIABLE ProblemeLineairePartieVariable; + + std::vector ProblemeSpx; /* Il y en a 1 par reservoir */ + + double CoutDeLaSolution; + double CoutDeLaSolutionBruite; + +} PROBLEME_HYDRAULIQUE; + +#endif diff --git a/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_fonctions.h b/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_fonctions.h new file mode 100644 index 0000000000..15a20d72b3 --- /dev/null +++ b/src/solver/hydro/include/antares/solver/hydro/monthly/h2o_m_fonctions.h @@ -0,0 +1,35 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_H2O_M_FONCTIONS__ +#define __SOLVER_H2O_M_FONCTIONS__ + +DONNEES_ANNUELLES H2O_M_Instanciation(int); +void H2O_M_OptimiserUneAnnee(DONNEES_ANNUELLES&, int); +void H2O_M_Free(DONNEES_ANNUELLES&); + +void H2O_M_ConstruireLesContraintes(DONNEES_ANNUELLES&); +void H2O_M_ConstruireLesVariables(DONNEES_ANNUELLES&); +void H2O_M_InitialiserBornesEtCoutsDesVariables(DONNEES_ANNUELLES&); +void H2O_M_InitialiserLeSecondMembre(DONNEES_ANNUELLES&); +void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES&, int); +void H2O_M_AjouterBruitAuCout(DONNEES_ANNUELLES&); + +#endif /* __SOLVER_H2O_M_FONCTIONS__ */ diff --git a/src/solver/hydro/management.h b/src/solver/hydro/management.h deleted file mode 100644 index ce7334e8c5..0000000000 --- a/src/solver/hydro/management.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_HYDRO_MANAGEMENT_H__ -#define __ANTARES_SOLVER_HYDRO_MANAGEMENT_H__ - -#include "management/management.h" - -#endif // __ANTARES_SOLVER_HYDRO_MANAGEMENT_H__ diff --git a/src/solver/hydro/management/HydroInputsChecker.cpp b/src/solver/hydro/management/HydroInputsChecker.cpp new file mode 100644 index 0000000000..c249cdabe3 --- /dev/null +++ b/src/solver/hydro/management/HydroInputsChecker.cpp @@ -0,0 +1,208 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/hydro/management/HydroInputsChecker.h" + +#include + +#include +#include "antares/antares/fatal-error.h" +#include "antares/solver/hydro/management/hydro-final-reservoir-level-functions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" +#include "antares/solver/simulation/common-eco-adq.h" + +namespace Antares +{ + +HydroInputsChecker::HydroInputsChecker(Antares::Data::Study& study): + areas_(study.areas), + parameters_(study.parameters), + calendar_(study.calendar), + simulationMode_(study.runtime->mode), + firstYear_(0), + endYear_(1 + study.runtime->rangeLimits.year[Data::rangeEnd]), + prepareInflows_(study.areas, study.calendar), + minGenerationScaling_(study.areas, study.calendar), + scenarioInitialHydroLevels_(study.scenarioInitialHydroLevels), + scenarioFinalHydroLevels_(study.scenarioFinalHydroLevels) +{ +} + +void HydroInputsChecker::Execute(uint year) +{ + prepareInflows_.Run(year); + minGenerationScaling_.Run(year); + + if (!checksOnGenerationPowerBounds(year)) + { + throw FatalError("hydro inputs checks: invalid minimum generation"); + } + if (parameters_.useCustomScenario) + { + CheckFinalReservoirLevelsConfiguration(areas_, + parameters_, + scenarioInitialHydroLevels_, + scenarioFinalHydroLevels_, + year); + } +} + +bool HydroInputsChecker::checksOnGenerationPowerBounds(uint year) const +{ + return checkMinGeneration(year) && checkGenerationPowerConsistency(year); +} + +bool HydroInputsChecker::checkMinGeneration(uint year) const +{ + bool ret = true; + areas_.each( + [this, &ret, &year](const Data::Area& area) + { + bool useHeuristicTarget = area.hydro.useHeuristicTarget; + bool followLoadModulations = area.hydro.followLoadModulations; + bool reservoirManagement = area.hydro.reservoirManagement; + + if (!useHeuristicTarget) + { + return; + } + + if (!followLoadModulations) + { + ret = checkWeeklyMinGeneration(year, area) && ret; + return; + } + + if (reservoirManagement) + { + ret = checkYearlyMinGeneration(year, area) && ret; + } + else + { + ret = checkMonthlyMinGeneration(year, area) && ret; + } + }); + return ret; +} + +bool HydroInputsChecker::checkWeeklyMinGeneration(uint year, const Data::Area& area) const +{ + const auto& srcinflows = area.hydro.series->storage.getColumn(year); + const auto& srcmingen = area.hydro.series->mingen.getColumn(year); + // Weekly minimum generation <= Weekly inflows for each week + for (uint week = 0; week < calendar_.maxWeeksInYear - 1; ++week) + { + double totalWeekMingen = 0.0; + double totalWeekInflows = 0.0; + for (uint hour = calendar_.weeks[week].hours.first; + hour < calendar_.weeks[week].hours.end && hour < HOURS_PER_YEAR; + ++hour) + { + totalWeekMingen += srcmingen[hour]; + } + + for (uint day = calendar_.weeks[week].daysYear.first; + day < calendar_.weeks[week].daysYear.end; + ++day) + { + totalWeekInflows += srcinflows[day]; + } + if (totalWeekMingen > totalWeekInflows) + { + logs.error() << "In Area " << area.name << " the minimum generation of " + << totalWeekMingen << " MW in week " << week + 1 << " of TS-" + << area.hydro.series->mingen.getSeriesIndex(year) + 1 + << " is incompatible with the inflows of " << totalWeekInflows << " MW."; + return false; + } + } + return true; +} + +bool HydroInputsChecker::checkYearlyMinGeneration(uint year, const Data::Area& area) const +{ + const auto& data = area.hydro.managementData.at(year); + if (data.totalYearMingen > data.totalYearInflows) + { + // Yearly minimum generation <= Yearly inflows + logs.error() << "In Area " << area.name << " the minimum generation of " + << data.totalYearMingen << " MW of TS-" + << area.hydro.series->mingen.getSeriesIndex(year) + 1 + << " is incompatible with the inflows of " << data.totalYearInflows << " MW."; + return false; + } + return true; +} + +bool HydroInputsChecker::checkMonthlyMinGeneration(uint year, const Data::Area& area) const +{ + const auto& data = area.hydro.managementData.at(year); + for (uint month = 0; month != 12; ++month) + { + uint realmonth = calendar_.months[month].realmonth; + // Monthly minimum generation <= Monthly inflows for each month + if (data.totalMonthMingen[realmonth] > data.totalMonthInflows[realmonth]) + { + logs.error() << "In Area " << area.name << " the minimum generation of " + << data.totalMonthMingen[realmonth] << " MW in month " << month + 1 + << " of TS-" << area.hydro.series->mingen.getSeriesIndex(year) + 1 + << " is incompatible with the inflows of " + << data.totalMonthInflows[realmonth] << " MW."; + return false; + } + } + return true; +} + +bool HydroInputsChecker::checkGenerationPowerConsistency(uint year) const +{ + bool ret = true; + + areas_.each( + [&ret, &year](const Data::Area& area) + { + const auto& srcmingen = area.hydro.series->mingen.getColumn(year); + const auto& srcmaxgen = area.hydro.series->maxHourlyGenPower.getColumn(year); + + const uint tsIndexMin = area.hydro.series->mingen.getSeriesIndex(year); + const uint tsIndexMax = area.hydro.series->maxHourlyGenPower.getSeriesIndex(year); + + for (uint h = 0; h < HOURS_PER_YEAR; ++h) + { + const auto& min = srcmingen[h]; + const auto& max = srcmaxgen[h]; + + if (max < min) + { + logs.error() << "In area: " << area.name << " [hourly] minimum generation of " + << min << " MW in timestep " << h + 1 << " of TS-" << tsIndexMin + 1 + << " is incompatible with the maximum generation of " << max + << " MW in timestep " << h + 1 << " of TS-" << tsIndexMax + 1 + << " MW."; + ret = false; + return; + } + } + }); + + return ret; +} +} // namespace Antares diff --git a/src/solver/hydro/management/MinGenerationScaling.cpp b/src/solver/hydro/management/MinGenerationScaling.cpp new file mode 100644 index 0000000000..08c9bf87d1 --- /dev/null +++ b/src/solver/hydro/management/MinGenerationScaling.cpp @@ -0,0 +1,92 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/hydro/management/MinGenerationScaling.h" + +#include + +namespace Antares +{ +MinGenerationScaling::MinGenerationScaling(Data::AreaList& areas, const Date::Calendar& calendar): + areas_(areas), + calendar_(calendar) +{ +} + +void MinGenerationScaling::Run(uint year) +{ + areas_.each( + // un-const because now data is a member of area [&](const Data::Area& area) + [this, &year](Data::Area& area) + { + const auto& srcmingen = area.hydro.series->mingen.getColumn(year); + + auto& data = area.hydro.managementData[year]; + double totalYearMingen = 0.0; + + for (uint month = 0; month != 12; ++month) + { + uint realmonth = calendar_.months[month].realmonth; + uint firstDayOfMonth = calendar_.months[month].daysYear.first; + uint firstDayOfNextMonth = calendar_.months[month].daysYear.end; + + double totalMonthMingen = std::accumulate(srcmingen + firstDayOfMonth * 24, + srcmingen + firstDayOfNextMonth * 24, + 0.); + + data.totalMonthMingen[realmonth] = totalMonthMingen; + totalYearMingen += totalMonthMingen; + + if (!(area.hydro.reservoirCapacity < 1e-4)) + { + if (area.hydro.reservoirManagement) + { + // Set monthly mingen, used later for h2o_m + data.mingens[realmonth] = totalMonthMingen / (area.hydro.reservoirCapacity); + assert(!std::isnan(data.mingens[month]) && "nan value detect in mingen"); + } + else + { + data.mingens[realmonth] = totalMonthMingen; + } + } + else + { + data.mingens[realmonth] = totalMonthMingen; + } + + // Set daily mingen, used later for h2o_d + uint simulationMonth = calendar_.mapping.months[realmonth]; + auto daysPerMonth = calendar_.months[simulationMonth].days; + uint firstDay = calendar_.months[simulationMonth].daysYear.first; + uint endDay = firstDay + daysPerMonth; + + for (uint day = firstDay; day != endDay; ++day) + { + data.dailyMinGen[day] = std::accumulate(srcmingen + day * 24, + srcmingen + day * 24 + 24, + 0.); + } + } + data.totalYearMingen = totalYearMingen; + }); +} +} // namespace Antares diff --git a/src/solver/hydro/management/PrepareInflows.cpp b/src/solver/hydro/management/PrepareInflows.cpp new file mode 100644 index 0000000000..01eb38efaf --- /dev/null +++ b/src/solver/hydro/management/PrepareInflows.cpp @@ -0,0 +1,93 @@ + +#include "antares/solver/hydro/management/PrepareInflows.h" + +namespace Antares +{ + +PrepareInflows::PrepareInflows(Data::AreaList& areas, const Date::Calendar& calendar): + areas_(areas), + calendar_(calendar) +{ +} + +void PrepareInflows::Run(uint year) +{ + LoadInflows(year); + ChangeInflowsToAccommodateFinalLevels(year); +} + +void PrepareInflows::LoadInflows(uint year) +{ + areas_.each( + [this, year](Data::Area& area) + { + const auto& srcinflows = area.hydro.series->storage.getColumn(year); + + auto& data = area.hydro.managementData[year]; + double totalYearInflows = 0.0; + + for (uint month = 0; month != 12; ++month) + { + uint realmonth = calendar_.months[month].realmonth; + + double totalMonthInflows = 0.0; + + uint firstDayOfMonth = calendar_.months[month].daysYear.first; + + uint firstDayOfNextMonth = calendar_.months[month].daysYear.end; + + for (uint d = firstDayOfMonth; d != firstDayOfNextMonth; ++d) + { + totalMonthInflows += srcinflows[d]; + } + + data.totalMonthInflows[realmonth] = totalMonthInflows; + totalYearInflows += totalMonthInflows; + + if (not(area.hydro.reservoirCapacity < 1e-4)) + { + if (area.hydro.reservoirManagement) + { + data.inflows[realmonth] = totalMonthInflows / (area.hydro.reservoirCapacity); + assert(!std::isnan(data.inflows[month]) && "nan value detect in inflows"); + } + else + { + data.inflows[realmonth] = totalMonthInflows; + } + } + else + { + data.inflows[realmonth] = totalMonthInflows; + } + } + data.totalYearInflows = totalYearInflows; + }); +} + +void PrepareInflows::ChangeInflowsToAccommodateFinalLevels(uint year) +{ + areas_.each( + [&year](Data::Area& area) + { + auto& data = area.hydro.managementData[year]; + + if (!area.hydro.deltaBetweenFinalAndInitialLevels[year].has_value()) + { + return; + } + + // Must be done before prepareMonthlyTargetGenerations + double delta = area.hydro.deltaBetweenFinalAndInitialLevels[year].value(); + if (delta < 0) + { + data.inflows[0] -= delta; + } + else if (delta > 0) + { + data.inflows[11] -= delta; + } + }); +} + +} // namespace Antares diff --git a/src/solver/hydro/management/daily.cpp b/src/solver/hydro/management/daily.cpp index e2648e37b7..254ab2b1b2 100644 --- a/src/solver/hydro/management/daily.cpp +++ b/src/solver/hydro/management/daily.cpp @@ -1,48 +1,45 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include +#include +#include +#include +#include + #include -#include -#include -#include #include -#include "management.h" -#include +#include + +#include +#include +#include +#include #include -#include "../daily/h2o_j_donnees_mensuelles.h" -#include "../daily/h2o_j_fonctions.h" -#include "../daily2/h2o2_j_donnees_mensuelles.h" -#include "../daily2/h2o2_j_fonctions.h" -#include "../../simulation/sim_extern_variables_globales.h" -#include -#include -#include -#include -#include +#include "antares/solver/hydro/daily/h2o_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily/h2o_j_fonctions.h" +#include "antares/solver/hydro/daily2/h2o2_j_donnees_mensuelles.h" +#include "antares/solver/hydro/daily2/h2o2_j_fonctions.h" +#include "antares/solver/hydro/management/management.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" using namespace Yuni; @@ -53,20 +50,18 @@ namespace FatalError fatalError(const std::string& areaName, int year) { std::ostringstream msg; - msg << "Year : " << year + 1 << " - hydro: " << areaName - << " [daily] fatal error"; + msg << "Year : " << year + 1 << " - hydro: " << areaName << " [daily] fatal error"; return FatalError(msg.str()); } FatalError solutionNotFound(const std::string& areaName, int year) { std::ostringstream msg; - msg << "Year : " << year + 1 << " - hydro: " << areaName - << " [daily] no solution found"; + msg << "Year : " << year + 1 << " - hydro: " << areaName << " [daily] no solution found"; return FatalError(msg.str()); } -} +} // namespace namespace Antares { @@ -74,6 +69,7 @@ enum { maxOPP = 32 }; + enum { maxDailyTargetGen = 32 @@ -81,7 +77,6 @@ enum struct DebugData { - using InflowsType = Matrix::ColumnType; using MaxPowerType = Matrix::ColumnType; using ReservoirLevelType = Matrix::ColumnType; @@ -91,40 +86,44 @@ struct DebugData std::array OVF{0}; std::array DEV{0}; std::array VIO{0}; - std::array deviationMax{0}; - std::array violationMax{0}; - std::array WASTE{0}; - std::array CoutTotal{0}; - std::array previousMonthWaste{0}; + std::array deviationMax{0}; + std::array violationMax{0}; + std::array WASTE{0}; + std::array CoutTotal{0}; + std::array previousMonthWaste{0}; Solver::IResultWriter& pWriter; - const TmpDataByArea& data; + const Antares::Data::AreaDependantHydroManagementData& data; const VENTILATION_HYDRO_RESULTS_BY_AREA& ventilationResults; - const InflowsType& srcinflows; + const double* srcinflows; const MaxPowerType& maxP; const MaxPowerType& maxE; const double* dailyTargetGen; const ReservoirLevelType& lowLevel; const double reservoirCapacity; + const Antares::Data::TimeDependantHydroManagementData& hydro_specific; + DebugData(Solver::IResultWriter& writer, - const TmpDataByArea& data, + const Antares::Data::AreaDependantHydroManagementData& data, const VENTILATION_HYDRO_RESULTS_BY_AREA& ventilationResults, - const InflowsType& srcinflows, + const double* srcinflows, const MaxPowerType& maxP, const MaxPowerType& maxE, const double* dailyTargetGen, const ReservoirLevelType& lowLevel, - double reservoirCapacity) : - pWriter(writer), - data(data), - ventilationResults(ventilationResults), - srcinflows(srcinflows), - maxP(maxP), - maxE(maxE), - dailyTargetGen(dailyTargetGen), - lowLevel(lowLevel), - reservoirCapacity(reservoirCapacity) + double reservoirCapacity, + const Antares::Data::TimeDependantHydroManagementData& hydro_specific): + pWriter(writer), + data(data), + ventilationResults(ventilationResults), + srcinflows(srcinflows), + maxP(maxP), + maxE(maxE), + dailyTargetGen(dailyTargetGen), + lowLevel(lowLevel), + reservoirCapacity(reservoirCapacity), + hydro_specific(hydro_specific) { OVF.fill(0); DEV.fill(0); @@ -146,7 +145,8 @@ struct DebugData { double value = ventilationResults.HydrauliqueModulableQuotidien[day]; buffer << day << '\t' << value << '\t' << OPP[day] << '\t' << DailyTargetGen[day] - << '\t' << data.DLE[day] << '\t' << data.DLN[day]; + << '\t' << hydro_specific.daily[day].DLE << '\t' + << hydro_specific.daily[day].DLN; buffer << '\n'; } auto buffer_str = buffer.str(); @@ -162,10 +162,10 @@ struct DebugData path << "debug" << SEP << "solver" << SEP << (1 + y) << SEP << "daily." << areaName.c_str() << ".txt"; - buffer << "\tNiveau init : " << data.MOL[initReservoirLvlMonth] << "\n"; - for (uint month = 0; month != 12; ++month) + buffer << "\tNiveau init : " << hydro_specific.monthly[initReservoirLvlMonth].MOL << "\n"; + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { - uint realmonth = (initReservoirLvlMonth + month) % 12; + uint realmonth = (initReservoirLvlMonth + month) % MONTHS_PER_YEAR; uint simulationMonth = calendar.mapping.months[realmonth]; auto daysPerMonth = calendar.months[simulationMonth].days; @@ -188,7 +188,8 @@ struct DebugData uint dayMonth = 1; for (uint day = firstDay; day != endDay; ++day) { - double turbines = ventilationResults.HydrauliqueModulableQuotidien[day] / reservoirCapacity; + double turbines = ventilationResults.HydrauliqueModulableQuotidien[day] + / reservoirCapacity; double niveauDeb = ventilationResults.NiveauxReservoirsDebutJours[day]; double niveauFin = ventilationResults.NiveauxReservoirsFinJours[day]; double apports = srcinflows[day] / reservoirCapacity; @@ -206,9 +207,9 @@ struct DebugData buffer << '\t' << deviationMax[realmonth] * 100 << '\t' << '\t' << violationMax[realmonth] * 100 << '\t' << '\t' << WASTE[realmonth] * 100 << '\t' << CoutTotal[realmonth] << '\t' - << (data.MOG[realmonth] / reservoirCapacity) * 100 << '\t' << '\t' - << '\t' << '\t' << '\t' - << (data.MOG[realmonth] / reservoirCapacity + << (hydro_specific.monthly[realmonth].MOG / reservoirCapacity) * 100 + << '\t' << '\t' << '\t' << '\t' << '\t' + << (hydro_specific.monthly[realmonth].MOG / reservoirCapacity + previousMonthWaste[realmonth]) * 100; } @@ -222,22 +223,21 @@ struct DebugData } }; -inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::State& state, - Data::Area& area, - uint y, - uint numSpace) +inline void HydroManagement::prepareDailyOptimalGenerations( + Data::Area& area, + uint y, + Antares::Data::Area::ScratchMap& scratchmap, + Antares::Data::TimeDependantHydroManagementData& hydro_specific) { - uint z = area.index; - assert(z < areas_.size()); + const auto srcinflows = area.hydro.series->storage.getColumn(y); - auto& inflowsmatrix = area.hydro.series->storage; + auto& data = area.hydro.managementData[y]; - auto tsIndex = area.hydro.series->getIndex(y); - auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; + auto& scratchpad = scratchmap.at(&area); - auto& data = tmpDataByArea_[numSpace][z]; + auto& meanMaxDailyGenPower = scratchpad.meanMaxDailyGenPower; - auto& scratchpad = area.scratchpad[numSpace]; + const uint tsIndex = meanMaxDailyGenPower.getSeriesIndex(y); int initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; @@ -249,12 +249,12 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St uint dayYear = 0; - auto const& maxPower = area.hydro.maxPower; + const auto& dailyNbHoursAtGenPmax = area.hydro.dailyNbHoursAtGenPmax; - auto const& maxP = maxPower[Data::PartHydro::genMaxP]; - auto const& maxE = maxPower[Data::PartHydro::genMaxE]; + const auto& maxP = meanMaxDailyGenPower[tsIndex]; + const auto& maxE = dailyNbHoursAtGenPmax[0]; - auto& ventilationResults = ventilationResults_[numSpace][z]; + auto& ventilationResults = ventilationResults_[area.index]; std::shared_ptr debugData(nullptr); @@ -268,25 +268,27 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St maxE, dailyTargetGen, lowLevel, - reservoirCapacity); + reservoirCapacity, + hydro_specific); } - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { auto daysPerMonth = calendar_.months[month].days; assert(daysPerMonth <= maxOPP); assert(daysPerMonth <= maxDailyTargetGen); - assert(daysPerMonth + dayYear - 1 < maxPower.height); + assert(daysPerMonth + dayYear - 1 < meanMaxDailyGenPower.timeSeries.height); for (uint day = 0; day != daysPerMonth; ++day) { auto dYear = day + dayYear; assert(day < 32); assert(dYear < 366); - scratchpad.optimalMaxPower[dYear] = maxP[dYear]; if (debugData) + { debugData->OPP[dYear] = maxP[dYear] * maxE[dYear]; + } } dayYear += daysPerMonth; @@ -296,7 +298,7 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St || (area.hydro.useHeuristicTarget && !area.hydro.followLoadModulations)) { dayYear = 0; - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { auto daysPerMonth = calendar_.months[month].days; for (uint day = 0; day != daysPerMonth; ++day) @@ -311,7 +313,7 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St else { dayYear = 0; - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { uint realmonth = calendar_.months[month].realmonth; auto daysPerMonth = calendar_.months[month].days; @@ -322,38 +324,43 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St for (uint day = 0; day != daysPerMonth; ++day) { auto dYear = day + dayYear; - if (data.DLE[dYear] > demandMax) - demandMax = data.DLE[dYear]; + if (hydro_specific.daily[dYear].DLE > demandMax) + { + demandMax = hydro_specific.daily[dYear].DLE; + } } - if (not Math::Zero(demandMax)) + if (!Utils::isZero(demandMax)) { - assert(Math::Abs(demandMax) > 1e-12); + assert(std::abs(demandMax) > 1e-12); double coeff = 0.; for (uint day = 0; day != daysPerMonth; ++day) { auto dYear = day + dayYear; - coeff += Math::Power(data.DLE[dYear] / demandMax, - area.hydro.interDailyBreakdown); + coeff += std::pow(hydro_specific.daily[dYear].DLE / demandMax, + area.hydro.interDailyBreakdown); } - coeff = data.MOG[realmonth] / coeff; + coeff = hydro_specific.monthly[realmonth].MOG / coeff; for (uint day = 0; day != daysPerMonth; ++day) { auto dYear = day + dayYear; dailyTargetGen[dYear] = coeff - * Math::Power(data.DLE[dYear] / demandMax, - area.hydro.interDailyBreakdown); + * std::pow(hydro_specific.daily[dYear].DLE + / demandMax, + area.hydro.interDailyBreakdown); } } else { assert(daysPerMonth > 0); - double coeff = data.MOG[realmonth] / daysPerMonth; + double coeff = hydro_specific.monthly[realmonth].MOG / daysPerMonth; for (uint day = 0; day != daysPerMonth; ++day) + { dailyTargetGen[day + dayYear] = coeff; + } } } @@ -363,7 +370,8 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St if (debugData) { - for (uint month = 0; month != 12; ++month) + dayYear = 0; + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { auto daysPerMonth = calendar_.months[month].days; @@ -372,14 +380,15 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St auto dYear = day + dayYear; debugData->DailyTargetGen[dYear] = dailyTargetGen[dYear]; } + dayYear += daysPerMonth; } } if (not area.hydro.reservoirManagement) { - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { - uint realmonth = (initReservoirLvlMonth + month) % 12; + uint realmonth = (initReservoirLvlMonth + month) % MONTHS_PER_YEAR; uint simulationMonth = calendar_.mapping.months[realmonth]; auto daysPerMonth = calendar_.months[simulationMonth].days; @@ -390,7 +399,7 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St DONNEES_MENSUELLES* problem = H2O_J_Instanciation(); H2O_J_AjouterBruitAuCout(*problem); problem->NombreDeJoursDuMois = (int)daysPerMonth; - problem->TurbineDuMois = data.MOG[realmonth]; + problem->TurbineDuMois = hydro_specific.monthly[realmonth].MOG; uint dayMonth = 0; for (uint day = firstDay; day != endDay; ++day) @@ -408,16 +417,15 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St dayMonth = 0; for (uint day = firstDay; day != endDay; ++day) { - ventilationResults.HydrauliqueModulableQuotidien[day] = problem->Turbine[dayMonth]; + ventilationResults.HydrauliqueModulableQuotidien[day] = problem + ->Turbine[dayMonth]; dayMonth++; } break; case NON: throw solutionNotFound(area.name.c_str(), y); - break; case EMERGENCY_SHUT_DOWN: throw fatalError(area.name.c_str(), y); - break; } H2O_J_Free(problem); @@ -425,8 +433,8 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St #ifndef NDEBUG for (uint day = firstDay; day != endDay; ++day) { - assert(!Math::NaN(ventilationResults.HydrauliqueModulableQuotidien[day])); - assert(!Math::Infinite(ventilationResults.HydrauliqueModulableQuotidien[day])); + assert(!std::isnan(ventilationResults.HydrauliqueModulableQuotidien[day])); + assert(!std::isinf(ventilationResults.HydrauliqueModulableQuotidien[day])); } #endif } @@ -440,14 +448,14 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St else { - double monthInitialLevel = data.MOL[initReservoirLvlMonth]; + double monthInitialLevel = hydro_specific.monthly[initReservoirLvlMonth].MOL; double wasteFromPreviousMonth = 0.; Hydro_problem_costs h2o2_optim_costs(parameters_); - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { - uint realmonth = (initReservoirLvlMonth + month) % 12; + uint realmonth = (initReservoirLvlMonth + month) % MONTHS_PER_YEAR; uint simulationMonth = calendar_.mapping.months[realmonth]; auto daysPerMonth = calendar_.months[simulationMonth].days; @@ -459,13 +467,15 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St H2O2_J_apply_costs(h2o2_optim_costs, problem); if (debugData) - debugData->previousMonthWaste[realmonth] - = wasteFromPreviousMonth / reservoirCapacity; + { + debugData->previousMonthWaste[realmonth] = wasteFromPreviousMonth + / reservoirCapacity; + } problem.NombreDeJoursDuMois = (int)daysPerMonth; - problem.TurbineDuMois - = (data.MOG[realmonth] + wasteFromPreviousMonth) / reservoirCapacity; + problem.TurbineDuMois = (hydro_specific.monthly[realmonth].MOG + wasteFromPreviousMonth) + / reservoirCapacity; problem.NiveauInitialDuMois = monthInitialLevel; problem.reservoirCapacity = reservoirCapacity; @@ -475,9 +485,9 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St problem.TurbineMax[dayMonth] = maxP[day] * maxE[day] / reservoirCapacity; problem.TurbineMin[dayMonth] = data.dailyMinGen[day] / reservoirCapacity; - problem.TurbineCible[dayMonth] - = (dailyTargetGen[day] + wasteFromPreviousMonth / daysPerMonth) - / reservoirCapacity; + problem.TurbineCible[dayMonth] = (dailyTargetGen[day] + + wasteFromPreviousMonth / daysPerMonth) + / reservoirCapacity; problem.niveauBas[dayMonth] = lowLevel[(day + 1) % 365]; problem.apports[dayMonth] = srcinflows[day] / reservoirCapacity; @@ -502,10 +512,12 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St dayMonth = 0; for (uint day = firstDay; day != endDay; ++day) { - ventilationResults.HydrauliqueModulableQuotidien[day] - = problem.Turbine[dayMonth] * reservoirCapacity; + ventilationResults.HydrauliqueModulableQuotidien[day] = problem + .Turbine[dayMonth] + * reservoirCapacity; - ventilationResults.NiveauxReservoirsFinJours[day] = problem.niveauxFinJours[dayMonth]; + ventilationResults.NiveauxReservoirsFinJours[day] = problem.niveauxFinJours + [dayMonth]; if (debugData) { @@ -519,8 +531,10 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St ventilationResults.NiveauxReservoirsDebutJours[firstDay] = monthInitialLevel; for (uint day = firstDay + 1; day != endDay; ++day) + { ventilationResults.NiveauxReservoirsDebutJours[day] = ventilationResults.NiveauxReservoirsFinJours[day - 1]; + } monthInitialLevel = problem.niveauxFinJours[dayMonth - 1]; @@ -529,19 +543,13 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St break; case NON: throw solutionNotFound(area.name.c_str(), y); - break; case EMERGENCY_SHUT_DOWN: throw fatalError(area.name.c_str(), y); - break; } H2O2_J_Free(problem); } - uint firstDaySimu = parameters_.simulationDays.first; - state.problemeHebdo->previousSimulationFinalLevel[z] - = ventilationResults.NiveauxReservoirsDebutJours[firstDaySimu] * reservoirCapacity; - if (debugData) { debugData->writeDailyDebugData(calendar_, initReservoirLvlMonth, y, area.name); @@ -549,14 +557,12 @@ inline void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::St } } -void HydroManagement::prepareDailyOptimalGenerations(Solver::Variable::State& state, - uint y, - uint numSpace) +void HydroManagement::prepareDailyOptimalGenerations(uint y, + Antares::Data::Area::ScratchMap& scratchmap, + HydroSpecificMap& hydro_specific_map) { areas_.each( - [&](Data::Area& area) { - prepareDailyOptimalGenerations(state, area, y, numSpace); - }); + [this, &scratchmap, &y, &hydro_specific_map](Data::Area& area) + { prepareDailyOptimalGenerations(area, y, scratchmap, hydro_specific_map[&area]); }); } - } // namespace Antares diff --git a/src/solver/hydro/management/hydro-final-reservoir-level-functions.cpp b/src/solver/hydro/management/hydro-final-reservoir-level-functions.cpp new file mode 100644 index 0000000000..6e9a53ce95 --- /dev/null +++ b/src/solver/hydro/management/hydro-final-reservoir-level-functions.cpp @@ -0,0 +1,73 @@ +/* +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ + +#include "antares/solver/hydro/management/hydro-final-reservoir-level-functions.h" + +#include +#include "antares/study/parts/hydro/finalLevelValidator.h" + +namespace Antares::Solver +{ + +void CheckFinalReservoirLevelsConfiguration(Data::AreaList& areas, + const Data::Parameters& parameters, + const Data::TimeSeries::TS& scenarioInitialHydroLevels, + const Data::TimeSeries::TS& scenarioFinalHydroLevels, + uint year) +{ + if (!parameters.yearsFilter.at(year)) + { + return; + } + + areas.each( + [&areas, ¶meters, &scenarioInitialHydroLevels, &scenarioFinalHydroLevels, year]( + Data::Area& area) + { + double initialLevel = scenarioInitialHydroLevels.entry[area.index][year]; + double finalLevel = scenarioFinalHydroLevels.entry[area.index][year]; + + Data::FinalLevelValidator validator(area.hydro, + area.index, + area.name, + initialLevel, + finalLevel, + year, + parameters.simulationDays.end, + parameters.firstMonthInYear); + if (!validator.check()) + { + throw FatalError("hydro final level : infeasibility"); + } + if (validator.finalLevelFineForUse()) + { + area.hydro.deltaBetweenFinalAndInitialLevels[year] = finalLevel - initialLevel; + } + }); +} // End function CheckFinalReservoirLevelsConfiguration + +} // namespace Antares::Solver diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 7328e3bbe8..0ad4d4a357 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -1,534 +1,288 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include -#include -#include "management.h" -#include "../../simulation/sim_extern_variables_globales.h" -#include +#include "antares/solver/hydro/management/management.h" + +#include #include -#include #include -using namespace Yuni; +#include + +#include +#include +#include +#include +#include "antares/solver/simulation/sim_extern_variables_globales.h" namespace Antares { -double HydroManagement::GammaVariable(double r) +namespace Solver +{ + +double randomReservoirLevel(double min, double avg, double max, MersenneTwister& random) +{ + auto equals = [](double a, double b) { return std::abs(a - b) < 1.e-6; }; + + if (equals(min, max)) + { + return avg; + } + if (equals(avg, min) || equals(avg, max)) + { + return avg; + } + + double e = (avg - min) / (max - min); + double re = 1. - e; + + assert(std::abs(1. + e) > 1e-12); + assert(std::abs(2. - e) > 1e-12); + + double v1 = (e * e) * re / (1. + e); + double v2 = e * re * re / (2. - e); + double v = std::min(v1, v2) * .5; + + assert(std::abs(v) > 1e-12); + + double a = e * (e * re / v - 1.); + double b = re * (e * re / v - 1.); + + double x = BetaVariable(a, b, random); + return x * max + (1. - x) * min; +} + +double GammaVariable(double r, MersenneTwister& random) { double x = 0.; do { double s = r - 1.; - double u = random_(); - double v = random_(); + double u = random(); + double v = random(); double w = u * (1. - u); - assert(Math::Abs(w) > 1e-12); + assert(std::abs(w) > 1e-12); assert(3. * (r - 0.25) / w > 0.); - double y = Math::SquareRootNoCheck(3. * (r - 0.25) / w) * (u - 0.5); + double y = std::sqrt(3. * (r - 0.25) / w) * (u - 0.5); x = y + s; if (v < 1e-12) + { break; + } w *= 4.; v *= w; double z = w * v * v; - assert(Math::Abs(s) > 1e-12); + assert(std::abs(s) > 1e-12); assert(z > 0.); assert(z / s > 0.); if (log(z) <= 2. * (s * log(x / s) - y)) + { break; + } } while (true); return x; } -inline double HydroManagement::BetaVariable(double a, double b) +double BetaVariable(double a, double b, MersenneTwister& random) { - double y = GammaVariable(a); - double z = GammaVariable(b); - assert(Math::Abs(y + z) > 1e-12); + double y = GammaVariable(a, random); + double z = GammaVariable(b, random); + assert(std::abs(y + z) > 1e-12); return y / (y + z); } +} // namespace Solver + HydroManagement::HydroManagement(const Data::AreaList& areas, const Data::Parameters& params, const Date::Calendar& calendar, - unsigned int maxNbYearsInParallel, - Solver::IResultWriter& resultWriter) : + Solver::IResultWriter& resultWriter): areas_(areas), calendar_(calendar), parameters_(params), - maxNbYearsInParallel_(maxNbYearsInParallel), resultWriter_(resultWriter) { - tmpDataByArea_ = new TmpDataByArea* [maxNbYearsInParallel_]; - for (uint numSpace = 0; numSpace < maxNbYearsInParallel_; numSpace++) - tmpDataByArea_[numSpace] = new TmpDataByArea[areas_.size()]; - - random_.reset(parameters_.seed[Data::seedHydroManagement]); - // Ventilation results memory allocation uint nbDaysPerYear = 365; - ventilationResults_.resize(maxNbYearsInParallel_); - for (uint numSpace = 0; numSpace < maxNbYearsInParallel_; numSpace++) + ventilationResults_.resize(areas_.size()); + for (uint areaIndex = 0; areaIndex < areas_.size(); ++areaIndex) { - ventilationResults_[numSpace].resize(areas_.size()); - for (uint areaIndex = 0; areaIndex < areas_.size(); ++areaIndex) - { - auto& area = *areas_.byIndex[areaIndex]; - size_t clusterCount = area.thermal.clusterCount(); + auto* area = areas_.byIndex[areaIndex]; + auto& ventilationResults = ventilationResults_[areaIndex]; - ventilationResults_[numSpace][areaIndex].HydrauliqueModulableQuotidien.assign(nbDaysPerYear, 0); - - if (area.hydro.reservoirManagement) - { - ventilationResults_[numSpace][areaIndex].NiveauxReservoirsDebutJours.assign(nbDaysPerYear, 0.); - ventilationResults_[numSpace][areaIndex].NiveauxReservoirsFinJours.assign(nbDaysPerYear, 0.); - } + ventilationResults.HydrauliqueModulableQuotidien.assign(nbDaysPerYear, 0); + if (area->hydro.reservoirManagement) + { + ventilationResults.NiveauxReservoirsDebutJours.assign(nbDaysPerYear, 0.); + ventilationResults.NiveauxReservoirsFinJours.assign(nbDaysPerYear, 0.); } } } -HydroManagement::~HydroManagement() +void HydroManagement::prepareNetDemand(uint year, + Data::SimulationMode mode, + const Antares::Data::Area::ScratchMap& scratchmap, + HydroSpecificMap& hydro_specific_map) { - for (uint numSpace = 0; numSpace < maxNbYearsInParallel_; numSpace++) - delete[] tmpDataByArea_[numSpace]; - delete[] tmpDataByArea_; -} - -void HydroManagement::prepareInflowsScaling(uint numSpace, uint year) -{ - areas_.each([&](Data::Area& area) + areas_.each( + [this, &year, &scratchmap, &mode, &hydro_specific_map](Data::Area& area) { - uint z = area.index; + const auto& scratchpad = scratchmap.at(&area); - auto& inflowsmatrix = area.hydro.series->storage; - assert(inflowsmatrix.width && inflowsmatrix.height); - auto tsIndex = area.hydro.series->getIndex(year); - auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; + const auto& rormatrix = area.hydro.series->ror; + const auto* ror = rormatrix.getColumn(year); - auto& data = tmpDataByArea_[numSpace][z]; - double totalYearInflows = 0.0; + auto& data = area.hydro.managementData[year]; + auto& hydro_specific = hydro_specific_map[&area]; + const double* loadSeries = area.load.series.getColumn(year); + const double* windSeries = area.wind.series.getColumn(year); + const double* solarSeries = area.solar.series.getColumn(year); - for (uint month = 0; month != 12; ++month) + for (uint hour = 0; hour != HOURS_PER_YEAR; ++hour) { - uint realmonth = calendar_.months[month].realmonth; - - double totalMonthInflows = 0.0; - - uint firstDayOfMonth = calendar_.months[month].daysYear.first; + auto dayYear = calendar_.hours[hour].dayYear; - uint firstDayOfNextMonth = calendar_.months[month].daysYear.end; + double netdemand = 0; - for (uint d = firstDayOfMonth; d != firstDayOfNextMonth; ++d) - totalMonthInflows += srcinflows[d]; - - data.totalMonthInflows[realmonth] = totalMonthInflows; - totalYearInflows += totalMonthInflows; + // Aggregated renewable production: wind & solar + if (parameters_.renewableGeneration.isAggregated()) + { + netdemand = +loadSeries[hour] - windSeries[hour] - scratchpad.miscGenSum[hour] + - solarSeries[hour] - ror[hour] + - ((mode != Data::SimulationMode::Adequacy) + ? scratchpad.mustrunSum[hour] + : scratchpad.originalMustrunSum[hour]); + } - if (not(area.hydro.reservoirCapacity < 1e-4)) + // Renewable clusters, if enabled + else if (parameters_.renewableGeneration.isClusters()) { - if (area.hydro.reservoirManagement) - { - data.inflows[realmonth] = totalMonthInflows / (area.hydro.reservoirCapacity); - assert(!Math::NaN(data.inflows[month]) && "nan value detect in inflows"); - } - else + netdemand = loadSeries[hour] - scratchpad.miscGenSum[hour] - ror[hour] + - ((mode != Data::SimulationMode::Adequacy) + ? scratchpad.mustrunSum[hour] + : scratchpad.originalMustrunSum[hour]); + + for (auto& c: area.renewable.list.each_enabled()) { - data.inflows[realmonth] = totalMonthInflows; + netdemand -= c->valueAtTimeStep(year, hour); } } - else - { - data.inflows[realmonth] = totalMonthInflows; - } + + assert(!std::isnan(netdemand) + && "hydro management: NaN detected when calculating the net demande"); + hydro_specific.daily[dayYear].DLN += netdemand; } - data.totalYearInflows = totalYearInflows; }); } -void HydroManagement::minGenerationScaling(uint numSpace, uint year) const +void HydroManagement::prepareEffectiveDemand(uint year, HydroSpecificMap& hydro_specific_map) const { - areas_.each([this, &numSpace, &year](Data::Area& area) + areas_.each( + [this, &year, &hydro_specific_map](Data::Area& area) { - uint z = area.index; + auto& data = area.hydro.managementData[year]; + auto& hydro_specific = hydro_specific_map[&area]; - auto& mingenmatrix = area.hydro.series->mingen; - auto tsIndex = area.hydro.series->getIndex(year); - auto const& srcmingen = mingenmatrix[tsIndex < mingenmatrix.width ? tsIndex : 0]; + for (uint day = 0; day != 365; ++day) + { + auto month = calendar_.days[day].month; + assert(month < 12 && "Invalid month index"); + auto realmonth = calendar_.months[month].realmonth; + + double effectiveDemand = 0; + // area.hydro.allocation is indexed by area index + area.hydro.allocation.eachNonNull( + [this, &effectiveDemand, &day, &hydro_specific_map](unsigned areaIndex, + double value) + { + const auto* area = areas_.byIndex[areaIndex]; + effectiveDemand += hydro_specific_map[area].daily[day].DLN * value; + }); - auto& data = tmpDataByArea_[numSpace][z]; - double totalYearMingen = 0.0; + assert(!std::isnan(effectiveDemand) && "nan value detected for effectiveDemand"); + hydro_specific.daily[day].DLE += effectiveDemand; + hydro_specific.monthly[realmonth].MLE += effectiveDemand; - for (uint month = 0; month != 12; ++month) - { - uint realmonth = calendar_.months[month].realmonth; - uint firstDayOfMonth = calendar_.months[month].daysYear.first; - uint firstDayOfNextMonth = calendar_.months[month].daysYear.end; + assert(not std::isnan(hydro_specific.daily[day].DLE) && "nan value detected for DLE"); + assert(not std::isnan(hydro_specific.monthly[realmonth].MLE) + && "nan value detected for DLE"); + } - double totalMonthMingen = std::accumulate( - srcmingen + firstDayOfMonth * 24, srcmingen + firstDayOfNextMonth * 24, 0.); + auto minimumYear = std::numeric_limits::infinity(); + auto dayYear = 0u; - data.totalMonthMingen[realmonth] = totalMonthMingen; - totalYearMingen += totalMonthMingen; + for (uint month = 0; month != 12; ++month) + { + auto minimumMonth = +std::numeric_limits::infinity(); + auto daysPerMonth = calendar_.months[month].days; + auto realmonth = calendar_.months[month].realmonth; - if (!(area.hydro.reservoirCapacity < 1e-4)) + for (uint d = 0; d != daysPerMonth; ++d) { - if (area.hydro.reservoirManagement) + auto dYear = d + dayYear; + if (hydro_specific.daily[dYear].DLE < minimumMonth) { - // Set monthly mingen, used later for h2o_m - data.mingens[realmonth] = totalMonthMingen / (area.hydro.reservoirCapacity); - assert(!Math::NaN(data.mingens[month]) && "nan value detect in mingen"); + minimumMonth = hydro_specific.daily[dYear].DLE; } - else + } + + if (minimumMonth < 0.) + { + for (uint d = 0; d != daysPerMonth; ++d) { - data.mingens[realmonth] = totalMonthMingen; + hydro_specific.daily[dayYear + d].DLE -= minimumMonth - 1e-4; } } - else + + if (hydro_specific.monthly[realmonth].MLE < minimumYear) { - data.mingens[realmonth] = totalMonthMingen; + minimumYear = hydro_specific.monthly[realmonth].MLE; } - // Set daily mingen, used later for h2o_d - uint simulationMonth = calendar_.mapping.months[realmonth]; - auto daysPerMonth = calendar_.months[simulationMonth].days; - uint firstDay = calendar_.months[simulationMonth].daysYear.first; - uint endDay = firstDay + daysPerMonth; + dayYear += daysPerMonth; + } - for (uint day = firstDay; day != endDay; ++day) + if (minimumYear < 0.) + { + for (uint realmonth = 0; realmonth != 12; ++realmonth) { - data.dailyMinGen[day] - = std::accumulate(srcmingen + day * 24, srcmingen + day * 24 + 24, 0.); + hydro_specific.monthly[realmonth].MLE -= minimumYear - 1e-4; } } - data.totalYearMingen = totalYearMingen; }); } -bool HydroManagement::checkMonthlyMinGeneration(uint numSpace, uint tsIndex, const Data::Area& area) const -{ - const auto& data = tmpDataByArea_[numSpace][area.index]; - for (uint month = 0; month != 12; ++month) - { - uint realmonth = calendar_.months[month].realmonth; - // Monthly minimum generation <= Monthly inflows for each month - if (data.totalMonthMingen[realmonth] > data.totalMonthInflows[realmonth]) - { - logs.error() << "In Area " << area.name << " the minimum generation of " - << data.totalMonthMingen[realmonth] << " MW in month " << month + 1 - << " of TS-" << tsIndex + 1 << " is incompatible with the inflows of " - << data.totalMonthInflows[realmonth] << " MW."; - return false; - } - } - return true; -} - -bool HydroManagement::checkYearlyMinGeneration(uint numSpace, uint tsIndex, const Data::Area& area) const -{ - const auto& data = tmpDataByArea_[numSpace][area.index]; - if (data.totalYearMingen > data.totalYearInflows) - { - // Yearly minimum generation <= Yearly inflows - logs.error() << "In Area " << area.name << " the minimum generation of " - << data.totalYearMingen << " MW of TS-" << tsIndex + 1 - << " is incompatible with the inflows of " << data.totalYearInflows << " MW."; - return false; - } - return true; -} - -bool HydroManagement::checkWeeklyMinGeneration(uint tsIndex, Data::Area& area) const -{ - auto& inflowsmatrix = area.hydro.series->storage; - auto& mingenmatrix = area.hydro.series->mingen; - auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; - auto const& srcmingen = mingenmatrix[tsIndex < mingenmatrix.width ? tsIndex : 0]; - // Weekly minimum generation <= Weekly inflows for each week - for (uint week = 0; week < calendar_.maxWeeksInYear - 1; ++week) - { - double totalWeekMingen = 0.0; - double totalWeekInflows = 0.0; - for (uint hour = calendar_.weeks[week].hours.first; - hour < calendar_.weeks[week].hours.end && hour < HOURS_PER_YEAR; - ++hour) - { - totalWeekMingen += srcmingen[hour]; - } - - for (uint day = calendar_.weeks[week].daysYear.first; - day < calendar_.weeks[week].daysYear.end; - ++day) - { - totalWeekInflows += srcinflows[day]; - } - if (totalWeekMingen > totalWeekInflows) - { - logs.error() << "In Area " << area.name << " the minimum generation of " - << totalWeekMingen << " MW in week " << week + 1 << " of TS-" - << tsIndex + 1 << " is incompatible with the inflows of " - << totalWeekInflows << " MW."; - return false; - } - } - return true; -} - -bool HydroManagement::checkHourlyMinGeneration(uint tsIndex, Data::Area& area) const -{ - // Hourly minimum generation <= hourly max generation for each hour - auto& mingenmatrix = area.hydro.series->mingen; - auto const& srcmingen = mingenmatrix[tsIndex < mingenmatrix.width ? tsIndex : 0]; - auto const& maxPower = area.hydro.maxPower; - auto const& maxP = maxPower[Data::PartHydro::genMaxP]; - - for (uint month = 0; month != 12; ++month) - { - uint realmonth = calendar_.months[month].realmonth; - uint simulationMonth = calendar_.mapping.months[realmonth]; - auto daysPerMonth = calendar_.months[simulationMonth].days; - uint firstDay = calendar_.months[simulationMonth].daysYear.first; - uint endDay = firstDay + daysPerMonth; - - for (uint day = firstDay; day != endDay; ++day) - { - for (uint h = 0; h < 24; ++h) - { - if (srcmingen[day * 24 + h] > maxP[day]) - { - logs.error() - << "In area: " << area.name << " [hourly] minimum generation of " - << srcmingen[day * 24 + h] << " MW in timestep " << day * 24 + h + 1 - << " of TS-" << tsIndex + 1 - << " is incompatible with the maximum generation of " << maxP[day] - << " MW."; - return false; - } - } - } - } - return true; -} - -bool HydroManagement::checkMinGeneration(uint numSpace, uint year) const -{ - bool ret = true; - areas_.each([this, &numSpace, &ret, &year](Data::Area& area) - { - auto tsIndex = area.hydro.series->getIndex(year); - - bool useHeuristicTarget = area.hydro.useHeuristicTarget; - bool followLoadModulations = area.hydro.followLoadModulations; - bool reservoirManagement = area.hydro.reservoirManagement; - - ret = checkHourlyMinGeneration(tsIndex, area) && ret; - - if (!useHeuristicTarget) - return; - - if (!followLoadModulations) - { - ret = checkWeeklyMinGeneration(tsIndex, area) && ret; - return; - } - - if (reservoirManagement) - ret = checkYearlyMinGeneration(numSpace, tsIndex, area) && ret; - else - ret = checkMonthlyMinGeneration(numSpace, tsIndex, area) && ret; - }); - return ret; -} - -void HydroManagement::prepareNetDemand(uint numSpace, uint year, Data::StudyMode mode) -{ - areas_.each([&](Data::Area& area) { - uint z = area.index; - - auto& scratchpad = area.scratchpad[numSpace]; - - auto& rormatrix = area.hydro.series->ror; - auto tsIndex = area.hydro.series->getIndex(year); - auto& ror = rormatrix[tsIndex < rormatrix.width ? tsIndex : 0]; - - auto& data = tmpDataByArea_[numSpace][z]; - const double* loadSeries = area.load.series->getColumn(year); - const double* windSeries = area.wind.series->getColumn(year); - const double* solarSeries = area.solar.series->getColumn(year); - - for (uint hour = 0; hour != HOURS_PER_YEAR; ++hour) - { - auto dayYear = calendar_.hours[hour].dayYear; - - double netdemand = 0; - - // Aggregated renewable production: wind & solar - if (parameters_.renewableGeneration.isAggregated()) - { - netdemand = + loadSeries[hour] - - windSeries[hour] - scratchpad.miscGenSum[hour] - - solarSeries[hour] - ror[hour] - - ((mode != Data::stdmAdequacy) ? scratchpad.mustrunSum[hour] - : scratchpad.originalMustrunSum[hour]); - } - - // Renewable clusters, if enabled - else if (parameters_.renewableGeneration.isClusters()) - { - netdemand = loadSeries[hour] - - scratchpad.miscGenSum[hour] - ror[hour] - - ((mode != Data::stdmAdequacy) ? scratchpad.mustrunSum[hour] - : scratchpad.originalMustrunSum[hour]); - - area.renewable.list.each([&](const Antares::Data::RenewableCluster& cluster) { - assert(cluster.series->timeSeries.jit == NULL && "No JIT data from the solver"); - netdemand -= cluster.valueAtTimeStep(hour, year); - }); - } - - assert(!Math::NaN(netdemand) - && "hydro management: NaN detected when calculating the net demande"); - data.DLN[dayYear] += netdemand; - } - }); -} - -void HydroManagement::prepareEffectiveDemand(uint numSpace) -{ - areas_.each([&](Data::Area& area) { - auto z = area.index; - - auto& data = tmpDataByArea_[numSpace][z]; - - for (uint day = 0; day != 365; ++day) - { - auto month = calendar_.days[day].month; - assert(month < 12 && "Invalid month index"); - auto realmonth = calendar_.months[month].realmonth; - - double effectiveDemand = 0; - area.hydro.allocation.eachNonNull([&](unsigned areaindex, double value) { - effectiveDemand += (tmpDataByArea_[numSpace][areaindex]).DLN[day] * value; - }); - - assert(!Math::NaN(effectiveDemand) && "nan value detected for effectiveDemand"); - data.DLE[day] += effectiveDemand; - data.MLE[realmonth] += effectiveDemand; - - assert(not Math::NaN(data.DLE[day]) && "nan value detected for DLE"); - assert(not Math::NaN(data.MLE[realmonth]) && "nan value detected for DLE"); - } - - auto minimumYear = std::numeric_limits::infinity(); - auto dayYear = 0u; - - for (uint month = 0; month != 12; ++month) - { - auto minimumMonth = +std::numeric_limits::infinity(); - auto daysPerMonth = calendar_.months[month].days; - auto realmonth = calendar_.months[month].realmonth; - - for (uint d = 0; d != daysPerMonth; ++d) - { - auto dYear = d + dayYear; - if (data.DLE[dYear] < minimumMonth) - minimumMonth = data.DLE[dYear]; - } - - if (minimumMonth < 0.) - { - for (uint d = 0; d != daysPerMonth; ++d) - data.DLE[dayYear + d] -= minimumMonth - 1e-4; - } - - if (data.MLE[realmonth] < minimumYear) - minimumYear = data.MLE[realmonth]; - - dayYear += daysPerMonth; - } - - if (minimumYear < 0.) - { - for (uint realmonth = 0; realmonth != 12; ++realmonth) - data.MLE[realmonth] -= minimumYear - 1e-4; - } - }); -} - -double HydroManagement::randomReservoirLevel(double min, double avg, double max) -{ - if (Math::Equals(min, max)) - return avg; - if (Math::Equals(avg, min) || Math::Equals(avg, max)) - return avg; - - double e = (avg - min) / (max - min); - double re = 1. - e; - - assert(Math::Abs(1. + e) > 1e-12); - assert(Math::Abs(2. - e) > 1e-12); - - double v1 = (e * e) * re / (1. + e); - double v2 = e * re * re / (2. - e); - double v = Math::Min(v1, v2) * .5; - - assert(Math::Abs(v) > 1e-12); - - double a = e * (e * re / v - 1.); - double b = re * (e * re / v - 1.); - - double x = BetaVariable(a, b); - return x * max + (1. - x) * min; -} - void HydroManagement::makeVentilation(double* randomReservoirLevel, - Solver::Variable::State& state, uint y, - uint numSpace) + Antares::Data::Area::ScratchMap& scratchmap) { - memset(tmpDataByArea_[numSpace], 0, sizeof(TmpDataByArea) * areas_.size()); - - prepareInflowsScaling(numSpace, y); - minGenerationScaling(numSpace, y); - if (!checkMinGeneration(numSpace, y)) - { - throw FatalError("hydro management: invalid minimum generation"); - } - - prepareNetDemand(numSpace, y, parameters_.mode); - prepareEffectiveDemand(numSpace); + HydroSpecificMap hydro_specific_map; + prepareNetDemand(y, parameters_.mode, scratchmap, hydro_specific_map); + prepareEffectiveDemand(y, hydro_specific_map); - prepareMonthlyOptimalGenerations(randomReservoirLevel, y, numSpace); - prepareDailyOptimalGenerations(state, y, numSpace); + prepareMonthlyOptimalGenerations(randomReservoirLevel, y, hydro_specific_map); + prepareDailyOptimalGenerations(y, scratchmap, hydro_specific_map); } } // namespace Antares diff --git a/src/solver/hydro/management/management.h b/src/solver/hydro/management/management.h deleted file mode 100644 index deb1f1f4d5..0000000000 --- a/src/solver/hydro/management/management.h +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_HYDRO_MANAGEMENT_MANAGEMENT_H__ -#define __ANTARES_SOLVER_HYDRO_MANAGEMENT_MANAGEMENT_H__ - -#include -#include -#include -#include "../../simulation/sim_structure_donnees.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -class State; -} -} // namespace Solver - -enum -{ - //! The maximum number of days in a year - dayYearCount = 366 -}; - -//! Temporary data -struct TmpDataByArea -{ - //! Monthly local effective demand - double MLE[12]; - //! Monthly optimal generation - double MOG[12]; - //! Monthly optimal level - double MOL[12]; - //! Monthly target generations - double MTG[12]; - //! inflows - double inflows[12]; - //! monthly minimal generation - std::array mingens; - - //! Net demand, for each day of the year, for each area - double DLN[dayYearCount]; - //! Daily local effective load - double DLE[dayYearCount]; - //! Daily optimized Generation - double DOG[dayYearCount]; - //! daily minimal generation - std::array dailyMinGen; - - // Data for minGen<->inflows preChecks - //! monthly total mingen - std::array totalMonthMingen; - //! monthly total inflows - std::array totalMonthInflows; - //! yearly total mingen - double totalYearMingen; - //! yearly total inflows - double totalYearInflows; - -}; // struct TmpDataByArea - -typedef struct -{ - std::vector HydrauliqueModulableQuotidien; /* indice par jour */ - std::vector NiveauxReservoirsDebutJours; //Niveaux (quotidiens) du reservoir de début - //de jour (en cas de gestion des reservoirs). - std::vector NiveauxReservoirsFinJours; //Niveaux (quotidiens) du reservoir de fin - //de jour (en cas de gestion des reservoirs). -} VENTILATION_HYDRO_RESULTS_BY_AREA; - -// vector of [numSpace][area] -using ALL_HYDRO_VENTILATION_RESULTS = std::vector>; - - -class HydroManagement final -{ -public: - HydroManagement(const Data::AreaList& areas, - const Data::Parameters& params, - const Date::Calendar& calendar, - unsigned int maxNbYearsInParallel, - Solver::IResultWriter& resultWriter); - - ~HydroManagement(); - - double randomReservoirLevel(double min, double avg, double max); - - //! Perform the hydro ventilation - void makeVentilation(double* randomReservoirLevel, - Solver::Variable::State& state, - uint y, - uint numSpace); - - ALL_HYDRO_VENTILATION_RESULTS& ventilationResults() { return ventilationResults_; } - -private: - //! Prepare inflows scaling for each area - void prepareInflowsScaling(uint numSpace, uint year); - //! Prepare minimum generation scaling for each area - void minGenerationScaling(uint numSpace, uint year) const; - //! check Monthly minimum generation is lower than available inflows - bool checkMonthlyMinGeneration(uint numSpace, uint tsIndex, const Data::Area& area) const; - //! check Yearly minimum generation is lower than available inflows - bool checkYearlyMinGeneration(uint numSpace, uint tsIndex, const Data::Area& area) const; - //! check Weekly minimum generation is lower than available inflows - bool checkWeeklyMinGeneration(uint tsIndex, Data::Area& area) const; - //! check Hourly minimum generation is lower than available inflows - bool checkHourlyMinGeneration(uint tsIndex, Data::Area& area) const; - //! check minimum generation is lower than available inflows - bool checkMinGeneration(uint numSpace, uint year) const; - //! Prepare the net demand for each area - void prepareNetDemand(uint numSpace, uint year, Data::StudyMode mode); - //! Prepare the effective demand for each area - void prepareEffectiveDemand(uint numSpace); - //! Monthly Optimal generations - void prepareMonthlyOptimalGenerations(double* random_reservoir_level, uint y, uint numSpace); - - //! Monthly target generations - // note: inflows may have two different types, if in swap mode or not - // \return The total inflow for the whole year - double prepareMonthlyTargetGenerations(Data::Area& area, TmpDataByArea& data); - - void prepareDailyOptimalGenerations(Solver::Variable::State& state, - uint y, - uint numSpace); - - void prepareDailyOptimalGenerations(Solver::Variable::State& state, - Data::Area& area, - uint y, - uint numSpace); - //@} - - //! \name Utilities - //@{ - //! Beta variable - double BetaVariable(double a, double b); - //! Gamma variable - double GammaVariable(double a); - //@} - -private: - TmpDataByArea** tmpDataByArea_; - const Data::AreaList& areas_; - const Date::Calendar& calendar_; - const Data::Parameters& parameters_; - MersenneTwister random_; - unsigned int maxNbYearsInParallel_ = 0; - Solver::IResultWriter& resultWriter_; - - ALL_HYDRO_VENTILATION_RESULTS ventilationResults_; -}; // class HydroManagement -} // namespace Antares - -#endif // __ANTARES_SOLVER_HYDRO_MANAGEMENT_MANAGEMENT_H__ diff --git a/src/solver/hydro/management/monthly.cpp b/src/solver/hydro/management/monthly.cpp index c526916f4e..8afcd0e26f 100644 --- a/src/solver/hydro/management/monthly.cpp +++ b/src/solver/hydro/management/monthly.cpp @@ -1,42 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include #include +#include #include -#include #include #include -#include "management.h" -#include -#include "../../simulation/sim_extern_variables_globales.h" -#include "../monthly/h2o_m_donnees_annuelles.h" -#include "../monthly/h2o_m_fonctions.h" + +#include +#include +#include +#include "antares/solver/hydro/management/management.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" using namespace Yuni; @@ -53,7 +49,7 @@ static void CheckHydroAllocationProblem(Data::Area& area, bool error = false; double X = problem.Volume[11] - problem.Turbine[11] + problem.Apport[11]; - if (not Math::Zero(X - lvi)) + if (!Utils::isZero(X - lvi)) { logs.fatal() << area.id << ": hydro management: monthly: reservoir error"; error = true; @@ -63,9 +59,9 @@ static void CheckHydroAllocationProblem(Data::Area& area, { logs.warning() << area.id << ": lvi = " << lvi; logs.warning() << area.id << ": cost = " << problem.CoutDepassementVolume; - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { - uint realmonth = (initLevelMonth + month) % 12; + uint realmonth = (initLevelMonth + month) % MONTHS_PER_YEAR; logs.warning() << "month: " << ((realmonth < 10) ? "0" : "") << realmonth << ", turb.max: " << problem.TurbineMax[realmonth] << ", turb.cible: " << problem.TurbineCible[realmonth] @@ -76,9 +72,9 @@ static void CheckHydroAllocationProblem(Data::Area& area, logs.info(); problem.Volume[initLevelMonth] = lvi; - for (uint month = 0; month != 12; ++month) + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) { - uint realmonth = (initLevelMonth + month) % 12; + uint realmonth = (initLevelMonth + month) % MONTHS_PER_YEAR; logs.warning() << "month: " << ((realmonth < 10) ? "0" : "") << realmonth << ", turbine: " << problem.Turbine[realmonth] << ", volume: " << problem.Volume[realmonth]; @@ -86,215 +82,242 @@ static void CheckHydroAllocationProblem(Data::Area& area, } } - -double HydroManagement::prepareMonthlyTargetGenerations(Data::Area& area, TmpDataByArea& data) +double HydroManagement::prepareMonthlyTargetGenerations( + Data::Area& area, + Antares::Data::AreaDependantHydroManagementData& data, + Antares::Data::TimeDependantHydroManagementData& hydro_specific) { double total = 0; - for (uint realmonth = 0; realmonth != 12; ++realmonth) + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) + { total += data.inflows[realmonth]; + } if (not area.hydro.followLoadModulations) { - for (uint realmonth = 0; realmonth != 12; ++realmonth) - data.MTG[realmonth] = data.inflows[realmonth]; + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) + { + hydro_specific.monthly[realmonth].MTG = data.inflows[realmonth]; + } return total; } double monthlyMaxDemand = -std::numeric_limits::infinity(); - for (uint realmonth = 0; realmonth != 12; ++realmonth) + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) { - if (data.MLE[realmonth] > monthlyMaxDemand) - monthlyMaxDemand = data.MLE[realmonth]; + if (hydro_specific.monthly[realmonth].MLE > monthlyMaxDemand) + { + monthlyMaxDemand = hydro_specific.monthly[realmonth].MLE; + } } - if (not Math::Zero(monthlyMaxDemand)) + if (!Utils::isZero(monthlyMaxDemand)) { double coeff = 0.; - for (uint realmonth = 0; realmonth != 12; ++realmonth) + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) { - assert(data.MLE[realmonth] / monthlyMaxDemand >= 0.); - coeff += Math::Power(data.MLE[realmonth] / monthlyMaxDemand, - area.hydro.intermonthlyBreakdown); + assert(hydro_specific.monthly[realmonth].MLE / monthlyMaxDemand >= 0.); + coeff += std::pow(hydro_specific.monthly[realmonth].MLE / monthlyMaxDemand, + area.hydro.intermonthlyBreakdown); } - if (!Math::Zero(coeff)) + if (!Utils::isZero(coeff)) + { coeff = total / coeff; + } - for (uint realmonth = 0; realmonth != 12; ++realmonth) + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) { - assert(data.MLE[realmonth] / monthlyMaxDemand >= 0.); - data.MTG[realmonth] = coeff - * Math::Power(data.MLE[realmonth] / monthlyMaxDemand, - area.hydro.intermonthlyBreakdown); + assert(hydro_specific.monthly[realmonth].MLE / monthlyMaxDemand >= 0.); + hydro_specific.monthly[realmonth].MTG = coeff + * std::pow(hydro_specific.monthly[realmonth].MLE + / monthlyMaxDemand, + area.hydro.intermonthlyBreakdown); } } else { double coeff = total / 12.; - for (uint realmonth = 0; realmonth != 12; ++realmonth) - data.MTG[realmonth] = coeff; + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) + { + hydro_specific.monthly[realmonth].MTG = coeff; + } } return total; } -void HydroManagement::prepareMonthlyOptimalGenerations(double* random_reservoir_level, +void HydroManagement::prepareMonthlyOptimalGenerations(const double* random_reservoir_level, uint y, - uint numSpace) + HydroSpecificMap& hydro_specific_map) { uint indexArea = 0; - areas_.each([&](Data::Area& area) { - uint z = area.index; - - auto& data = tmpDataByArea_[numSpace][z]; - - auto& minLvl = area.hydro.reservoirLevel[Data::PartHydro::minimum]; - auto& maxLvl = area.hydro.reservoirLevel[Data::PartHydro::maximum]; - - int initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; - - double lvi = -1.; - if (area.hydro.reservoirManagement) - lvi = random_reservoir_level[indexArea]; - - indexArea++; - - double solutionCost = 0.; - double solutionCostNoised = 0.; - - if (area.hydro.reservoirManagement) - { - auto problem = H2O_M_Instanciation(1); - - double totalInflowsYear = prepareMonthlyTargetGenerations(area, data); - assert(totalInflowsYear >= 0.); - - problem.CoutDepassementVolume = 1e2; - problem.CoutViolMaxDuVolumeMin = 1e5; - problem.VolumeInitial = lvi; - - for (unsigned month = 0; month != 12; ++month) - { - uint realmonth = (initReservoirLvlMonth + month) % 12; - - uint simulationMonth = calendar_.mapping.months[realmonth]; - uint firstDay = calendar_.months[simulationMonth].daysYear.first; - - problem.TurbineMax[month] = totalInflowsYear; - problem.TurbineMin[month] = data.mingens[realmonth]; - problem.TurbineCible[month] = data.MTG[realmonth]; - problem.Apport[month] = data.inflows[realmonth]; - problem.VolumeMin[month] = minLvl[firstDay]; - problem.VolumeMax[month] = maxLvl[firstDay]; - } - - H2O_M_OptimiserUneAnnee(problem, 0); - switch (problem.ResultatsValides) { - case OUI: { - if (Logs::Verbosity::Debug::enabled) - CheckHydroAllocationProblem(area, problem, initReservoirLvlMonth, lvi); - - for (uint month = 0; month != 12; ++month) { - uint realmonth = (initReservoirLvlMonth + month) % 12; - - data.MOG[realmonth] = problem.Turbine[month] * area.hydro.reservoirCapacity; - data.MOL[realmonth] = problem.Volume[month]; - } - data.MOL[initReservoirLvlMonth] = lvi; - solutionCost = problem.ProblemeHydraulique.CoutDeLaSolution; - solutionCostNoised = problem.ProblemeHydraulique.CoutDeLaSolutionBruite; - - break; - } - case NON: { - std::ostringstream msg; - msg << "Year : " << y + 1 << " - hydro: " << area.name - << " [month] no solution found"; - throw FatalError(msg.str()); - } - case EMERGENCY_SHUT_DOWN: { - std::ostringstream msg; - msg << "Year : " << y + 1 << " - hydro: " << area.name - << " [month] fatal error"; - throw FatalError(msg.str()); - } - } - - H2O_M_Free(problem); - } - - else - { - auto& reservoirLevel = area.hydro.reservoirLevel[Data::PartHydro::average]; - - for (uint realmonth = 0; realmonth != 12; ++realmonth) - { - data.MOG[realmonth] = data.inflows[realmonth]; - data.MOL[realmonth] = reservoirLevel[realmonth]; - } - } + areas_.each( + [this, &random_reservoir_level, &y, &indexArea, &hydro_specific_map](Data::Area& area) + { + auto& data = area.hydro.managementData[y]; + auto& hydro_specific = hydro_specific_map[&area]; + + auto& minLvl = area.hydro.reservoirLevel[Data::PartHydro::minimum]; + auto& maxLvl = area.hydro.reservoirLevel[Data::PartHydro::maximum]; + + int initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; + + double lvi = -1.; + if (area.hydro.reservoirManagement) + { + lvi = random_reservoir_level[indexArea]; + } + + double solutionCost = 0.; + double solutionCostNoised = 0.; + + if (area.hydro.reservoirManagement) + { + auto problem = H2O_M_Instanciation(1); + + double totalInflowsYear = prepareMonthlyTargetGenerations(area, data, hydro_specific); + assert(totalInflowsYear >= 0.); + + problem.CoutDepassementVolume = 1e2; + problem.CoutViolMaxDuVolumeMin = 1e5; + problem.VolumeInitial = lvi; + + for (unsigned month = 0; month != MONTHS_PER_YEAR; ++month) + { + uint realmonth = (initReservoirLvlMonth + month) % MONTHS_PER_YEAR; + + uint simulationMonth = calendar_.mapping.months[realmonth]; + uint firstDay = calendar_.months[simulationMonth].daysYear.first; + + problem.TurbineMax[month] = totalInflowsYear; + problem.TurbineMin[month] = data.mingens[realmonth]; + problem.TurbineCible[month] = hydro_specific.monthly[realmonth].MTG; + problem.Apport[month] = data.inflows[realmonth]; + problem.VolumeMin[month] = minLvl[firstDay]; + problem.VolumeMax[month] = maxLvl[firstDay]; + } + + H2O_M_OptimiserUneAnnee(problem, 0); + switch (problem.ResultatsValides) + { + case OUI: + { + if (Logs::Verbosity::Debug::enabled) + { + CheckHydroAllocationProblem(area, problem, initReservoirLvlMonth, lvi); + } + + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) + { + uint realmonth = (initReservoirLvlMonth + month) % MONTHS_PER_YEAR; + + hydro_specific.monthly[realmonth].MOG = problem.Turbine[month] + * area.hydro.reservoirCapacity; + hydro_specific.monthly[realmonth].MOL = problem.Volume[month]; + } + hydro_specific.monthly[initReservoirLvlMonth].MOL = lvi; + solutionCost = problem.ProblemeHydraulique.CoutDeLaSolution; + solutionCostNoised = problem.ProblemeHydraulique.CoutDeLaSolutionBruite; + + break; + } + case NON: + { + std::ostringstream msg; + msg << "Year : " << y + 1 << " - hydro: " << area.name + << " [month] no solution found"; + throw FatalError(msg.str()); + } + case EMERGENCY_SHUT_DOWN: + { + std::ostringstream msg; + msg << "Year : " << y + 1 << " - hydro: " << area.name << " [month] fatal error"; + throw FatalError(msg.str()); + } + } + + H2O_M_Free(problem); + } + + else + { + auto& reservoirLevel = area.hydro.reservoirLevel[Data::PartHydro::average]; + + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) + { + hydro_specific.monthly[realmonth].MOG = data.inflows[realmonth]; + hydro_specific.monthly[realmonth].MOL = reservoirLevel[realmonth]; + } + } #ifndef NDEBUG - for (uint realmonth = 0; realmonth != 12; ++realmonth) - { - assert(!Math::NaN(data.MOG[realmonth]) && "nan value detected for MOG"); - assert(!Math::NaN(data.MOL[realmonth]) && "nan value detected for MOL"); - assert(!Math::Infinite(data.MOG[realmonth]) && "infinite value detected for MOG"); - assert(!Math::Infinite(data.MOL[realmonth]) && "infinite value detected for MOL"); - } + for (uint realmonth = 0; realmonth != MONTHS_PER_YEAR; ++realmonth) + { + assert(!std::isnan(hydro_specific.monthly[realmonth].MOG) + && "nan value detected for MOG"); + assert(!std::isnan(hydro_specific.monthly[realmonth].MOL) + && "nan value detected for MOL"); + assert(!std::isinf(hydro_specific.monthly[realmonth].MOG) + && "infinite value detected for MOG"); + assert(!std::isinf(hydro_specific.monthly[realmonth].MOL) + && "infinite value detected for MOL"); + } #endif - if (parameters_.hydroDebug) - { - std::ostringstream buffer, path; - path << "debug" << SEP << "solver" << SEP << (1 + y) << SEP << "monthly." << area.name - << ".txt"; - - if (area.hydro.reservoirManagement) - buffer << "Initial Reservoir Level\t" << lvi << "\n"; - else - buffer << "Initial Reservoir Level : unrelevant (no reservoir mgmt)\n"; - buffer << "\n"; - - auto writeSolutionCost = [&buffer](const std::string& caption, double cost) { - auto precision = buffer.precision(); - buffer << caption << std::fixed << std::setprecision(13) << cost; - buffer << std::setprecision(precision) << std::defaultfloat; - }; - writeSolutionCost("Solution cost : ", solutionCost); - writeSolutionCost("Solution cost (noised) : ", solutionCostNoised); - buffer << "\n\n"; - - buffer << '\t' << "\tInflows" << '\t' << "\tTarget Gen." - << "\tTurbined" - << "\tLevels" << '\t' << "\tLvl min" << '\t' << "\tLvl max\n"; - for (uint month = 0; month != 12; ++month) - { - uint realmonth = (initReservoirLvlMonth + month) % 12; - - uint simulationMonth = calendar_.mapping.months[realmonth]; - - uint firstDay = calendar_.months[simulationMonth].daysYear.first; - - auto monthName = calendar_.text.months[simulationMonth].name; - - buffer << monthName[0] << monthName[1] << monthName[2] << '\t'; - buffer << '\t'; - buffer << data.inflows[realmonth] << '\t'; - buffer << data.MTG[realmonth] << '\t'; - buffer << data.MOG[realmonth] / area.hydro.reservoirCapacity << '\t'; - buffer << data.MOL[realmonth] << '\t'; - buffer << minLvl[firstDay] << '\t'; - buffer << maxLvl[firstDay] << '\t'; - buffer << '\n'; - } - auto content = buffer.str(); - resultWriter_.addEntryFromBuffer(path.str(), content); - } - }); + if (parameters_.hydroDebug) + { + std::ostringstream buffer, path; + path << "debug" << SEP << "solver" << SEP << (1 + y) << SEP << "monthly." << area.name + << ".txt"; + + if (area.hydro.reservoirManagement) + buffer << "Initial Reservoir Level\t" << lvi << "\n"; + else + buffer << "Initial Reservoir Level : unrelevant (no reservoir mgmt)\n"; + buffer << "\n"; + + auto writeSolutionCost = [&buffer](const std::string& caption, double cost) + { + auto precision = buffer.precision(); + buffer << caption << std::fixed << std::setprecision(13) << cost; + buffer << std::setprecision(precision) << std::defaultfloat; + }; + writeSolutionCost("Solution cost : ", solutionCost); + writeSolutionCost("Solution cost (noised) : ", solutionCostNoised); + buffer << "\n\n"; + + buffer << '\t' << "\tInflows" << '\t' << "\tTarget Gen." << "\tTurbined" << "\tLevels" + << '\t' << "\tLvl min" << '\t' << "\tLvl max\n"; + for (uint month = 0; month != MONTHS_PER_YEAR; ++month) + { + uint realmonth = (initReservoirLvlMonth + month) % MONTHS_PER_YEAR; + + uint simulationMonth = calendar_.mapping.months[realmonth]; + + uint firstDay = calendar_.months[simulationMonth].daysYear.first; + + auto monthName = calendar_.text.months[simulationMonth].name; + + buffer << monthName[0] << monthName[1] << monthName[2] << '\t'; + buffer << '\t'; + buffer << data.inflows[realmonth] << '\t'; + buffer << hydro_specific.monthly[realmonth].MTG << '\t'; + buffer << hydro_specific.monthly[realmonth].MOG / area.hydro.reservoirCapacity + << '\t'; + buffer << hydro_specific.monthly[realmonth].MOL << '\t'; + buffer << minLvl[firstDay] << '\t'; + buffer << maxLvl[firstDay] << '\t'; + buffer << '\n'; + } + auto content = buffer.str(); + resultWriter_.addEntryFromBuffer(path.str(), content); + } + indexArea++; + }); } } // namespace Antares diff --git a/src/solver/hydro/monthly/h2o_m_ajouter_bruit.cpp b/src/solver/hydro/monthly/h2o_m_ajouter_bruit.cpp index 113b972117..1b0341f838 100644 --- a/src/solver/hydro/monthly/h2o_m_ajouter_bruit.cpp +++ b/src/solver/hydro/monthly/h2o_m_ajouter_bruit.cpp @@ -1,7 +1,28 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include + #include -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" namespace Constants { @@ -12,30 +33,30 @@ constexpr unsigned int seed = 0x79686d64; // "hydm" in hexa void H2O_M_AjouterBruitAuCout(DONNEES_ANNUELLES& DonneesAnnuelles) { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; - CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe; + CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables = ProblemeHydraulique + .CorrespondanceDesVariables; auto& CoutLineaireBruite = ProblemeLineairePartieFixe.CoutLineaireBruite; const auto& CoutLineaire = ProblemeLineairePartieFixe.CoutLineaire; Antares::MersenneTwister noiseGenerator; noiseGenerator.reset(Constants::seed); // Arbitrary seed, hard-coded since we don't really want // the user to change it - const std::vector*> monthlyVariables - = {&CorrespondanceDesVariables.NumeroDeVariableVolume, - &CorrespondanceDesVariables.NumeroDeVariableTurbine, - &CorrespondanceDesVariables.NumeroDeVariableDepassementVolumeMax, - &CorrespondanceDesVariables.NumeroDeVariableDepassementVolumeMin, - &CorrespondanceDesVariables.NumeroDeVariableDEcartPositifAuTurbineCible, - &CorrespondanceDesVariables.NumeroDeVariableDEcartNegatifAuTurbineCible}; + const std::vector*> monthlyVariables = { + &CorrespondanceDesVariables.NumeroDeVariableVolume, + &CorrespondanceDesVariables.NumeroDeVariableTurbine, + &CorrespondanceDesVariables.NumeroDeVariableDepassementVolumeMax, + &CorrespondanceDesVariables.NumeroDeVariableDepassementVolumeMin, + &CorrespondanceDesVariables.NumeroDeVariableDEcartPositifAuTurbineCible, + &CorrespondanceDesVariables.NumeroDeVariableDEcartNegatifAuTurbineCible}; - for (const auto& variable : monthlyVariables) + for (const auto& variable: monthlyVariables) { - for (int Var : *variable) + for (int Var: *variable) { - CoutLineaireBruite[Var] - = CoutLineaire[Var] + noiseGenerator() * Constants::noiseAmplitude; + CoutLineaireBruite[Var] = CoutLineaire[Var] + + noiseGenerator() * Constants::noiseAmplitude; } } int Var = CorrespondanceDesVariables.NumeroDeLaVariableViolMaxVolumeMin; diff --git a/src/solver/hydro/monthly/h2o_m_construire_les_contraintes.cpp b/src/solver/hydro/monthly/h2o_m_construire_les_contraintes.cpp index 3e1b61ec93..64ec013f79 100644 --- a/src/solver/hydro/monthly/h2o_m_construire_les_contraintes.cpp +++ b/src/solver/hydro/monthly/h2o_m_construire_les_contraintes.cpp @@ -1,43 +1,37 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" void H2O_M_ConstruireLesContraintes(DONNEES_ANNUELLES& DonneesAnnuelles) { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; - CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; + CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables = ProblemeHydraulique + .CorrespondanceDesVariables; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe; - auto& CoefficientsDeLaMatriceDesContraintes - = ProblemeLineairePartieFixe.CoefficientsDeLaMatriceDesContraintes; + auto& CoefficientsDeLaMatriceDesContraintes = ProblemeLineairePartieFixe + .CoefficientsDeLaMatriceDesContraintes; auto& IndicesColonnes = ProblemeLineairePartieFixe.IndicesColonnes; auto& IndicesDebutDeLigne = ProblemeLineairePartieFixe.IndicesDebutDeLigne; auto& Sens = ProblemeLineairePartieFixe.Sens; @@ -45,10 +39,10 @@ void H2O_M_ConstruireLesContraintes(DONNEES_ANNUELLES& DonneesAnnuelles) auto& NumeroDeVariableVolume = CorrespondanceDesVariables.NumeroDeVariableVolume; auto& NumeroDeVariableTurbine = CorrespondanceDesVariables.NumeroDeVariableTurbine; - auto& NumeroDeVariableDepassementVolumeMax - = CorrespondanceDesVariables.NumeroDeVariableDepassementVolumeMax; - auto& NumeroDeVariableDepassementVolumeMin - = CorrespondanceDesVariables.NumeroDeVariableDepassementVolumeMin; + auto& NumeroDeVariableDepassementVolumeMax = CorrespondanceDesVariables + .NumeroDeVariableDepassementVolumeMax; + auto& NumeroDeVariableDepassementVolumeMin = CorrespondanceDesVariables + .NumeroDeVariableDepassementVolumeMin; auto& NumeroDeVariableDEcartPositifAuTurbineCible = CorrespondanceDesVariables.NumeroDeVariableDEcartPositifAuTurbineCible; auto& NumeroDeVariableDEcartNegatifAuTurbineCible diff --git a/src/solver/hydro/monthly/h2o_m_construire_les_variables.cpp b/src/solver/hydro/monthly/h2o_m_construire_les_variables.cpp index 93eb7d297f..0173f9989d 100644 --- a/src/solver/hydro/monthly/h2o_m_construire_les_variables.cpp +++ b/src/solver/hydro/monthly/h2o_m_construire_les_variables.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifdef __cplusplus @@ -36,38 +30,30 @@ extern "C" } #endif -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" void H2O_M_ConstruireLesVariables(DONNEES_ANNUELLES& DonneesAnnuelles) { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; - CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables; + = ProblemeHydraulique.ProblemeLineairePartieVariable; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe; + CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables = ProblemeHydraulique + .CorrespondanceDesVariables; const int NbPdt = DonneesAnnuelles.NombreDePasDeTemps; int Var = 0; - CorrespondanceDesVariables.NumeroDeVariableVolume[0] = Var; - ProblemeLineairePartieVariable.Xmin[Var] = 0.0; - ProblemeLineairePartieVariable.Xmax[Var] = 1.0; - ProblemeLineairePartieFixe.TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesAnnuelles.Volume[0]); - Var++; - - for (int Pdt = 1; Pdt < NbPdt; Pdt++) + for (int Pdt = 0; Pdt < NbPdt; Pdt++) { CorrespondanceDesVariables.NumeroDeVariableVolume[Pdt] = Var; ProblemeLineairePartieVariable.Xmin[Var] = 0.0; ProblemeLineairePartieVariable.Xmax[Var] = 1.0; ProblemeLineairePartieFixe.TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesAnnuelles.Volume[Pdt]); + ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesAnnuelles.Volume[Pdt]); Var++; } @@ -77,8 +63,8 @@ void H2O_M_ConstruireLesVariables(DONNEES_ANNUELLES& DonneesAnnuelles) ProblemeLineairePartieVariable.Xmin[Var] = 0.0; ProblemeLineairePartieVariable.Xmax[Var] = 0.0; ProblemeLineairePartieFixe.TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = &(DonneesAnnuelles.Turbine[Pdt]); + ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = &( + DonneesAnnuelles.Turbine[Pdt]); Var++; } diff --git a/src/solver/hydro/monthly/h2o_m_donnees_annuelles.h b/src/solver/hydro/monthly/h2o_m_donnees_annuelles.h deleted file mode 100644 index 175aed380c..0000000000 --- a/src/solver/hydro/monthly/h2o_m_donnees_annuelles.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#ifndef __SOLVER_H2O_M_DONNEES_ANNEE__ -#define __SOLVER_H2O_M_DONNEES_ANNEE__ - -#define OUI 1 -#define NON 0 -#define EMERGENCY_SHUT_DOWN 2 - -#include "h2o_m_donnees_optimisation.h" - -/*************************************************************************************************/ -/* Structure contenant les champs a renseigner par l'appelant */ - -typedef struct -{ - /* En entree: seules les donnees ci-dessous doivent etre renseignees par l'appelant apres - avoir appele " H2O_M_Instanciation " */ - /* Commence a 0 pour le 1er janvier et se termine a 11 pour le 1er decembre */ - double CoutDepassementVolume; /* A renseigner par l'appelant : 1 valeur */ - double CoutViolMaxDuVolumeMin; // A renseigner par l'appelant : 1 valeur - double VolumeInitial; /* A renseigner par l'appelant : 1 valeur */ - std::vector TurbineMax; /* A renseigner par l'appelant : 1 valeur par mois */ - std::vector TurbineMin; - std::vector TurbineCible; /* A renseigner par l'appelant : 1 valeur par mois */ - std::vector Apport; /* A renseigner par l'appelant : 1 valeur par mois */ - /* Pour decrire la bande de volumes permise */ - std::vector VolumeMin; /* A renseigner par l'appelant : 1 valeur par mois */ - std::vector VolumeMax; /* A renseigner par l'appelant : 1 valeur par mois */ - - /* Les resultats */ - char - ResultatsValides; /* Vaut: - OUI si la solution est exploitable pour le reservoir - NON s'il y a eu un probleme dans la resolution - EMERGENCY_SHUT_DOWN si la resolution du probleme a donne lieu a une erreur interne - */ - std::vector Turbine; /* Resultat a recuperer par l'appelant */ - std::vector Volume; /* Resultat a recuperer par l'appelant */ - - /******************************************************************************************/ - /* Problemes internes (utilise uniquement par l'optimisation) */ - PROBLEME_HYDRAULIQUE ProblemeHydraulique; - int NombreDePasDeTemps; /* 12 */ -} DONNEES_ANNUELLES; - -#endif diff --git a/src/solver/hydro/monthly/h2o_m_donnees_optimisation.h b/src/solver/hydro/monthly/h2o_m_donnees_optimisation.h deleted file mode 100644 index 7395dfa915..0000000000 --- a/src/solver/hydro/monthly/h2o_m_donnees_optimisation.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_H2O_M_STRUCTURE_INTERNE__ -#define __SOLVER_H2O_M_STRUCTURE_INTERNE__ - -#ifdef __CPLUSPLUS -extern "C" -{ -#endif - -#include "spx_definition_arguments.h" -#include "spx_fonctions.h" - -#ifdef __CPLUSPLUS -} -#endif - -#include - -#define LINFINI 1.e+80 - -/*--------------------------------------------------------------------------------------*/ -/* Matrice des contraintes: il y aura une seule instance pour tous les reservoirs */ -/* Dans ce struct il n'y a que des donnees qui sont lues et surtout pas ecrites */ -/* Ce struct est instancie une seule fois */ -typedef struct -{ - int NombreDeVariables; - std::vector CoutLineaire; - std::vector CoutLineaireBruite; /* Ajout de bruit pour forcer l'unicité des solutions */ - std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les suivantes - (voir le fichier spx_constantes_externes.h mais ne jamais utiliser les - valeurs explicites des constantes): VARIABLE_FIXE , - VARIABLE_BORNEE_DES_DEUX_COTES , - VARIABLE_BORNEE_INFERIEUREMENT , - VARIABLE_BORNEE_SUPERIEUREMENT , - VARIABLE_NON_BORNEE - */ - /* La matrice des contraintes */ - int NombreDeContraintes; - std::vector Sens; - std::vector IndicesDebutDeLigne; - std::vector NombreDeTermesDesLignes; - std::vector CoefficientsDeLaMatriceDesContraintes; - std::vector IndicesColonnes; - int NombreDeTermesAlloues; -} PROBLEME_LINEAIRE_PARTIE_FIXE; - -/* Partie variable renseignee avant le lancement de l'optimisation de chaque reservoir */ -typedef struct -{ - /* Donnees variables de la matrice des contraintes */ - /* On met quand-meme les bornes dans la partie variable pour le cas ou on voudrait avoir - un jour des bornes min et max variables dans le temps et en fonction des reservoirs */ - std::vector Xmin; - std::vector Xmax; - std::vector SecondMembre; - /* Tableau de pointeur a des doubles. Ce tableau est parallele a X, il permet - de renseigner directement les structures de description du reseau avec les - resultats contenus dans X */ - std::vector AdresseOuPlacerLaValeurDesVariablesOptimisees; - /* Resultat */ - std::vector X; - /* En Entree ou en Sortie */ - int ExistenceDUneSolution; /* En sortie, vaut : - OUI_SPX s'il y a une solution, - NON_SPX s'il n'y a pas de solution - admissible SPX_ERREUR_INTERNE si probleme a l'execution - (saturation memoire par exemple), et dans ce cas il n'y a pas de - solution SPX_MATRICE_DE_BASE_SINGULIERE si on n'a pas pu - construire de matrice de base reguliere, et dans ce cas il n'y a - pas de solution - */ - - std::vector PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector CoutsReduits; /* Vecteur a passer au Simplexe pour recuperer les couts reduits */ - std::vector CoutsMarginauxDesContraintes; /* Vecteur a passer au Simplexe pour recuperer les couts - marginaux */ -} PROBLEME_LINEAIRE_PARTIE_VARIABLE; - -/* Les correspondances des variables */ -typedef struct -{ - std::vector NumeroDeVariableVolume; /* Volumes */ - std::vector NumeroDeVariableTurbine; /* Turbines */ - std::vector NumeroDeVariableDepassementVolumeMax; /* Depassement du volume max */ - std::vector NumeroDeVariableDepassementVolumeMin; /* Depassement du volume min */ - int NumeroDeLaVariableViolMaxVolumeMin; // Depassement max du volume min - std::vector NumeroDeVariableDEcartPositifAuTurbineCible; /* Ecart positif au volume cible */ - std::vector NumeroDeVariableDEcartNegatifAuTurbineCible; /* Ecart negatif au volume cible */ - int NumeroDeLaVariableXi; /* Variable decrivant l'ecart max au turbine cible */ -} CORRESPONDANCE_DES_VARIABLES; - -/* Structure uniquement exploitee par l'optimisation (donc a ne pas acceder depuis l'exterieur) */ -typedef struct -{ - int NombreDeReservoirs; - char LesCoutsOntEteInitialises; /* Vaut OUI ou NON */ - - CORRESPONDANCE_DES_VARIABLES CorrespondanceDesVariables; - - PROBLEME_LINEAIRE_PARTIE_FIXE ProblemeLineairePartieFixe; - PROBLEME_LINEAIRE_PARTIE_VARIABLE ProblemeLineairePartieVariable; - - std::vector ProblemeSpx; /* Il y en a 1 par reservoir */ - - double CoutDeLaSolution; - double CoutDeLaSolutionBruite; - -} PROBLEME_HYDRAULIQUE; - -#endif diff --git a/src/solver/hydro/monthly/h2o_m_fonctions.h b/src/solver/hydro/monthly/h2o_m_fonctions.h deleted file mode 100644 index aa5a531b28..0000000000 --- a/src/solver/hydro/monthly/h2o_m_fonctions.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_H2O_M_FONCTIONS__ -#define __SOLVER_H2O_M_FONCTIONS__ - -DONNEES_ANNUELLES H2O_M_Instanciation(int); -void H2O_M_OptimiserUneAnnee(DONNEES_ANNUELLES&, int); -void H2O_M_Free(DONNEES_ANNUELLES&); - -void H2O_M_ConstruireLesContraintes(DONNEES_ANNUELLES&); -void H2O_M_ConstruireLesVariables(DONNEES_ANNUELLES&); -void H2O_M_InitialiserBornesEtCoutsDesVariables(DONNEES_ANNUELLES&); -void H2O_M_InitialiserLeSecondMembre(DONNEES_ANNUELLES&); -void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES&, int); -void H2O_M_AjouterBruitAuCout(DONNEES_ANNUELLES&); - -#endif /* __SOLVER_H2O_M_FONCTIONS__ */ diff --git a/src/solver/hydro/monthly/h2o_m_free.cpp b/src/solver/hydro/monthly/h2o_m_free.cpp index be762274e2..bde155e821 100644 --- a/src/solver/hydro/monthly/h2o_m_free.cpp +++ b/src/solver/hydro/monthly/h2o_m_free.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifdef __CPLUSPLUS @@ -37,19 +31,20 @@ extern "C" } #endif -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" void H2O_M_Free(DONNEES_ANNUELLES& DonneesAnnuelles) { - PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; for (int i = 0; i < ProblemeHydraulique.NombreDeReservoirs; i++) { PROBLEME_SPX* ProbSpx = (PROBLEME_SPX*)ProblemeHydraulique.ProblemeSpx[i]; if (ProbSpx) + { SPX_LibererProbleme(ProbSpx); + } } return; diff --git a/src/solver/hydro/monthly/h2o_m_initialiser_les_bornes_des_variables.cpp b/src/solver/hydro/monthly/h2o_m_initialiser_les_bornes_des_variables.cpp index c55cb17d1d..7ddee7cf2d 100644 --- a/src/solver/hydro/monthly/h2o_m_initialiser_les_bornes_des_variables.cpp +++ b/src/solver/hydro/monthly/h2o_m_initialiser_les_bornes_des_variables.cpp @@ -1,42 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" void H2O_M_InitialiserBornesEtCoutsDesVariables(DONNEES_ANNUELLES& DonneesAnnuelles) { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable; - const CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; + = ProblemeHydraulique.ProblemeLineairePartieVariable; + const CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables = ProblemeHydraulique + .CorrespondanceDesVariables; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe; DonneesAnnuelles.Volume[0] = DonneesAnnuelles.VolumeInitial; @@ -45,7 +39,6 @@ void H2O_M_InitialiserBornesEtCoutsDesVariables(DONNEES_ANNUELLES& DonneesAnnuel auto& TurbineMax = DonneesAnnuelles.TurbineMax; const auto& TurbineMin = DonneesAnnuelles.TurbineMin; - auto& Xmin = ProblemeLineairePartieVariable.Xmin; auto& Xmax = ProblemeLineairePartieVariable.Xmax; auto& X = ProblemeLineairePartieVariable.X; diff --git a/src/solver/hydro/monthly/h2o_m_initialiser_les_second_membre.cpp b/src/solver/hydro/monthly/h2o_m_initialiser_les_second_membre.cpp index 9c08ade8c5..4244bd555d 100644 --- a/src/solver/hydro/monthly/h2o_m_initialiser_les_second_membre.cpp +++ b/src/solver/hydro/monthly/h2o_m_initialiser_les_second_membre.cpp @@ -1,38 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" void H2O_M_InitialiserLeSecondMembre(DONNEES_ANNUELLES& DonneesAnnuelles) { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable; + = ProblemeHydraulique.ProblemeLineairePartieVariable; double ChgmtSens = -1; const int NbPdt = DonneesAnnuelles.NombreDePasDeTemps; diff --git a/src/solver/hydro/monthly/h2o_m_instanciation.cpp b/src/solver/hydro/monthly/h2o_m_instanciation.cpp index f6166a3a94..8d7c53c7d4 100644 --- a/src/solver/hydro/monthly/h2o_m_instanciation.cpp +++ b/src/solver/hydro/monthly/h2o_m_instanciation.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" DONNEES_ANNUELLES H2O_M_Instanciation(int NombreDeReservoirs) { @@ -52,12 +46,12 @@ DONNEES_ANNUELLES H2O_M_Instanciation(int NombreDeReservoirs) ProblemeHydraulique.ProblemeSpx.assign(NombreDeReservoirs, nullptr); - CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables - = ProblemeHydraulique.CorrespondanceDesVariables; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; + CORRESPONDANCE_DES_VARIABLES& CorrespondanceDesVariables = ProblemeHydraulique + .CorrespondanceDesVariables; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable; + = ProblemeHydraulique.ProblemeLineairePartieVariable; CorrespondanceDesVariables.NumeroDeVariableVolume.assign(NbPdt, 0); CorrespondanceDesVariables.NumeroDeVariableTurbine.assign(NbPdt, 0); @@ -109,8 +103,8 @@ DONNEES_ANNUELLES H2O_M_Instanciation(int NombreDeReservoirs) ProblemeLineairePartieFixe.NombreDeTermesAlloues = NombreDeTermesAlloues; - ProblemeLineairePartieFixe.CoefficientsDeLaMatriceDesContraintes - .assign(NombreDeTermesAlloues, 0.); + ProblemeLineairePartieFixe.CoefficientsDeLaMatriceDesContraintes.assign(NombreDeTermesAlloues, + 0.); ProblemeLineairePartieFixe.IndicesColonnes.assign(NombreDeTermesAlloues, 0); @@ -119,11 +113,10 @@ DONNEES_ANNUELLES H2O_M_Instanciation(int NombreDeReservoirs) ProblemeLineairePartieVariable.SecondMembre.assign(NombreDeContraintes, 0.); ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees - .assign(NombreDeVariables, nullptr); + .assign(NombreDeVariables, nullptr); ProblemeLineairePartieVariable.X.assign(NombreDeVariables, 0.); - ProblemeLineairePartieVariable.PositionDeLaVariable.assign(NombreDeVariables, 0); ProblemeLineairePartieVariable.ComplementDeLaBase.assign(NombreDeContraintes, 0); diff --git a/src/solver/hydro/monthly/h2o_m_optimiser_une_annee.cpp b/src/solver/hydro/monthly/h2o_m_optimiser_une_annee.cpp index caa489b5d3..0b1adcffe4 100644 --- a/src/solver/hydro/monthly/h2o_m_optimiser_une_annee.cpp +++ b/src/solver/hydro/monthly/h2o_m_optimiser_une_annee.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" void H2O_M_OptimiserUneAnnee(DONNEES_ANNUELLES& DonneesAnnuelles, int NumeroDeReservoir) { diff --git a/src/solver/hydro/monthly/h2o_m_resoudre_le_probleme_lineaire.cpp b/src/solver/hydro/monthly/h2o_m_resoudre_le_probleme_lineaire.cpp index 8b61cc3ee3..f65ec03e6e 100644 --- a/src/solver/hydro/monthly/h2o_m_resoudre_le_probleme_lineaire.cpp +++ b/src/solver/hydro/monthly/h2o_m_resoudre_le_probleme_lineaire.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "h2o_m_donnees_annuelles.h" -#include "h2o_m_fonctions.h" +#include "antares/solver/hydro/monthly/h2o_m_donnees_annuelles.h" +#include "antares/solver/hydro/monthly/h2o_m_fonctions.h" #ifdef _MSC_VER #define SNPRINTF sprintf_s @@ -40,10 +34,9 @@ void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES& DonneesAnnuelles, int N { PROBLEME_HYDRAULIQUE& ProblemeHydraulique = DonneesAnnuelles.ProblemeHydraulique; PROBLEME_LINEAIRE_PARTIE_VARIABLE& ProblemeLineairePartieVariable - = ProblemeHydraulique.ProblemeLineairePartieVariable; - PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe - = ProblemeHydraulique.ProblemeLineairePartieFixe; - + = ProblemeHydraulique.ProblemeLineairePartieVariable; + PROBLEME_LINEAIRE_PARTIE_FIXE& ProblemeLineairePartieFixe = ProblemeHydraulique + .ProblemeLineairePartieFixe; PROBLEME_SPX* ProbSpx = ProblemeHydraulique.ProblemeSpx[NumeroDeReservoir]; std::unique_ptr Probleme = std::make_unique(); @@ -83,8 +76,9 @@ void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES& DonneesAnnuelles, int N Probleme->IndicesDebutDeLigne = ProblemeLineairePartieFixe.IndicesDebutDeLigne.data(); Probleme->NombreDeTermesDesLignes = ProblemeLineairePartieFixe.NombreDeTermesDesLignes.data(); Probleme->IndicesColonnes = ProblemeLineairePartieFixe.IndicesColonnes.data(); - Probleme->CoefficientsDeLaMatriceDesContraintes - = ProblemeLineairePartieFixe.CoefficientsDeLaMatriceDesContraintes.data(); + Probleme->CoefficientsDeLaMatriceDesContraintes = ProblemeLineairePartieFixe + .CoefficientsDeLaMatriceDesContraintes + .data(); Probleme->Sens = ProblemeLineairePartieFixe.Sens.data(); Probleme->SecondMembre = ProblemeLineairePartieVariable.SecondMembre.data(); @@ -103,15 +97,19 @@ void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES& DonneesAnnuelles, int N Probleme->UtiliserCoutMax = NON_SPX; Probleme->CoutMax = 0.0; - Probleme->CoutsMarginauxDesContraintes - = ProblemeLineairePartieVariable.CoutsMarginauxDesContraintes.data(); + Probleme->CoutsMarginauxDesContraintes = ProblemeLineairePartieVariable + .CoutsMarginauxDesContraintes.data(); Probleme->CoutsReduits = ProblemeLineairePartieVariable.CoutsReduits.data(); #ifndef NDEBUG if (PremierPassage) + { Probleme->AffichageDesTraces = NON_SPX; + } else + { Probleme->AffichageDesTraces = OUI_SPX; + } #else Probleme->AffichageDesTraces = NON_SPX; #endif @@ -121,17 +119,20 @@ void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES& DonneesAnnuelles, int N ProbSpx = SPX_Simplexe(Probleme.get(), ProbSpx); if (ProbSpx) + { ProblemeHydraulique.ProblemeSpx[NumeroDeReservoir] = ProbSpx; + } ProblemeLineairePartieVariable.ExistenceDUneSolution = Probleme->ExistenceDUneSolution; - if (ProblemeLineairePartieVariable.ExistenceDUneSolution != OUI_SPX && PremierPassage && ProbSpx) + if (ProblemeLineairePartieVariable.ExistenceDUneSolution != OUI_SPX && PremierPassage + && ProbSpx) { if (ProblemeLineairePartieVariable.ExistenceDUneSolution != SPX_ERREUR_INTERNE) { SPX_LibererProbleme(ProbSpx); - ProbSpx = NULL; + ProbSpx = nullptr; PremierPassage = false; goto RESOLUTION; } @@ -147,24 +148,28 @@ void H2O_M_ResoudreLeProblemeLineaire(DONNEES_ANNUELLES& DonneesAnnuelles, int N ProblemeHydraulique.CoutDeLaSolution = 0.0; for (int var = 0; var < Probleme->NombreDeVariables; var++) { - ProblemeHydraulique.CoutDeLaSolution - += ProblemeLineairePartieFixe.CoutLineaire[var] * Probleme->X[var]; + ProblemeHydraulique.CoutDeLaSolution += ProblemeLineairePartieFixe.CoutLineaire[var] + * Probleme->X[var]; } ProblemeHydraulique.CoutDeLaSolutionBruite = 0.0; for (int var = 0; var < Probleme->NombreDeVariables; var++) { - ProblemeHydraulique.CoutDeLaSolutionBruite - += ProblemeLineairePartieFixe.CoutLineaireBruite[var] * Probleme->X[var]; + ProblemeHydraulique.CoutDeLaSolutionBruite += ProblemeLineairePartieFixe + .CoutLineaireBruite[var] + * Probleme->X[var]; } DonneesAnnuelles.ResultatsValides = OUI; for (int var = 0; var < ProblemeLineairePartieFixe.NombreDeVariables; var++) { - double* pt = ProblemeLineairePartieVariable.AdresseOuPlacerLaValeurDesVariablesOptimisees[var]; + double* pt = ProblemeLineairePartieVariable + .AdresseOuPlacerLaValeurDesVariablesOptimisees[var]; if (pt) + { *pt = ProblemeLineairePartieVariable.X[var]; + } } } else diff --git a/src/solver/infeasible-problem-analysis/CMakeLists.txt b/src/solver/infeasible-problem-analysis/CMakeLists.txt index 97864d3ef8..720842fd6a 100644 --- a/src/solver/infeasible-problem-analysis/CMakeLists.txt +++ b/src/solver/infeasible-problem-analysis/CMakeLists.txt @@ -1,18 +1,30 @@ project(infeasible-problem-analysis) set(SRC_INFEASIBLE_PROBLEM_ANALYSIS - problem.cpp - problem.h - report.h - report.cpp - constraint.h - constraint.cpp - exceptions.h - exceptions.cpp - ) + include/antares/solver/infeasible-problem-analysis/unfeasibility-analysis.h + include/antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h + constraint-slack-analysis.cpp + include/antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h + variables-bounds-consistency.cpp + unfeasible-pb-analyzer.cpp + include/antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h + include/antares/solver/infeasible-problem-analysis/report.h + report.cpp + include/antares/solver/infeasible-problem-analysis/constraint.h + constraint.cpp +) add_library(infeasible_problem_analysis ${SRC_INFEASIBLE_PROBLEM_ANALYSIS}) target_link_libraries(infeasible_problem_analysis - PUBLIC ortools::ortools sirius_solver - utils #ortools-utils, not Antares::utils - ) + PRIVATE + ortools::ortools + Antares::logs +) +target_include_directories(infeasible_problem_analysis + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/solver/infeasible-problem-analysis/constraint-slack-analysis.cpp b/src/solver/infeasible-problem-analysis/constraint-slack-analysis.cpp new file mode 100644 index 0000000000..785d4670f8 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/constraint-slack-analysis.cpp @@ -0,0 +1,113 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include "antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h" + +#include + +#include +#include "antares/solver/infeasible-problem-analysis/report.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +#include "ortools/linear_solver/linear_solver.h" +#pragma GCC diagnostic pop + +using namespace operations_research; + +namespace Antares::Optimization +{ + +void ConstraintSlackAnalysis::run(MPSolver* problem) +{ + addSlackVariables(problem); + if (slackVariables_.empty()) + { + logs.error() << title() << " : no constraints have been selected"; + return; + } + + buildObjective(problem); + + const MPSolver::ResultStatus status = problem->Solve(); + if ((status != MPSolver::OPTIMAL) && (status != MPSolver::FEASIBLE)) + { + logs.error() << title() << " : modified linear problem could not be solved"; + return; + } + + hasDetectedInfeasibilityCause_ = true; +} + +void ConstraintSlackAnalysis::addSlackVariables(MPSolver* problem) +{ + /* Optimization: + We assess that less than 1 every 3 constraint will match + the regex. If more, push_back may force the copy of memory blocks. + This should not happen in most cases. + */ + const unsigned int selectedConstraintsInverseRatio = 3; + slackVariables_.reserve(problem->NumConstraints() / selectedConstraintsInverseRatio); + std::regex rgx(constraint_name_pattern); + const double infinity = MPSolver::infinity(); + for (MPConstraint* constraint: problem->constraints()) + { + if (std::regex_search(constraint->name(), rgx)) + { + if (constraint->lb() != -infinity) + { + const MPVariable* slack = problem->MakeNumVar(0, + infinity, + constraint->name() + "::low"); + constraint->SetCoefficient(slack, 1.); + slackVariables_.push_back(slack); + } + + if (constraint->ub() != infinity) + { + const MPVariable* slack = problem->MakeNumVar(0, + infinity, + constraint->name() + "::up"); + constraint->SetCoefficient(slack, -1.); + slackVariables_.push_back(slack); + } + } + } +} + +void ConstraintSlackAnalysis::buildObjective(MPSolver* problem) const +{ + MPObjective* objective = problem->MutableObjective(); + // Reset objective function + objective->Clear(); + // Only slack variables have a non-zero cost + for (const MPVariable* slack: slackVariables_) + { + objective->SetCoefficient(slack, 1.); + } + objective->SetMinimization(); +} + +void ConstraintSlackAnalysis::printReport() const +{ + InfeasibleProblemReport report(slackVariables_); + report.prettyPrint(); +} + +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/constraint.cpp b/src/solver/infeasible-problem-analysis/constraint.cpp index ba8788ebcc..0e95848ad9 100644 --- a/src/solver/infeasible-problem-analysis/constraint.cpp +++ b/src/solver/infeasible-problem-analysis/constraint.cpp @@ -1,16 +1,40 @@ -#include +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include "antares/solver/infeasible-problem-analysis/constraint.h" -#include "constraint.h" -#include -#include #include +#include +#include +#include -namespace Antares +namespace { -namespace Optimization +const std::string kUnknown = ""; +} + +namespace Antares::Optimization { -Constraint::Constraint(const std::string& input, const double slackValue) : - mInput(input), mSlackValue(slackValue) +Constraint::Constraint(const std::string& input, const double slackValue): + mInput(input), + mSlackValue(slackValue) { } @@ -42,10 +66,11 @@ double Constraint::getSlackValue() const return mSlackValue; } -class StringIsNotWellFormated : public std::runtime_error +class StringIsNotWellFormated: public std::runtime_error { public: - StringIsNotWellFormated(const std::string& error_message) : std::runtime_error(error_message) + StringIsNotWellFormated(const std::string& error_message): + std::runtime_error(error_message) { } }; @@ -103,9 +128,10 @@ std::string Constraint::getTimeStepInYear() const case ConstraintType::binding_constraint_daily: case ConstraintType::fictitious_load: case ConstraintType::hydro_reservoir_level: - return StringBetweenAngleBrackets (mItems.at(mItems.size()-2)); + case ConstraintType::short_term_storage_level: + return StringBetweenAngleBrackets(mItems.at(mItems.size() - 2)); default: - return "-1"; + return kUnknown; } } @@ -132,6 +158,10 @@ ConstraintType Constraint::getType() const { return ConstraintType::hydro_reservoir_level; } + if (mItems.at(0) == "Level") + { + return ConstraintType::short_term_storage_level; + } return ConstraintType::none; } @@ -144,7 +174,19 @@ std::string Constraint::getBindingConstraintName() const case ConstraintType::binding_constraint_weekly: return mItems.at(0); default: - return ""; + return kUnknown; + } +} + +std::string Constraint::getSTSName() const +{ + if (getType() == ConstraintType::short_term_storage_level) + { + return StringBetweenAngleBrackets(mItems.at(2)); + } + else + { + return kUnknown; } } @@ -167,9 +209,12 @@ std::string Constraint::prettyPrint() const case ConstraintType::hydro_reservoir_level: return "Hydro reservoir constraint at area '" + getAreaName() + "' at hour " + getTimeStepInYear(); + case ConstraintType::short_term_storage_level: + return "Short-term-storage reservoir constraint at area '" + getAreaName() + "' in STS '" + + getSTSName() + "' at hour " + getTimeStepInYear(); + default: - return ""; + return kUnknown; } } -} // namespace Optimization -} // namespace Antares +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/constraint.h b/src/solver/infeasible-problem-analysis/constraint.h deleted file mode 100644 index 86d2bebd71..0000000000 --- a/src/solver/infeasible-problem-analysis/constraint.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include - -namespace Antares -{ -namespace Optimization -{ -enum class ConstraintType -{ - binding_constraint_hourly, - binding_constraint_daily, - binding_constraint_weekly, - fictitious_load, - hydro_reservoir_level, - none -}; - -class Constraint -{ -public: - // Construct object - Constraint() = default; - Constraint(const std::string& input, const double slackValue); - - // Raw members - double getSlackValue() const; - - // Extract items, check consistency - std::size_t extractItems(); - std::string prettyPrint() const; - ConstraintType getType() const; - -private: - std::string mInput; - std::vector mItems; - double mSlackValue; - - // Get specific items - std::string getAreaName() const; - std::string getTimeStepInYear() const; - std::string getBindingConstraintName() const; -}; -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/infeasible-problem-analysis/exceptions.cpp b/src/solver/infeasible-problem-analysis/exceptions.cpp deleted file mode 100644 index 1f225fe486..0000000000 --- a/src/solver/infeasible-problem-analysis/exceptions.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "exceptions.h" - -/* This file contains exceptions that can be thrown by the - infeasible problem analyser. -*/ - -namespace Antares -{ -namespace Optimization -{ -SlackVariablesEmpty::SlackVariablesEmpty(const std::string& s) : std::runtime_error(s) -{ -} -ProblemResolutionFailed::ProblemResolutionFailed(const std::string& s) : std::runtime_error(s) -{ -} -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/infeasible-problem-analysis/exceptions.h b/src/solver/infeasible-problem-analysis/exceptions.h deleted file mode 100644 index 5b88b77c06..0000000000 --- a/src/solver/infeasible-problem-analysis/exceptions.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include - -namespace Antares -{ -namespace Optimization -{ -class SlackVariablesEmpty : public std::runtime_error -{ -public: - explicit SlackVariablesEmpty(const std::string& message); -}; -class ProblemResolutionFailed : public std::runtime_error -{ -public: - explicit ProblemResolutionFailed(const std::string& message); -}; -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h new file mode 100644 index 0000000000..a298b6b026 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h @@ -0,0 +1,63 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include + +#include "unfeasibility-analysis.h" + +namespace operations_research +{ +class MPVariable; +class MPSolver; +} // namespace operations_research + +namespace Antares::Optimization +{ + +/*! + * That particular analysis relaxes all constraints by + * adding slack variables for each one. + */ +class ConstraintSlackAnalysis: public UnfeasibilityAnalysis +{ +public: + ConstraintSlackAnalysis() = default; + ~ConstraintSlackAnalysis() override = default; + + void run(operations_research::MPSolver* problem) override; + void printReport() const override; + + std::string title() const override + { + return "Slack variables analysis"; + } + +private: + void buildObjective(operations_research::MPSolver* problem) const; + void addSlackVariables(operations_research::MPSolver* problem); + + std::vector slackVariables_; + const std::string constraint_name_pattern = "^AreaHydroLevel::|::hourly::|::daily::|::weekly::|" + "^FictiveLoads::|^Level::"; +}; + +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/constraint.h b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/constraint.h new file mode 100644 index 0000000000..aba82e7f21 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/constraint.h @@ -0,0 +1,65 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include +#include + +namespace Antares::Optimization +{ +enum class ConstraintType +{ + binding_constraint_hourly, + binding_constraint_daily, + binding_constraint_weekly, + fictitious_load, + hydro_reservoir_level, + short_term_storage_level, + none +}; + +class Constraint +{ +public: + // Construct object + Constraint() = default; + Constraint(const std::string& input, const double slackValue); + + // Raw members + double getSlackValue() const; + + // Extract items, check consistency + std::size_t extractItems(); + std::string prettyPrint() const; + ConstraintType getType() const; + +private: + std::string mInput; + std::vector mItems; + double mSlackValue; + + // Get specific items + std::string getAreaName() const; + std::string getSTSName() const; + std::string getTimeStepInYear() const; + std::string getBindingConstraintName() const; +}; +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/report.h b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/report.h new file mode 100644 index 0000000000..6ebb919fb1 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/report.h @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include +#include +#include + +#include "constraint.h" + +namespace operations_research +{ +class MPVariable; +} + +namespace Antares::Optimization +{ +class InfeasibleProblemReport +{ +public: + InfeasibleProblemReport() = delete; + explicit InfeasibleProblemReport( + const std::vector& slackVariables); + void prettyPrint(); + +private: + void turnSlackVarsIntoConstraints( + const std::vector& slackVariables); + void sortConstraints(); + void trimConstraints(); + void extractItems(); + void logSuspiciousConstraints(); + + std::vector mConstraints; + std::map mTypes; + const unsigned int nbVariables = 10; +}; +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/unfeasibility-analysis.h b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/unfeasibility-analysis.h new file mode 100644 index 0000000000..6e2bd38403 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/unfeasibility-analysis.h @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include +#include + +namespace operations_research +{ +class MPSolver; +} + +namespace Antares::Optimization +{ + +/*! + * Interface for all elementary analysis. + */ +class UnfeasibilityAnalysis +{ +public: + UnfeasibilityAnalysis() = default; + virtual ~UnfeasibilityAnalysis() = default; + + virtual void run(operations_research::MPSolver* problem) = 0; + virtual void printReport() const = 0; + virtual std::string title() const = 0; + + bool hasDetectedInfeasibilityCause() const + { + return hasDetectedInfeasibilityCause_; + } + +protected: + bool hasDetectedInfeasibilityCause_ = false; +}; + +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h new file mode 100644 index 0000000000..88c37468b0 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include +#include +#include + +#include "unfeasibility-analysis.h" + +namespace operations_research +{ +class MPSolver; +} + +namespace Antares::Optimization +{ + +/*! + * In charge of anayzing the possible reasons for the unfeasibility of an optimization problem. + * + * The analyzer relies on the execution of possibly multiple UnfeasibilityAnalysis. + */ +class UnfeasiblePbAnalyzer +{ +public: + UnfeasiblePbAnalyzer() = delete; + explicit UnfeasiblePbAnalyzer(std::vector> analysisList); + void run(operations_research::MPSolver* problem); + void printReport() const; + +private: + std::vector> analysisList_; +}; + +std::unique_ptr makeUnfeasiblePbAnalyzer(); + +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h new file mode 100644 index 0000000000..6ac0d3624d --- /dev/null +++ b/src/solver/infeasible-problem-analysis/include/antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h @@ -0,0 +1,73 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include + +#include "unfeasibility-analysis.h" + +namespace Antares::Optimization +{ + +struct VariableBounds +{ + VariableBounds(const std::string& var_name, double low_bound, double up_bound): + name(var_name), + lowBound(low_bound), + upBound(up_bound) + { + } + + std::string name; + double lowBound; + double upBound; +}; + +/*! + * That particular analysis simply checks that all variables + * are within their minimum and maximum bounds. + */ +class VariablesBoundsConsistency: public UnfeasibilityAnalysis +{ +public: + VariablesBoundsConsistency() = default; + ~VariablesBoundsConsistency() override = default; + + void run(operations_research::MPSolver* problem) override; + void printReport() const override; + + std::string title() const override + { + return "Variables bounds consistency check"; + } + + const std::vector& incorrectVars() const + { + return incorrectVars_; + } + +private: + void storeIncorrectVariable(std::string name, double lowBound, double upBound); + bool foundIncorrectVariables(); + + std::vector incorrectVars_; +}; +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/problem.cpp b/src/solver/infeasible-problem-analysis/problem.cpp deleted file mode 100644 index c6d399b568..0000000000 --- a/src/solver/infeasible-problem-analysis/problem.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "problem.h" -#include "exceptions.h" - -#include -#include -#include - -using namespace operations_research; - -namespace Antares -{ -namespace Optimization -{ -InfeasibleProblemAnalysis::InfeasibleProblemAnalysis(const std::string& solverName, const PROBLEME_SIMPLEXE_NOMME* ProbSpx) -{ - mSolver - = std::unique_ptr(ProblemSimplexeNommeConverter(solverName, ProbSpx).Convert()); -} - -void InfeasibleProblemAnalysis::addSlackVariables() -{ - /* Optimization: - We assess that less than 1 every 3 constraint will match - the regex. If more, push_back may force the copy of memory blocks. - This should not happen in most cases. - */ - const unsigned int selectedConstraintsInverseRatio = 3; - mSlackVariables.reserve(mSolver->NumConstraints() / selectedConstraintsInverseRatio); - std::regex rgx(constraint_name_pattern); - const double infinity = MPSolver::infinity(); - for (MPConstraint* constraint : mSolver->constraints()) - { - if (std::regex_search(constraint->name(), rgx)) - { - if (constraint->lb() != -infinity) - { - const MPVariable* slack - = mSolver->MakeNumVar(0, infinity, constraint->name() + "::low"); - constraint->SetCoefficient(slack, 1.); - mSlackVariables.push_back(slack); - } - - if (constraint->ub() != infinity) - { - const MPVariable* slack - = mSolver->MakeNumVar(0, infinity, constraint->name() + "::up"); - constraint->SetCoefficient(slack, -1.); - mSlackVariables.push_back(slack); - } - } - } -} - -void InfeasibleProblemAnalysis::buildObjective() const -{ - MPObjective* objective = mSolver->MutableObjective(); - // Reset objective function - objective->Clear(); - // Only slack variables have a non-zero cost - for (const MPVariable* slack : mSlackVariables) - { - objective->SetCoefficient(slack, 1.); - } - objective->SetMinimization(); -} - -MPSolver::ResultStatus InfeasibleProblemAnalysis::Solve() const -{ - return mSolver->Solve(); -} - -InfeasibleProblemReport InfeasibleProblemAnalysis::produceReport() -{ - addSlackVariables(); - if (mSlackVariables.empty()) - { - throw SlackVariablesEmpty( - "Cannot generate infeasibility report: no constraints have been selected"); - } - buildObjective(); - const MPSolver::ResultStatus status = Solve(); - if ((status != MPSolver::OPTIMAL) && (status != MPSolver::FEASIBLE)) - { - throw ProblemResolutionFailed( - "Linear problem could not be solved, and infeasibility analysis could not help"); - } - return InfeasibleProblemReport(mSlackVariables); -} -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/infeasible-problem-analysis/problem.h b/src/solver/infeasible-problem-analysis/problem.h deleted file mode 100644 index d0e277492a..0000000000 --- a/src/solver/infeasible-problem-analysis/problem.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "../utils/ortools_utils.h" -#include "report.h" - -namespace Antares -{ -namespace Optimization -{ -class InfeasibleProblemAnalysis -{ -public: - InfeasibleProblemAnalysis() = delete; - explicit InfeasibleProblemAnalysis(const std::string& solverName, const PROBLEME_SIMPLEXE_NOMME* ProbSpx); - InfeasibleProblemReport produceReport(); - -private: - void buildObjective() const; - void addSlackVariables(); - operations_research::MPSolver::ResultStatus Solve() const; - - std::unique_ptr mSolver; - std::vector mSlackVariables; - const std::string constraint_name_pattern = "^AreaHydroLevel::|::hourly::|::daily::|::weekly::|^FictiveLoads::"; - -}; -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/infeasible-problem-analysis/report.cpp b/src/solver/infeasible-problem-analysis/report.cpp index 96719116a7..28e72109bf 100644 --- a/src/solver/infeasible-problem-analysis/report.cpp +++ b/src/solver/infeasible-problem-analysis/report.cpp @@ -1,36 +1,77 @@ -#include "report.h" -#include "constraint.h" -#include +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include "antares/solver/infeasible-problem-analysis/report.h" + #include +#include +#include "antares/solver/infeasible-problem-analysis/constraint.h" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +#include "ortools/linear_solver/linear_solver.h" +#pragma GCC diagnostic pop + +using namespace operations_research; + static bool compareSlackSolutions(const Antares::Optimization::Constraint& a, const Antares::Optimization::Constraint& b) { return a.getSlackValue() > b.getSlackValue(); } -namespace Antares -{ -namespace Optimization +namespace Antares::Optimization { InfeasibleProblemReport::InfeasibleProblemReport( - const std::vector& slackVariables) + const std::vector& slackVariables) +{ + turnSlackVarsIntoConstraints(slackVariables); + sortConstraints(); + trimConstraints(); +} + +void InfeasibleProblemReport::turnSlackVarsIntoConstraints( + const std::vector& slackVariables) { - for (const operations_research::MPVariable* slack : slackVariables) + for (const MPVariable* slack: slackVariables) { - append(slack->name(), slack->solution_value()); + mConstraints.emplace_back(slack->name(), slack->solution_value()); } - trim(); } -void InfeasibleProblemReport::append(const std::string& constraintName, double value) +void InfeasibleProblemReport::sortConstraints() { - mConstraints.emplace_back(constraintName, value); + std::sort(std::begin(mConstraints), std::end(mConstraints), ::compareSlackSolutions); +} + +void InfeasibleProblemReport::trimConstraints() +{ + if (nbVariables <= mConstraints.size()) + { + mConstraints.resize(nbVariables); + } } void InfeasibleProblemReport::extractItems() { - for (auto& c : mConstraints) + for (auto& c: mConstraints) { if (c.extractItems() == 0) { @@ -43,7 +84,7 @@ void InfeasibleProblemReport::extractItems() void InfeasibleProblemReport::logSuspiciousConstraints() { Antares::logs.error() << "The following constraints are suspicious (first = most suspicious)"; - for (const auto& c : mConstraints) + for (const auto& c: mConstraints) { Antares::logs.error() << c.prettyPrint(); } @@ -57,6 +98,13 @@ void InfeasibleProblemReport::logSuspiciousConstraints() { Antares::logs.error() << "* Last resort shedding status,"; } + if (mTypes[ConstraintType::short_term_storage_level] > 0) + { + Antares::logs.error() + << "* Short-term storage reservoir level impossible to manage. Please check inflows, " + "lower & upper curves and initial level (if prescribed),"; + } + const unsigned int bcCount = mTypes[ConstraintType::binding_constraint_hourly] + mTypes[ConstraintType::binding_constraint_daily] + mTypes[ConstraintType::binding_constraint_weekly]; @@ -74,14 +122,4 @@ void InfeasibleProblemReport::prettyPrint() logSuspiciousConstraints(); } -void InfeasibleProblemReport::trim() -{ - std::sort(std::begin(mConstraints), std::end(mConstraints), ::compareSlackSolutions); - if (nbVariables <= mConstraints.size()) - { - mConstraints.resize(nbVariables); - } -} - -} // namespace Optimization -} // namespace Antares +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/report.h b/src/solver/infeasible-problem-analysis/report.h deleted file mode 100644 index db15744f19..0000000000 --- a/src/solver/infeasible-problem-analysis/report.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "constraint.h" -#include "ortools/linear_solver/linear_solver.h" - -namespace Antares -{ -namespace Optimization -{ -class InfeasibleProblemReport -{ -public: - InfeasibleProblemReport() = delete; - explicit InfeasibleProblemReport( - const std::vector& slackVariables); - void prettyPrint(); - -private: - void trim(); - void extractItems(); - void logSuspiciousConstraints(); - void append(const std::string& constraintName, double value); - std::vector mConstraints; - std::map mTypes; - const unsigned int nbVariables = 10; -}; -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.cpp b/src/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.cpp new file mode 100644 index 0000000000..c0e506ea91 --- /dev/null +++ b/src/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.cpp @@ -0,0 +1,82 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include "antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h" + +#include +#include + +#include +#include "antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h" +#include "antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h" + +using namespace operations_research; + +namespace Antares::Optimization +{ + +std::unique_ptr makeUnfeasiblePbAnalyzer() +{ + std::vector> analysisList; + analysisList.push_back(std::make_unique()); + analysisList.push_back(std::make_unique()); + + return std::make_unique(std::move(analysisList)); +} + +UnfeasiblePbAnalyzer::UnfeasiblePbAnalyzer( + std::vector> analysisList): + analysisList_(std::move(analysisList)) +{ +} + +void UnfeasiblePbAnalyzer::run(MPSolver* problem) +{ + logs.info(); + logs.info() << "Solver: Starting unfeasibility analysis..."; + + for (auto& analysis: analysisList_) + { + logs.info(); + logs.info() << analysis->title() << " : running..."; + analysis->run(problem); + if (analysis->hasDetectedInfeasibilityCause()) + { + return; + } + + logs.notice() << analysis->title() << " : nothing detected."; + } +} + +void UnfeasiblePbAnalyzer::printReport() const +{ + for (auto& analysis: analysisList_) + { + if (analysis->hasDetectedInfeasibilityCause()) + { + logs.info() << analysis->title() << " : printing report"; + analysis->printReport(); + return; + } + } + logs.notice() << "Solver: unfeasibility analysis : could not find the cause of unfeasibility."; +} +} // namespace Antares::Optimization diff --git a/src/solver/infeasible-problem-analysis/variables-bounds-consistency.cpp b/src/solver/infeasible-problem-analysis/variables-bounds-consistency.cpp new file mode 100644 index 0000000000..ab8c889d6d --- /dev/null +++ b/src/solver/infeasible-problem-analysis/variables-bounds-consistency.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include "antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h" + +#include +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +#include "ortools/linear_solver/linear_solver.h" +#pragma GCC diagnostic pop + +using namespace operations_research; + +namespace Antares::Optimization +{ + +void VariablesBoundsConsistency::run(MPSolver* problem) +{ + for (const auto& var: problem->variables()) + { + double lowBound = var->lb(); + double upBound = var->ub(); + std::string name = var->name(); + if (lowBound > upBound) + { + storeIncorrectVariable(name, lowBound, upBound); + } + } + + if (foundIncorrectVariables()) + { + hasDetectedInfeasibilityCause_ = true; + } +} + +void VariablesBoundsConsistency::storeIncorrectVariable(std::string name, + double lowBound, + double upBound) +{ + incorrectVars_.push_back(VariableBounds(name, lowBound, upBound)); +} + +bool VariablesBoundsConsistency::foundIncorrectVariables() +{ + return !incorrectVars_.empty(); +} + +void VariablesBoundsConsistency::printReport() const +{ + for (const auto& var: incorrectVars_) + { + logs.notice() << var.name << " : low bound = " << var.lowBound + << ", up bound = " << var.upBound; + } +} +} // namespace Antares::Optimization diff --git a/src/solver/lps/CMakeLists.txt b/src/solver/lps/CMakeLists.txt new file mode 100644 index 0000000000..8c3e48cab0 --- /dev/null +++ b/src/solver/lps/CMakeLists.txt @@ -0,0 +1,24 @@ +set(PROJ lps) +set(HEADERS + include/antares/solver/lps/LpsFromAntares.h +) +set(SRC_PROJ + ${HEADERS} + LpsFromAntares.cpp +) +source_group("solver\\lps" FILES ${SRC_PROJ}) + +add_library(${PROJ}) +target_sources(${PROJ} PRIVATE + ${SRC_PROJ} +) +add_library(Antares::${PROJ} ALIAS ${PROJ}) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/solver/lps/LpsFromAntares.cpp b/src/solver/lps/LpsFromAntares.cpp new file mode 100644 index 0000000000..a32484038d --- /dev/null +++ b/src/solver/lps/LpsFromAntares.cpp @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/lps/LpsFromAntares.h" + +namespace Antares::Solver +{ +bool LpsFromAntares::empty() const +{ + return constantProblemData.VariablesCount == 0 || weeklyProblems.empty(); +} + +void LpsFromAntares::setConstantData(const ConstantDataFromAntares& data) +{ + constantProblemData = data; +} + +void LpsFromAntares::addWeeklyData(WeeklyProblemId id, const WeeklyDataFromAntares& data) +{ + weeklyProblems.emplace(id, data); +} + +const WeeklyDataFromAntares& LpsFromAntares::weeklyData(WeeklyProblemId id) const +{ + auto it = weeklyProblems.find(id); + if (it == weeklyProblems.end()) + { + return WeeklyDataFromAntares(); // TODO Better error handling + } + return it->second; +} + +size_t LpsFromAntares::weekCount() const noexcept +{ + return weeklyProblems.size(); +} + +} // namespace Antares::Solver diff --git a/src/solver/lps/include/antares/solver/lps/LpsFromAntares.h b/src/solver/lps/include/antares/solver/lps/LpsFromAntares.h new file mode 100644 index 0000000000..f85d99b060 --- /dev/null +++ b/src/solver/lps/include/antares/solver/lps/LpsFromAntares.h @@ -0,0 +1,149 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include +#include +#include +#include +#include + +namespace Antares::Solver +{ + +/** + * @struct WeeklyProblemId + * @brief The WeeklyProblemId struct is used to identify a weekly problem by year and week. + */ +struct WeeklyProblemId +{ + unsigned int year = 0; + unsigned int week = 0; + // Order of comparison is order of member declaration + auto operator<=>(const WeeklyProblemId& other) const = default; +}; + +// Type de données inutile car les matrices de tous les pbs Weekly sont +// identiques. Cela pourra changer à l'avenir si des coefficients de contraintes +// couplantes peuvent varier au cours du temps (ex: rendement d'une pompe à +// chaleur qui varie selon la température, FlowBased ?, etc) +/** + * @class ConstantDataFromAntares + * @brief The ConstantDataFromAntares class is used to store constant data across all weeks + * of Antares problems. + */ +struct ConstantDataFromAntares +{ + unsigned VariablesCount = 0; // Mathématiquement : Nb colonnes de la matrice, + // Informatiquement = TypeDeVariable.size() + unsigned ConstraintesCount = 0; // Mathématiqument : Nb lignes de la matrice, + // Informatiquement = Mdeb.size() + unsigned CoeffCount = 0; // Mathématiquement : Nb coeffs non nuls de la + // matrice, Informatiquement = Nbterm.size() = + // IndicesColonnes.size()= + // CoefficientsDeLaMatriceDesContraintes.size() + + std::vector VariablesType; // Variables entières ou biniaires + std::vector Mdeb; // Indique dans les indices dans le vecteur IndicesColonnes qui + // correspondent au début de chaque ligne. Ex : Mdeb[3] = 8 et + // Mdeb[4] = 13 -> Les termes IndicesColonnes[8] à + // IndicesColonnes[12] correspondent à des Id de colonnes de la + // ligne 3 de la matrice (en supposant que les lignes sont indexées + // à partir de 0) + std::vector NotNullTermCount; // Nombre de termes non nuls sur chaque ligne. + // Inutile car NbTerm[i] = Mdeb[i+1] - Mdeb[i] + std::vector ColumnIndexes; // Id des colonnes des termes de + // CoefficientsDeLaMatriceDesContraintes : Ex + // IndicesColonnes[3] = 8 -> + // CoefficientsDeLaMatriceDesContraintes[8] donne la + // valeur du terme de la colonne 8, et de la ligne i où + // i est tel que Mdeb[i] <= 3 < Mdeb[i+1] + std::vector ConstraintsMatrixCoeff; // Coefficients de la matrice + + std::vector VariablesMeaning; + std::vector ConstraintsMeaning; + + auto operator<=>(const ConstantDataFromAntares& other) const = default; +}; + +/** + * @class WeeklyDataFromAntares + * @brief The WeeklyDataFromAntares class is used to store weekly data for an Antares Problem. + */ +struct WeeklyDataFromAntares +{ + std::vector Direction; // Sens de la contrainte : < ou > ou =, taille = + // NombreDeContraintes + std::vector Xmax; // Borne max des variables de la semaine + // considérée, taille = NombreDeVariables + std::vector Xmin; // Borne min des variables de la semaine + // considérée, taille = NombreDeVariables + std::vector LinearCost; // Coefficients du vecteur de coût de la fonction objectif, + // taille = NombreDeVariables + std::vector RHS; // Vecteur des second membre des contraintes, taille = + // NombreDeContraintes + std::string name; + + std::vector variables; + std::vector constraints; + + auto operator<=>(const WeeklyDataFromAntares& other) const = default; +}; + +using WeeklyDataByYearWeek = std::map; + +/** + * @class LpsFromAntares + * @brief The LpsFromAntares class is used to manage the constant and weekly data for Antares + * problems. + */ +class LpsFromAntares +{ +public: + /* + * @brief Checks if the LpsFromAntares object is empty. + * Emptiness is defined by either the constant data or the weekly data being empty. + */ + bool empty() const; + /* + * @brief Replaces the constant data in the LpsFromAntares object. + * Copy happens + */ + void setConstantData(const ConstantDataFromAntares& data); + /* + * @brief Adds weekly data to the LpsFromAntares object. + */ + void addWeeklyData(WeeklyProblemId id, const WeeklyDataFromAntares& data); + /* + * @brief Retrieves weekly data from the LpsFromAntares object. + */ + const WeeklyDataFromAntares& weeklyData(WeeklyProblemId id) const; + /* + * @brief Retrieves the number of weeks in the LpsFromAntares object. + */ + [[nodiscard]] size_t weekCount() const noexcept; + + ConstantDataFromAntares constantProblemData; + WeeklyDataByYearWeek weeklyProblems; +}; + +} // namespace Antares::Solver diff --git a/src/solver/main.cpp b/src/solver/main.cpp index 367278b7b9..169b29321a 100644 --- a/src/solver/main.cpp +++ b/src/solver/main.cpp @@ -1,52 +1,46 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include -#include "application.h" +#include #include - -#include +#include +#include #include -#include +#include "antares/application/application.h" using namespace Antares; using namespace Yuni; #define SEP Yuni::IO::Separator -namespace { +namespace +{ -const char* const GPL_ANNOUNCEMENT +const char* const MPL_ANNOUNCEMENT = "Copyright 2007-2023 RTE - Authors: The Antares_Simulator Team \n" "\n" "Antares_Simulator is free software : you can redistribute it and / or modify\n" - "it under the terms of the GNU General Public License as published by\n" - "the Free Software Foundation, either version 3 of the License, or\n" + "it under the terms of the Mozilla Public Licence 2.0 as published by\n" + "the Mozilla Foundation, either version 2 of the License, or\n" "(at your option) any later version.\n" "\n" "There are special exceptions to the terms and conditions of the\n" @@ -57,10 +51,10 @@ const char* const GPL_ANNOUNCEMENT "Antares_Simulator is distributed in the hope that it will be useful, \n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the\n" - "GNU General Public License for more details.\n" + "Mozilla Public Licence 2.0 for more details.\n" "\n" - "You should have received a copy of the GNU General Public License\n" - "along with Antares_Simulator.If not, see .\n" + "You should have received a copy of the Mozilla Public Licence 2.0\n" + "along with Antares_Simulator.If not, see .\n" "\n"; const char* const ANTARES_LOGO = "\n\n" @@ -106,22 +100,24 @@ void logAbortion() } } -} +} // namespace /*! ** \brief main */ int main(int argc, char** argv) { - try { - + try + { logs.info(ANTARES_LOGO); - logs.info(GPL_ANNOUNCEMENT); + logs.info(MPL_ANNOUNCEMENT); // Name of the running application for the logger logs.applicationName("solver"); if (not memory.initializeTemporaryFolder()) + { throw FatalError("Could not initialize temporary folder"); + } // locale InitializeDefaultLocale(); @@ -134,22 +130,22 @@ int main(int argc, char** argv) application.execute(); application.writeExectutionInfo(); - // to avoid a bug from wxExecute, we should wait a little before returning - SuspendMilliSeconds(200 /*ms*/); - return EXIT_SUCCESS; } - catch (const std::bad_alloc& exc) { + catch (const std::bad_alloc& exc) + { logs.fatal() << exc.what(); logAbortion(); return ALLOCATION_FAILURE_EXIT_CODE; } - catch (const std::exception& exc) { + catch (const std::exception& exc) + { logs.fatal() << exc.what(); logAbortion(); return EXIT_FAILURE; } - catch (...) { + catch (...) + { logs.fatal() << "An unexpected error occurred."; logAbortion(); return EXIT_FAILURE; diff --git a/src/solver/main/CMakeLists.txt b/src/solver/main/CMakeLists.txt deleted file mode 100644 index 592a0a87e7..0000000000 --- a/src/solver/main/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -set(SRC_SOLVER_MAIN_ECONOMY economy.cpp) -set(SRC_SOLVER_MAIN_ADEQUACY adequacy.cpp) - -#if(MSVC) -# set_source_files_properties(economy.cpp PROPERTIES COMPILE_FLAGS " /MP") -# set_source_files_properties(adequacy-draft.cpp PROPERTIES COMPILE_FLAGS " /MP") -#endif(MSVC) - - - -add_library(antares-solver-main-adequacy ${SRC_SOLVER_MAIN_ADEQUACY}) -target_link_libraries(antares-solver-main-adequacy - PRIVATE - Antares::infoCollection - antares-solver-simulation -) - -add_library(antares-solver-main-economy ${SRC_SOLVER_MAIN_ECONOMY}) -target_link_libraries(antares-solver-main-economy - PRIVATE - Antares::infoCollection - antares-solver-simulation -) diff --git a/src/solver/main/adequacy.cpp b/src/solver/main/adequacy.cpp deleted file mode 100644 index 899e26ccd2..0000000000 --- a/src/solver/main/adequacy.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "../application.h" -#include "../simulation/solver.h" -#include "../simulation/adequacy.h" -#include -#include - -namespace Antares -{ -namespace Solver -{ -void Application::runSimulationInAdequacyMode() -{ - // Type of the simulation - typedef Solver::Simulation::ISimulation SimulationType; - SimulationType simulation(*pStudy, pSettings, pDurationCollector, *resultWriter); - simulation.checkWriter(); - simulation.run(); - - if (!(pSettings.noOutput || pSettings.tsGeneratorsOnly)) - { - Benchmarking::Timer timer; - simulation.writeResults(/*synthesis:*/ true); - timer.stop(); - pDurationCollector.addDuration("synthesis_export", timer.get_duration()); - - this->pOptimizationInfo = simulation.getOptimizationInfo(); - } -} -} // namespace Solver -} // namespace Antares diff --git a/src/solver/main/economy.cpp b/src/solver/main/economy.cpp deleted file mode 100644 index bc42b7e563..0000000000 --- a/src/solver/main/economy.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "../application.h" -#include "../simulation/solver.h" -#include "../simulation/economy.h" -#include -#include - -namespace Antares -{ -namespace Solver -{ -void Application::runSimulationInEconomicMode() -{ - // Type of the simulation - typedef Solver::Simulation::ISimulation SimulationType; - SimulationType simulation(*pStudy, pSettings, pDurationCollector, *resultWriter); - simulation.checkWriter(); - simulation.run(); - - if (!(pSettings.noOutput || pSettings.tsGeneratorsOnly)) - { - Benchmarking::Timer timer; - simulation.writeResults(/*synthesis:*/ true); - timer.stop(); - pDurationCollector.addDuration("synthesis_export", timer.get_duration()); - - this->pOptimizationInfo = simulation.getOptimizationInfo(); - } -} -} // namespace Solver -} // namespace Antares diff --git a/src/solver/misc/CMakeLists.txt b/src/solver/misc/CMakeLists.txt new file mode 100644 index 0000000000..7ac136c669 --- /dev/null +++ b/src/solver/misc/CMakeLists.txt @@ -0,0 +1,39 @@ +set(PROJ misc) +set(HEADERS + include/antares/solver/misc/cholesky.h + include/antares/solver/misc/cholesky.hxx + include/antares/solver/misc/matrix-dp-make.h + include/antares/solver/misc/matrix-dp-make.hxx + include/antares/solver/misc/options.h + include/antares/solver/misc/system-memory.h + include/antares/solver/misc/write-command-line.h +) +set(SRC_MISC + ${HEADERS} + options.cpp + system-memory.cpp + write-command-line.cpp +) +source_group("solver\\misc" FILES ${SRC_MISC}) + +add_library(${PROJ} ${SRC_MISC}) +add_library(Antares::${PROJ} ALIAS ${PROJ}) + +target_link_libraries(${PROJ} + PRIVATE + Antares::logs + Antares::exception + Antares::utils + PUBLIC + yuni-static-core + Antares::study +) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/solver/misc/cholesky.h b/src/solver/misc/cholesky.h deleted file mode 100644 index 550acc3151..0000000000 --- a/src/solver/misc/cholesky.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_MISC_CHOLESKY_H__ -#define __ANTARES_SOLVER_MISC_CHOLESKY_H__ - -#include -#include -#include - -namespace Antares -{ -namespace Solver -{ -/*! -** \brief Factorisation de Cholesky d'une matrice A symetrique reelle -** -** Factorisation de Cholesky d'une matrice A symetrique reelle dont ignore si -** elle est ou non semi definie positive. -** Si A est definie positive ou semi-definie positive on acheve la factorisation -** Si A n'est pas definie positive on arrete la factorisation en cours de route -** On retourne un code qui indique si A est définie positive ou non -** -** LtL = A si A est semi-definie positive -** \param A matrice NxN a factoriser -** -** \param L A bi-dimensional array of the form T** -** \param A A bi-dimensional array of the form T** -** \param size The number of process -** \param temp A temporary array for calculations (with at least @size items) -** \return true si A n'est ni definie positive ni semi-positive, false sinon -*/ -template -bool Cholesky(U1& L, U2& A, uint size, T* temp); - -} // namespace Solver -} // namespace Antares - -#include "cholesky.hxx" - -#endif // __ANTARES_SOLVER_MISC_CHOLESKY_H__ diff --git a/src/solver/misc/cholesky.hxx b/src/solver/misc/cholesky.hxx deleted file mode 100644 index dbee7cf513..0000000000 --- a/src/solver/misc/cholesky.hxx +++ /dev/null @@ -1,100 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -//! Precision sur la factorisation des matrices -#define ANTARES_CHOLESKY_EPSIMIN ((T)1.0e-9) - -namespace Antares -{ -namespace Solver -{ -template -bool Cholesky(U1& L, U2& A, uint size, T* temp) -{ - using namespace Yuni; - - for (uint i = 0; i != size; ++i) - temp[i] = 0; - - T som; - - for (uint i = 0; i < size; ++i) - { - typename MatrixSubColumn::Type Li = L[i]; - - // on calcule d'abord L[i][i] - som = A[i][i]; - for (int j = 0; j <= (int)(i - 1); ++j) - som -= Li[j] * Li[j]; - - if (som > ANTARES_CHOLESKY_EPSIMIN) - { - Li[i] = Math::SquareRootNoCheck(som); - - // maintenant on cherche L[k][i], k > i. - for (uint k = i + 1; k < size; ++k) - { - typename MatrixSubColumn::Type Lk = L[k]; - typename MatrixSubColumn::Type Ak = A[k]; - - if (temp[k] == Ak[k]) - { - Lk[i] = 0; - } - else - { - som = Ak[i]; - for (int j = 0; j <= (int)(i - 1); ++j) - som -= Li[j] * Lk[j]; - - Lk[i] = som / Li[i]; - temp[k] += Lk[i] * Lk[i]; - - // si temp[k] = A[k][k] la matrice n'est pas dp mais il est encore possible - // qu'elle soit sdp. - // si temp > A[k][k] alors il est certain que A n'est ni sdp ni dp donc on - // arrete le calcul - if (temp[k] > Ak[k]) - return true; - } - } - } - else - { - // annule le reste de la colonne - for (uint k = i; k != size; ++k) - L[k][i] = 0; - } - } - - return false; -} - -} // namespace Solver -} // namespace Antares - -#undef ANTARES_CHOLESKY_EPSIMIN diff --git a/src/solver/misc/include/antares/solver/misc/cholesky.h b/src/solver/misc/include/antares/solver/misc/cholesky.h new file mode 100644 index 0000000000..8ff9f97c81 --- /dev/null +++ b/src/solver/misc/include/antares/solver/misc/cholesky.h @@ -0,0 +1,59 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_MISC_CHOLESKY_H__ +#define __ANTARES_SOLVER_MISC_CHOLESKY_H__ + +#include +#include + +#include + +namespace Antares +{ +namespace Solver +{ +/*! +** \brief Factorisation de Cholesky d'une matrice A symetrique reelle +** +** Factorisation de Cholesky d'une matrice A symetrique reelle dont ignore si +** elle est ou non semi definie positive. +** Si A est definie positive ou semi-definie positive on acheve la factorisation +** Si A n'est pas definie positive on arrete la factorisation en cours de route +** On retourne un code qui indique si A est définie positive ou non +** +** LtL = A si A est semi-definie positive +** \param A matrice NxN a factoriser +** +** \param L A bi-dimensional array of the form T** +** \param A A bi-dimensional array of the form T** +** \param size The number of process +** \param temp A temporary array for calculations (with at least @size items) +** \return true si A n'est ni definie positive ni semi-positive, false sinon +*/ +template +bool Cholesky(U1& L, U2& A, uint size, T* temp); + +} // namespace Solver +} // namespace Antares + +#include "cholesky.hxx" + +#endif // __ANTARES_SOLVER_MISC_CHOLESKY_H__ diff --git a/src/solver/misc/include/antares/solver/misc/cholesky.hxx b/src/solver/misc/include/antares/solver/misc/cholesky.hxx new file mode 100644 index 0000000000..26c333d785 --- /dev/null +++ b/src/solver/misc/include/antares/solver/misc/cholesky.hxx @@ -0,0 +1,106 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +//! Precision sur la factorisation des matrices +#define ANTARES_CHOLESKY_EPSIMIN ((T)1.0e-9) + +#include + +namespace Antares +{ +namespace Solver +{ +template +bool Cholesky(U1& L, U2& A, uint size, T* temp) +{ + using namespace Yuni; + + for (uint i = 0; i != size; ++i) + { + temp[i] = 0; + } + + T som; + + for (uint i = 0; i < size; ++i) + { + typename MatrixSubColumn::Type Li = L[i]; + + // on calcule d'abord L[i][i] + som = A[i][i]; + for (int j = 0; j <= (int)(i - 1); ++j) + { + som -= Li[j] * Li[j]; + } + + if (som > ANTARES_CHOLESKY_EPSIMIN) + { + Li[i] = std::sqrt(som); + + // maintenant on cherche L[k][i], k > i. + for (uint k = i + 1; k < size; ++k) + { + typename MatrixSubColumn::Type Lk = L[k]; + typename MatrixSubColumn::Type Ak = A[k]; + + if (temp[k] == Ak[k]) + { + Lk[i] = 0; + } + else + { + som = Ak[i]; + for (int j = 0; j <= (int)(i - 1); ++j) + { + som -= Li[j] * Lk[j]; + } + + Lk[i] = som / Li[i]; + temp[k] += Lk[i] * Lk[i]; + + // si temp[k] = A[k][k] la matrice n'est pas dp mais il est encore possible + // qu'elle soit sdp. + // si temp > A[k][k] alors il est certain que A n'est ni sdp ni dp donc on + // arrete le calcul + if (temp[k] > Ak[k]) + { + return true; + } + } + } + } + else + { + // annule le reste de la colonne + for (uint k = i; k != size; ++k) + { + L[k][i] = 0; + } + } + } + + return false; +} + +} // namespace Solver +} // namespace Antares + +#undef ANTARES_CHOLESKY_EPSIMIN diff --git a/src/solver/misc/matrix-dp-make.h b/src/solver/misc/include/antares/solver/misc/matrix-dp-make.h similarity index 75% rename from src/solver/misc/matrix-dp-make.h rename to src/solver/misc/include/antares/solver/misc/matrix-dp-make.h index c00f23ba1d..75f8f29c16 100644 --- a/src/solver/misc/matrix-dp-make.h +++ b/src/solver/misc/include/antares/solver/misc/matrix-dp-make.h @@ -1,34 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_SOLVER_MISC_MATRIX_DP_MAKE_H__ #define __ANTARES_SOLVER_MISC_MATRIX_DP_MAKE_H__ #include #include + #include "cholesky.h" namespace Antares diff --git a/src/solver/misc/matrix-dp-make.hxx b/src/solver/misc/include/antares/solver/misc/matrix-dp-make.hxx similarity index 80% rename from src/solver/misc/matrix-dp-make.hxx rename to src/solver/misc/include/antares/solver/misc/matrix-dp-make.hxx index bc2b0e014c..6ef2649a92 100644 --- a/src/solver/misc/matrix-dp-make.hxx +++ b/src/solver/misc/include/antares/solver/misc/matrix-dp-make.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_SOLVER_MISC_MATRIX_DP_MAKE_HXX__ #define __ANTARES_SOLVER_MISC_MATRIX_DP_MAKE_HXX__ @@ -52,7 +46,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) for (uint j = 0; j != size; ++j) { for (uint k = 0; k <= j; ++k) + { B[j][k] = A[j][k]; + } } // A est definie positive ou semi-dp: pas de redressement à faire et LtL = A return T(1); @@ -60,7 +56,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) // Il faut trouver B definie positive et proche de A for (uint j = 0; j != size; ++j) + { B[j][j] = T(1); + } uint compteur = 0; do @@ -73,7 +71,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) for (uint j = 0; j != size; ++j) { for (uint k = 0; k < j; ++k) + { B[j][k] = A[j][k] * r + C[j][k] * (T(1) - r); + } } } else @@ -81,7 +81,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) for (uint j = 0; j != size; ++j) { for (uint k = 0; k < j; ++k) + { B[j][k] = A[j][k] * r; // + C[j][k] * (T(1) - r); + } } } @@ -106,7 +108,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) for (uint j = 0; j != size; ++j) { for (uint k = 0; k < j; ++k) + { B[j][k] = A[j][k] * rho + C[j][k] * (T(1) - rho); + } } } else @@ -114,7 +118,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) for (uint j = 0; j != size; ++j) { for (uint k = 0; k < j; ++k) + { B[j][k] = A[j][k] * rho; // + C[j][k] * (T(1) - rho); + } } } Cholesky(L, B, size, temp); @@ -124,7 +130,9 @@ T MatrixDPMake(U1& L, U2& A, U3& B, U4& C, uint size, T* temp, bool CIsIdentity) // avoid infinite loops if (++compteur > maxLoopCount) // si on n'a pas eu convergence C n'est pas valide + { return T(-1); + } } while (true); return rho; diff --git a/src/solver/misc/include/antares/solver/misc/options.h b/src/solver/misc/include/antares/solver/misc/options.h new file mode 100644 index 0000000000..00daf5aec7 --- /dev/null +++ b/src/solver/misc/include/antares/solver/misc/options.h @@ -0,0 +1,79 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_MISC_GETOPT_H__ +#define __SOLVER_MISC_GETOPT_H__ + +#include + +#include +#include +#include + +#include +#include + +/*! +** \brief Command line settings for launching the simulation +*/ +class Settings +{ +public: + void checkAndSetStudyFolder(const std::string& folder); + void reset(); + + //! Where is my study + YString studyFolder; + //! Name of the simulation + Yuni::CString<150, false> simulationName; + //! Comment file + std::string commentFile; + + //! Simplex optimizatio range + Yuni::CString<32, false> simplexOptimRange; + + //! Ignore error/warnings + int ignoreWarningsErrors = 0; + //! Ignore constraints + bool ignoreConstraints = false; + + //! Run the TS generator only + bool tsGeneratorsOnly = false; + + //! True to disable the writing in the output folder + bool noOutput = false; + //! Progression + bool displayProgression = false; + + Yuni::String PID; + bool forceZipOutput = false; + Antares::Solver::Optimization::OptimizationOptions optOptions; +}; // class Settings + +/*! +** \brief Interprete options given in command line +*/ +std::unique_ptr CreateParser(Settings& settings, + Antares::Data::StudyLoadOptions& options); + +void checkAndCorrectSettingsAndOptions(Settings& settings, Data::StudyLoadOptions& options); + +void checkOrtoolsSolver(const Antares::Solver::Optimization::OptimizationOptions& optOptions); +#endif /* __SOLVER_MISC_GETOPT_H__ */ diff --git a/src/solver/misc/include/antares/solver/misc/system-memory.h b/src/solver/misc/include/antares/solver/misc/system-memory.h new file mode 100644 index 0000000000..e61a4329d2 --- /dev/null +++ b/src/solver/misc/include/antares/solver/misc/system-memory.h @@ -0,0 +1,40 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_MISC_SYSTEM_MEMORY_H__ +#define __SOLVER_MISC_SYSTEM_MEMORY_H__ + +#include +#include + +class SystemMemoryLogger: public Yuni::Thread::Timer +{ +public: + SystemMemoryLogger(); + virtual ~SystemMemoryLogger(); + +protected: + virtual bool onInterval(uint); + + virtual bool onStarting(); + +}; // class SystemMemoryLogguer + +#endif /* __SOLVER_MISC_SYSTEM_MEMORY_H__ */ diff --git a/src/solver/misc/include/antares/solver/misc/write-command-line.h b/src/solver/misc/include/antares/solver/misc/write-command-line.h new file mode 100644 index 0000000000..fa779ac257 --- /dev/null +++ b/src/solver/misc/include/antares/solver/misc/write-command-line.h @@ -0,0 +1,26 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +namespace Antares::Solver +{ +void WriteCommandLineIntoLogs(int argc, char** argv); +} diff --git a/src/solver/misc/options.cpp b/src/solver/misc/options.cpp index 918f73724b..960b0dda6c 100644 --- a/src/solver/misc/options.cpp +++ b/src/solver/misc/options.cpp @@ -1,96 +1,75 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/misc/options.h" -#include -#include -#include -#include - -#include -#include +#include #include -#include +#include #include -#include - -#include "options.h" -#include "../config.h" +#include -#include "../../config.h" +#include +#include #include #include -#include -#include - -#include "utils/ortools_utils.h" +#include +#include +#include "antares/antares/Enum.hpp" +#include "antares/config/config.h" +#include "antares/solver/utils/ortools_utils.h" -using namespace Yuni; using namespace Antares; using namespace Antares::Data; -static std::string availableOrToolsSolversString() -{ - const std::list availableSolverList = getAvailableOrtoolsSolverName(); - std::string availableSolverListStr; - for (auto it = availableSolverList.begin(); it != availableSolverList.end(); it++) - { - availableSolverListStr += *it + ";"; - } - // Remove last semicolumn - if (!availableSolverListStr.empty()) - availableSolverListStr.pop_back(); - return availableSolverListStr; -} - -std::unique_ptr CreateParser(Settings& settings, - Antares::Data::StudyLoadOptions& options) +std::unique_ptr CreateParser(Settings& settings, StudyLoadOptions& options) { settings.reset(); - auto parser = std::unique_ptr(new GetOpt::Parser()); + auto parser = std::make_unique(); - parser->addParagraph(String() << "Antares Solver v" << ANTARES_VERSION_PUB_STR << "\n"); + parser->addParagraph(Yuni::String() << "Antares Solver v" << ANTARES_VERSION_PUB_STR << "\n"); // Simulation mode parser->addParagraph("Simulation"); // --input parser->addFlag(options.studyFolder, 'i', "input", "Study folder"); // --expansion - parser->addFlag( - options.forceExpansion, ' ', "expansion", "Force the simulation in expansion mode"); + parser->addFlag(options.forceExpansion, + ' ', + "expansion", + "Force the simulation in expansion mode"); // --economy parser->addFlag(options.forceEconomy, ' ', "economy", "Force the simulation in economy mode"); // --adequacy - parser->addFlag( - options.forceAdequacy, ' ', "adequacy", "Force the simulation in adequacy mode"); + parser->addFlag(options.forceAdequacy, + ' ', + "adequacy", + "Force the simulation in adequacy mode"); // --parallel - parser->addFlag( - options.enableParallel, ' ', "parallel", "Enable the parallel computation of MC years"); + parser->addFlag(options.enableParallel, + ' ', + "parallel", + "Enable the parallel computation of MC years"); // --force-parallel parser->add(options.maxNbYearsInParallel, ' ', @@ -99,24 +78,39 @@ std::unique_ptr CreateParser(Settings& settings, // add option for ortools use // --use-ortools - parser->addFlag( - options.ortoolsUsed, ' ', "use-ortools", "Use ortools library to launch solver"); + parser->addFlag(options.optOptions.ortoolsUsed, + ' ', + "use-ortools", + "Use ortools library to launch solver"); //--ortools-solver - parser->add(options.ortoolsSolver, + parser->add(options.optOptions.ortoolsSolver, ' ', "ortools-solver", "Ortools solver used for simulation (only available with use-ortools " "option)\nAvailable solver list : " + availableOrToolsSolversString()); + //--xpress-parameters + parser->add( + options.optOptions.solverParameters, + ' ', + "solver-parameters", + "Set xpress solver specific parameters. The specified string must be wrapped into quotes: " + "--solver-parameters=\"param1 value1 param2 value2\". The syntax of parameters is solver " + "specfic, examples are given in Antares-Simulator online documentation."); + parser->addParagraph("\nParameters"); // --name - parser->add( - settings.simulationName, 'n', "name", "Set the name of the new simulation to VALUE"); + parser->add(settings.simulationName, + 'n', + "name", + "Set the name of the new simulation to VALUE"); // --generators-only - parser->addFlag( - settings.tsGeneratorsOnly, 'g', "generators-only", "Run the time-series generators only"); + parser->addFlag(settings.tsGeneratorsOnly, + 'g', + "generators-only", + "Run the time-series generators only"); // --comment-file parser->add(settings.commentFile, @@ -126,8 +120,10 @@ std::unique_ptr CreateParser(Settings& settings, // --force parser->addFlag(settings.ignoreWarningsErrors, 'f', "force", "Ignore all warnings at loading"); // --no-output - parser->addFlag( - settings.noOutput, ' ', "no-output", "Do not write the results in the output folder"); + parser->addFlag(settings.noOutput, + ' ', + "no-output", + "Do not write the results in the output folder"); // --year parser->add(options.nbYears, 'y', "year", "Override the number of MC years"); // --year-by-year @@ -174,21 +170,30 @@ std::unique_ptr CreateParser(Settings& settings, "named-mps-problems", "Export named constraints and variables in mps (both optim)."); + // --solver-logs + parser->addFlag(options.optOptions.solverLogs, ' ', "solver-logs", "Print solver logs."); + parser->addParagraph("\nMisc."); // --progress - parser->addFlag( - settings.displayProgression, ' ', "progress", "Display the progress of each task"); + parser->addFlag(settings.displayProgression, + ' ', + "progress", + "Display the progress of each task"); // --pid parser->add(settings.PID, 'p', "pid", "Specify the file where to write the process ID"); // --list-solvers - parser->addFlag( - options.listSolvers, 'l', "list-solvers", "List available OR-Tools solvers, then exit."); + parser->addFlag(options.listSolvers, + 'l', + "list-solvers", + "List available OR-Tools solvers, then exit."); // --version - parser->addFlag( - options.displayVersion, 'v', "version", "Print the version of antares-solver and exit"); + parser->addFlag(options.displayVersion, + 'v', + "version", + "Print the version of antares-solver and exit"); // The last argument is the study folder. // Unlike all other arguments, it does not need to be given after a --flag. @@ -202,24 +207,26 @@ void checkAndCorrectSettingsAndOptions(Settings& settings, Data::StudyLoadOption const auto& optPID = settings.PID; if (!optPID.empty()) { - IO::File::Stream pidfile; - if (pidfile.openRW(optPID)) - pidfile << ProcessID(); + if (std::ofstream pidfile(optPID); pidfile.is_open()) + { + pidfile << getpid(); + } else + { throw Error::WritingPID(optPID); + } } // Simulation name if (!options.simulationName.empty()) - settings.simulationName = options.simulationName; - - if (options.nbYears > MAX_NB_MC_YEARS) { - throw Error::InvalidNumberOfMCYears(options.nbYears); + settings.simulationName = options.simulationName; } if (options.maxNbYearsInParallel) + { options.forceParallel = true; + } if (options.enableParallel && options.forceParallel) { @@ -231,11 +238,15 @@ void checkAndCorrectSettingsAndOptions(Settings& settings, Data::StudyLoadOption settings.simplexOptimRange.trim(" \t"); settings.simplexOptimRange.toLower(); if (settings.simplexOptimRange == "week") + { options.simplexOptimizationRange = Data::sorWeek; + } else { if (settings.simplexOptimRange == "day") + { options.simplexOptimizationRange = Data::sorDay; + } else { throw Error::InvalidOptimizationRange(); @@ -244,17 +255,7 @@ void checkAndCorrectSettingsAndOptions(Settings& settings, Data::StudyLoadOption } options.checkForceSimulationMode(); - checkOrtoolsSolver(options); - - // PID - if (!optPID.empty()) - { - IO::File::Stream pidfile; - if (pidfile.openRW(optPID)) - pidfile << ProcessID(); - else - throw Error::WritingPID(optPID); - } + checkOrtoolsSolver(options.optOptions); // no-output and force-zip-output if (settings.noOutput && settings.forceZipOutput) @@ -263,51 +264,43 @@ void checkAndCorrectSettingsAndOptions(Settings& settings, Data::StudyLoadOption } } -void checkOrtoolsSolver(Data::StudyLoadOptions& options) +void checkOrtoolsSolver(const Antares::Solver::Optimization::OptimizationOptions& optOptions) { - std::string baseSolver = "sirius"; - if (options.ortoolsUsed) + if (optOptions.ortoolsUsed) { + const std::string& solverName = optOptions.ortoolsSolver; const std::list availableSolverList = getAvailableOrtoolsSolverName(); - if (availableSolverList.empty()) - { - throw Error::InvalidSolver(options.ortoolsSolver); - } // Check if solver is available - bool found - = (std::find( - availableSolverList.begin(), availableSolverList.end(), options.ortoolsSolver) - != availableSolverList.end()); - + bool found = (std::find(availableSolverList.begin(), availableSolverList.end(), solverName) + != availableSolverList.end()); if (!found) { - logs.warning() << "Invalid ortools-solver option. Got '" << options.ortoolsSolver - << "'. reset to " << baseSolver; - options.ortoolsSolver = baseSolver; + throw Error::InvalidSolver(optOptions.ortoolsSolver, availableOrToolsSolversString()); } } } -void Settings::checkAndSetStudyFolder(Yuni::String folder) +void Settings::checkAndSetStudyFolder(const std::string& folder) { // The study folder if (folder.empty()) + { throw Error::NoStudyProvided(); + } // Making the path absolute - String abspath; - IO::MakeAbsolute(abspath, folder); - IO::Normalize(folder, abspath); + std::filesystem::path abspath = std::filesystem::absolute(folder); + abspath = abspath.lexically_normal(); // Checking if the path exists - if (!IO::Directory::Exists(folder)) + if (!std::filesystem::exists(abspath)) { throw Error::StudyFolderDoesNotExist(folder); } // Copying the result - studyFolder = folder; + studyFolder = abspath.string(); } void Settings::reset() diff --git a/src/solver/misc/options.h b/src/solver/misc/options.h deleted file mode 100644 index 58d5eeedbc..0000000000 --- a/src/solver/misc/options.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_MISC_GETOPT_H__ -#define __SOLVER_MISC_GETOPT_H__ - -#include -#include -#include -#include - -#include - -/*! -** \brief Command line settings for launching the simulation -*/ -class Settings -{ -public: - //! Where is my study - YString studyFolder; - //! Name of the simulation - Yuni::CString<150, false> simulationName; - //! Comment file - YString commentFile; - - //! Simplex optimizatio range - Yuni::CString<32, false> simplexOptimRange; - - //! Ignore error/warnings - int ignoreWarningsErrors = 0; - //! Ignore constraints - bool ignoreConstraints = false; - //! - bool tsGeneratorsOnly = false; - //! True to disable the writing in the output folder - bool noOutput = false; - //! Progression - bool displayProgression = false; - - Yuni::String PID; - - bool forceZipOutput = false; - - void checkAndSetStudyFolder(Yuni::String folder); - void reset(); -}; // class Settings - -/*! -** \brief Interprete options given in command line -*/ -std::unique_ptr CreateParser(Settings& settings, - Antares::Data::StudyLoadOptions& options); - -void checkAndCorrectSettingsAndOptions(Settings& settings, Data::StudyLoadOptions& options); - -void checkOrtoolsSolver(Data::StudyLoadOptions& options); -#endif /* __SOLVER_MISC_GETOPT_H__ */ diff --git a/src/solver/misc/process-priority.cpp b/src/solver/misc/process-priority.cpp deleted file mode 100644 index bb1d75f388..0000000000 --- a/src/solver/misc/process-priority.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "../application.h" -#ifdef YUNI_OS_WINDOWS -#include -#include -#include - -using namespace Yuni; -using namespace Antares; -#endif - -namespace Antares -{ -namespace Solver -{ -void Application::resetProcessPriority() const -{ -#ifdef YUNI_OS_WINDOWS - if (System::CPU::Count() <= 2) - { - if (not SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS)) - logs.info() << " :: impossible to reset the process priority"; - } -#endif -} -} // namespace Solver -} // namespace Antares diff --git a/src/solver/misc/system-memory.cpp b/src/solver/misc/system-memory.cpp index 224264a152..1c116e6d0e 100644 --- a/src/solver/misc/system-memory.cpp +++ b/src/solver/misc/system-memory.cpp @@ -1,34 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "system-memory.h" -#include +#include "antares/solver/misc/system-memory.h" + #include +#include + using namespace Yuni; using namespace Antares; diff --git a/src/solver/misc/system-memory.h b/src/solver/misc/system-memory.h deleted file mode 100644 index 51828f54c9..0000000000 --- a/src/solver/misc/system-memory.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_MISC_SYSTEM_MEMORY_H__ -#define __SOLVER_MISC_SYSTEM_MEMORY_H__ - -#include -#include - -class SystemMemoryLogger : public Yuni::Thread::Timer -{ -public: - SystemMemoryLogger(); - virtual ~SystemMemoryLogger(); - -protected: - virtual bool onInterval(uint); - - virtual bool onStarting(); - -}; // class SystemMemoryLogguer - -#endif /* __SOLVER_MISC_SYSTEM_MEMORY_H__ */ diff --git a/src/solver/misc/write-command-line.cpp b/src/solver/misc/write-command-line.cpp index 544cc6bb3b..420999a51b 100644 --- a/src/solver/misc/write-command-line.cpp +++ b/src/solver/misc/write-command-line.cpp @@ -1,6 +1,27 @@ -#include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include +#include + namespace Antares::Solver { void WriteCommandLineIntoLogs(int argc, char** argv) @@ -10,7 +31,9 @@ void WriteCommandLineIntoLogs(int argc, char** argv) { buffer << argv[arg]; if (arg + 1 != argc) + { buffer << " "; + } } logs.info() << " :: command: " << buffer.str(); } diff --git a/src/solver/misc/write-command-line.h b/src/solver/misc/write-command-line.h deleted file mode 100644 index 173b62bdb9..0000000000 --- a/src/solver/misc/write-command-line.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -namespace Antares::Solver -{ -void WriteCommandLineIntoLogs(int argc, char** argv); -} diff --git a/src/solver/optimisation/CMakeLists.txt b/src/solver/optimisation/CMakeLists.txt index 4d23d3ef89..a6c6f01e66 100644 --- a/src/solver/optimisation/CMakeLists.txt +++ b/src/solver/optimisation/CMakeLists.txt @@ -1,147 +1,212 @@ set(RTESOLVER_OPT - opt_optimisation_hebdo.cpp - opt_appel_solveur_quadratique.cpp - opt_gestion_second_membre_cas_lineaire.cpp - opt_optimisation_lineaire.cpp - opt_chainage_intercos.cpp - opt_fonctions.h - opt_pilotage_optimisation_lineaire.cpp - opt_pilotage_optimisation_quadratique.cpp - opt_structure_probleme_a_resoudre.h - opt_constants.h - opt_alloc_probleme_a_optimiser.cpp - opt_gestion_des_bornes_cas_quadratique.cpp - opt_construction_variables_optimisees_lineaire.cpp - opt_gestion_des_couts_cas_lineaire.cpp - opt_gestion_second_membre_cas_quadratique.cpp - opt_gestion_des_pmin.cpp - opt_calcul_des_pmin_MUT_MDT.cpp - opt_numero_de_jour_du_pas_de_temps.cpp - opt_construction_variables_optimisees_quadratique.cpp + opt_optimisation_hebdo.cpp + opt_appel_solveur_quadratique.cpp + opt_gestion_second_membre_cas_lineaire.cpp + opt_optimisation_lineaire.cpp + opt_chainage_intercos.cpp + include/antares/solver/optimisation/opt_fonctions.h + opt_pilotage_optimisation_lineaire.cpp + opt_pilotage_optimisation_quadratique.cpp + include/antares/solver/optimisation/opt_structure_probleme_a_resoudre.h + include/antares/solver/optimisation/opt_constants.h + opt_alloc_probleme_a_optimiser.cpp + opt_gestion_des_bornes_cas_quadratique.cpp + opt_construction_variables_optimisees_lineaire.cpp + opt_gestion_des_couts_cas_lineaire.cpp + opt_gestion_second_membre_cas_quadratique.cpp + opt_gestion_des_pmin.cpp + opt_calcul_des_pmin_MUT_MDT.cpp + opt_numero_de_jour_du_pas_de_temps.cpp + opt_construction_variables_optimisees_quadratique.cpp + opt_decompte_variables_et_contraintes.cpp opt_decompte_variables_et_contraintes.cpp - opt_construction_matrice_des_contraintes_cas_quadratique.cpp - opt_construction_matrice_des_contraintes_cas_lineaire.cpp - opt_construction_matrice_des_contraintes_outils.cpp - opt_gestion_des_bornes_cas_lineaire.cpp - opt_verification_presence_reserve_jmoins1.cpp - opt_init_contraintes_hydrauliques.cpp - opt_appel_solveur_lineaire.cpp - opt_liberation_problemes_simplexe.cpp - opt_restaurer_les_donnees.cpp + opt_gestion_des_bornes_cas_lineaire.cpp + opt_verification_presence_reserve_jmoins1.cpp + opt_init_contraintes_hydrauliques.cpp + opt_appel_solveur_lineaire.cpp + opt_liberation_problemes_simplexe.cpp + opt_restaurer_les_donnees.cpp + opt_gestion_des_couts_cas_quadratique.cpp opt_gestion_des_couts_cas_quadratique.cpp - opt_construction_contraintes_couts_demarrage.cpp - opt_construction_variables_couts_demarrages.cpp - opt_gestion_des_bornes_couts_demarrage.cpp - opt_gestion_des_couts_couts_demarrage.cpp - opt_gestion_second_membre_couts_demarrage.cpp - opt_gestion_second_membre_couts_demarrage.cpp - opt_decompte_variables_et_contraintes_couts_demarrage.cpp - opt_init_minmax_groupes_couts_demarrage.cpp - opt_nombre_min_groupes_demarres_couts_demarrage.cpp - opt_export_structure.h - opt_export_structure.cpp - base_weekly_optimization.h - base_weekly_optimization.cpp - adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h - adequacy_patch_local_matching/adequacy_patch_weekly_optimization.cpp - weekly_optimization.h - weekly_optimization.cpp - optim_post_process_list.h - optim_post_process_list.cpp - post_process_commands.h - post_process_commands.cpp - adequacy_patch_csr/hourly_csr_problem.h - adequacy_patch_csr/adq_patch_post_process_list.h - adequacy_patch_csr/adq_patch_post_process_list.cpp - adequacy_patch_local_matching/adq_patch_local_matching.h - adequacy_patch_local_matching/adq_patch_local_matching.cpp - adequacy_patch_csr/adq_patch_curtailment_sharing.h - adequacy_patch_csr/adq_patch_curtailment_sharing.cpp - adequacy_patch_csr/solve_problem.cpp - adequacy_patch_csr/set_variable_boundaries.cpp - adequacy_patch_csr/set_problem_cost_function.cpp - adequacy_patch_csr/construct_problem_variables.cpp - adequacy_patch_csr/construct_problem_constraints_RHS.cpp - adequacy_patch_csr/csr_quadratic_problem.h - adequacy_patch_csr/csr_quadratic_problem.cpp - adequacy_patch_csr/count_constraints_variables.h - adequacy_patch_csr/count_constraints_variables.cpp + opt_construction_variables_couts_demarrages.cpp + opt_gestion_des_bornes_couts_demarrage.cpp + opt_gestion_des_couts_couts_demarrage.cpp + opt_gestion_second_membre_couts_demarrage.cpp + opt_gestion_second_membre_couts_demarrage.cpp + opt_decompte_variables_et_contraintes_couts_demarrage.cpp + opt_init_minmax_groupes_couts_demarrage.cpp + opt_nombre_min_groupes_demarres_couts_demarrage.cpp + include/antares/solver/optimisation/opt_export_structure.h + opt_export_structure.cpp + include/antares/solver/optimisation/base_weekly_optimization.h + base_weekly_optimization.cpp + include/antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h + adequacy_patch_local_matching/adequacy_patch_weekly_optimization.cpp + include/antares/solver/optimisation/weekly_optimization.h + weekly_optimization.cpp + include/antares/solver/optimisation/optim_post_process_list.h + optim_post_process_list.cpp + include/antares/solver/optimisation/post_process_commands.h + post_process_commands.cpp + include/antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h + include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h + adequacy_patch_csr/adq_patch_post_process_list.cpp + include/antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h + adequacy_patch_local_matching/adq_patch_local_matching.cpp + include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h + adequacy_patch_csr/adq_patch_curtailment_sharing.cpp + adequacy_patch_csr/solve_problem.cpp + adequacy_patch_csr/set_variable_boundaries.cpp + adequacy_patch_csr/set_problem_cost_function.cpp + adequacy_patch_csr/construct_problem_variables.cpp + adequacy_patch_csr/construct_problem_constraints_RHS.cpp + include/antares/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h + adequacy_patch_csr/csr_quadratic_problem.cpp + include/antares/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h + adequacy_patch_csr/count_constraints_variables.cpp + include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.h + adequacy_patch_csr/constraints/CsrFlowDissociation.cpp + include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.h + adequacy_patch_csr/constraints/CsrAreaBalance.cpp + include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.h + adequacy_patch_csr/constraints/CsrBindingConstraintHour.cpp - opt_period_string_generator_base.h - opt_rename_problem.h - opt_rename_problem.cpp + include/antares/solver/optimisation/opt_rename_problem.h + opt_rename_problem.cpp - constraints/ConstraintBuilder.cpp - constraints/ConstraintBuilder.h - constraints/AreaBalance.h + constraints/ConstraintBuilder.cpp + include/antares/solver/optimisation/constraints/ConstraintBuilder.h + constraints/constraint_builder_utils.cpp + include/antares/solver/optimisation/constraints/constraint_builder_utils.h + include/antares/solver/optimisation/constraints/AreaBalance.h constraints/AreaBalance.cpp - constraints/FictitiousLoad.h + include/antares/solver/optimisation/constraints/FictitiousLoad.h constraints/FictitiousLoad.cpp - constraints/ShortTermStorageLevel.h + include/antares/solver/optimisation/constraints/ShortTermStorageLevel.h constraints/ShortTermStorageLevel.cpp - constraints/FlowDissociation.h + include/antares/solver/optimisation/constraints/FlowDissociation.h constraints/FlowDissociation.cpp - constraints/BindingConstraintHour.h + include/antares/solver/optimisation/constraints/BindingConstraintHour.h constraints/BindingConstraintHour.cpp - constraints/BindingConstraintDay.h + include/antares/solver/optimisation/constraints/BindingConstraintDay.h constraints/BindingConstraintDay.cpp - constraints/BindingConstraintWeek.h + include/antares/solver/optimisation/constraints/BindingConstraintWeek.h constraints/BindingConstraintWeek.cpp - constraints/HydroPower.h + include/antares/solver/optimisation/constraints/HydroPower.h constraints/HydroPower.cpp - constraints/HydroPowerSmoothingUsingVariationSum.h + include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h constraints/HydroPowerSmoothingUsingVariationSum.cpp - constraints/HydroPowerSmoothingUsingVariationMaxDown.h + include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h constraints/HydroPowerSmoothingUsingVariationMaxDown.cpp - constraints/HydroPowerSmoothingUsingVariationMaxUp.h + include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h constraints/HydroPowerSmoothingUsingVariationMaxUp.cpp - constraints/MinHydroPower.h + include/antares/solver/optimisation/constraints/MinHydroPower.h constraints/MinHydroPower.cpp - constraints/MaxHydroPower.h + include/antares/solver/optimisation/constraints/MaxHydroPower.h constraints/MaxHydroPower.cpp - constraints/MaxPumping.h + include/antares/solver/optimisation/constraints/MaxPumping.h constraints/MaxPumping.cpp - constraints/AreaHydroLevel.h + include/antares/solver/optimisation/constraints/AreaHydroLevel.h constraints/AreaHydroLevel.cpp - constraints/FinalStockEquivalent.h + include/antares/solver/optimisation/constraints/FinalStockEquivalent.h constraints/FinalStockEquivalent.cpp - constraints/FinalStockExpression.h + include/antares/solver/optimisation/constraints/FinalStockExpression.h constraints/FinalStockExpression.cpp - constraints/PMaxDispatchableGeneration.h + include/antares/solver/optimisation/constraints/PMaxDispatchableGeneration.h constraints/PMaxDispatchableGeneration.cpp - constraints/PMinDispatchableGeneration.h + include/antares/solver/optimisation/constraints/PMinDispatchableGeneration.h constraints/PMinDispatchableGeneration.cpp - constraints/ConsistenceNumberOfDispatchableUnits.h + include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h constraints/ConsistenceNumberOfDispatchableUnits.cpp - constraints/NbUnitsOutageLessThanNbUnitsStop.h + include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h constraints/NbUnitsOutageLessThanNbUnitsStop.cpp - constraints/NbDispUnitsMinBoundSinceMinUpTime.h + include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h constraints/NbDispUnitsMinBoundSinceMinUpTime.cpp - constraints/MinDownTime.h + include/antares/solver/optimisation/constraints/MinDownTime.h constraints/MinDownTime.cpp - ) - + include/antares/solver/optimisation/ProblemMatrixEssential.h + ProblemMatrixEssential.cpp + include/antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h + LinearProblemMatrixStartUpCosts.cpp + include/antares/solver/optimisation/LinearProblemMatrix.h + LinearProblemMatrix.cpp + include/antares/solver/optimisation/QuadraticProblemMatrix.h + QuadraticProblemMatrix.cpp + include/antares/solver/optimisation/constraints/ConstraintGroup.h + include/antares/solver/optimisation/constraints/Group1.h + constraints/Group1.cpp + include/antares/solver/optimisation/constraints/BindingConstraintDayGroup.h + constraints/BindingConstraintDayGroup.cpp + include/antares/solver/optimisation/constraints/BindingConstraintWeekGroup.h + constraints/BindingConstraintWeekGroup.cpp + include/antares/solver/optimisation/constraints/HydroPowerGroup.h + constraints/HydroPowerGroup.cpp + include/antares/solver/optimisation/constraints/HydraulicSmoothingGroup.h + constraints/HydraulicSmoothingGroup.cpp + include/antares/solver/optimisation/constraints/MinMaxHydroPowerGroup.h + constraints/MinMaxHydroPowerGroup.cpp + include/antares/solver/optimisation/constraints/MaxPumpingGroup.h + constraints/MaxPumpingGroup.cpp + include/antares/solver/optimisation/constraints/AreaHydroLevelGroup.h + constraints/AreaHydroLevelGroup.cpp + include/antares/solver/optimisation/constraints/FinalStockGroup.h + constraints/FinalStockGroup.cpp + include/antares/solver/optimisation/constraints/AbstractStartUpCostsGroup.h + constraints/AbstractStartUpCostsGroup.cpp + include/antares/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.h + constraints/PMinMaxDispatchableGenerationGroup.cpp + include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.h + constraints/ConsistenceNumberOfDispatchableUnitsGroup.cpp + include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.h + constraints/NbUnitsOutageLessThanNbUnitsStopGroup.cpp + include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.h + constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.cpp + include/antares/solver/optimisation/constraints/MinDownTimeGroup.h + constraints/MinDownTimeGroup.cpp + include/antares/solver/optimisation/constraints/ExchangeBalance.h + constraints/ExchangeBalance.cpp + include/antares/solver/optimisation/constraints/ExchangeBalanceGroup.h + constraints/ExchangeBalanceGroup.cpp + variables/VariableManagement.h + variables/VariableManagement.cpp + variables/VariableManagerUtils.h + variables/VariableManagerUtils.cpp + include/antares/solver/optimisation/HebdoProblemToLpsTranslator.h + HebdoProblemToLpsTranslator.cpp +) set(SRC_MODEL - ${RTESOLVER_OPT} + ${RTESOLVER_OPT} ) add_library(model_antares ${SRC_MODEL}) -if(NOT MSVC) - target_compile_options(model_antares - PUBLIC - "-Wno-unused-variable") -else() - #set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS} /wd 4101") # unused local variable - #set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} /wd 4101") # unused local variable -endif() +if (NOT MSVC) + target_compile_options(model_antares + PUBLIC + "-Wno-unused-variable") +else () + #set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS} /wd 4101") # unused local variable + #set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} /wd 4101") # unused local variable +endif () target_link_libraries(model_antares PUBLIC - utils + Antares::solverUtils sirius_solver - infeasible_problem_analysis antares-solver-simulation Antares::benchmarking + Antares::optimization-options + Antares::lps + PRIVATE + infeasible_problem_analysis ) + +target_include_directories(model_antares + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/solver/optimisation/HebdoProblemToLpsTranslator.cpp b/src/solver/optimisation/HebdoProblemToLpsTranslator.cpp new file mode 100644 index 0000000000..d4c6e4b6b0 --- /dev/null +++ b/src/solver/optimisation/HebdoProblemToLpsTranslator.cpp @@ -0,0 +1,124 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/optimisation/HebdoProblemToLpsTranslator.h" + +#include "antares/solver/utils/filename.h" + +namespace Antares::Solver +{ + +namespace +{ +/** + * @brief Copies elements from one container to another. + * + * This function takes two containers as arguments. It copies elements from the first container to + * the second one. + * + * @param in The container from which to copy elements. + * @param out The container to which to copy elements. + */ +template +void copy(const T& in, U& out) +{ + std::ranges::copy(in, std::back_inserter(out)); +} +} // namespace + +WeeklyDataFromAntares HebdoProblemToLpsTranslator::translate( + const PROBLEME_ANTARES_A_RESOUDRE* problem, + std::string_view name) const +{ + if (problem == nullptr) + { + return {}; + } + auto ret = WeeklyDataFromAntares(); + + copy(problem->CoutLineaire, ret.LinearCost); + copy(problem->Xmax, ret.Xmax); + copy(problem->Xmin, ret.Xmin); + copy(problem->NomDesVariables, ret.variables); + copy(problem->NomDesContraintes, ret.constraints); + copy(problem->SecondMembre, ret.RHS); + copy(problem->Sens, ret.Direction); + + copy(name, ret.name); + + return ret; +} + +ConstantDataFromAntares HebdoProblemToLpsTranslator::commonProblemData( + const PROBLEME_ANTARES_A_RESOUDRE* problem) const +{ + if (problem == nullptr) + { + return ConstantDataFromAntares(); + } + + if (problem->NombreDeVariables <= 0) + { + throw WeeklyProblemTranslationException("VariablesCount must be strictly positive"); + } + if (problem->NombreDeContraintes <= 0) + { + throw WeeklyProblemTranslationException("ConstraintesCount must be strictly positive"); + } + + if (problem->NombreDeContraintes > problem->IndicesDebutDeLigne.size()) + { + throw WeeklyProblemTranslationException( + "ConstraintesCount exceed IndicesDebutDeLigne size"); + } + + if (problem->NombreDeContraintes > problem->NombreDeTermesDesLignes.size()) + { + throw WeeklyProblemTranslationException( + "ConstraintesCount exceed NombreDeTermesDesLignes size"); + } + + ConstantDataFromAntares ret; + + ret.VariablesCount = problem->NombreDeVariables; + ret.ConstraintesCount = problem->NombreDeContraintes; + + ret.CoeffCount = problem->IndicesDebutDeLigne[problem->NombreDeContraintes - 1] + + problem->NombreDeTermesDesLignes[problem->NombreDeContraintes - 1]; + + copy(problem->TypeDeVariable, ret.VariablesType); + + copy(problem->CoefficientsDeLaMatriceDesContraintes, ret.ConstraintsMatrixCoeff); + ret.ConstraintsMatrixCoeff.resize(ret.CoeffCount); + copy(problem->IndicesColonnes, ret.ColumnIndexes); + ret.ColumnIndexes.resize(ret.CoeffCount); + copy(problem->IndicesDebutDeLigne, ret.Mdeb); + ret.Mdeb.push_back(ret.CoeffCount); + return ret; +} + +WeeklyProblemTranslationException::WeeklyProblemTranslationException( + const std::string& string) noexcept: + std::runtime_error{string} +{ +} +} // namespace Antares::Solver diff --git a/src/solver/optimisation/LinearProblemMatrix.cpp b/src/solver/optimisation/LinearProblemMatrix.cpp new file mode 100644 index 0000000000..ccc11e14a1 --- /dev/null +++ b/src/solver/optimisation/LinearProblemMatrix.cpp @@ -0,0 +1,67 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/LinearProblemMatrix.h" + +#include "antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h" +#include "antares/solver/optimisation/opt_export_structure.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/utils/filename.h" + +using namespace Antares::Data; + +LinearProblemMatrix::LinearProblemMatrix(PROBLEME_HEBDO* problemeHebdo, ConstraintBuilder& builder): + ProblemMatrixEssential(problemeHebdo), + builder_(builder), + group1_(problemeHebdo, builder), + bindingConstraintDayGroup_(problemeHebdo, builder), + bindingConstraintWeekGroup_(problemeHebdo, builder), + hydroPowerGroup_(problemeHebdo, builder), + hydraulicSmoothingGroup_(problemeHebdo, builder), + minMaxHydroPowerGroup_(problemeHebdo, builder), + maxPumpingGroup_(problemeHebdo, builder), + areaHydroLevelGroup_(problemeHebdo, builder), + finalStockGroup_(problemeHebdo, builder) +{ + constraintgroups_ = {&group1_, + &bindingConstraintDayGroup_, + &bindingConstraintWeekGroup_, + &hydroPowerGroup_, + &hydraulicSmoothingGroup_, + &minMaxHydroPowerGroup_, + &maxPumpingGroup_, + &areaHydroLevelGroup_, + &finalStockGroup_}; +} + +void LinearProblemMatrix::Run() +{ + InitializeProblemAResoudreCounters(); + + ProblemMatrixEssential::Run(); + + if (problemeHebdo_->OptimisationAvecCoutsDeDemarrage) + { + LinearProblemMatrixStartUpCosts(problemeHebdo_, false, builder_).Run(); + } + + return; +} diff --git a/src/solver/optimisation/LinearProblemMatrixStartUpCosts.cpp b/src/solver/optimisation/LinearProblemMatrixStartUpCosts.cpp new file mode 100644 index 0000000000..7a324d7def --- /dev/null +++ b/src/solver/optimisation/LinearProblemMatrixStartUpCosts.cpp @@ -0,0 +1,40 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h" +using namespace Antares::Data; + +LinearProblemMatrixStartUpCosts::LinearProblemMatrixStartUpCosts(PROBLEME_HEBDO* problemeHebdo, + bool Simulation, + ConstraintBuilder& builder): + ProblemMatrixEssential(problemeHebdo), + simulation_(Simulation), + pMinMaxDispatchableGenerationGroup_(problemeHebdo, simulation_, builder), + consistenceNumberOfDispatchableUnitsGroup_(problemeHebdo, simulation_, builder), + nbUnitsOutageLessThanNbUnitsStopGroup_(problemeHebdo, simulation_, builder), + nbDispUnitsMinBoundSinceMinUpTimeGroup_(problemeHebdo, simulation_, builder), + minDownTimeGroup_(problemeHebdo, simulation_, builder) +{ + constraintgroups_ = {&pMinMaxDispatchableGenerationGroup_, + &consistenceNumberOfDispatchableUnitsGroup_, + &nbUnitsOutageLessThanNbUnitsStopGroup_, + &nbDispUnitsMinBoundSinceMinUpTimeGroup_, + &minDownTimeGroup_}; +} diff --git a/src/solver/optimisation/ProblemMatrixEssential.cpp b/src/solver/optimisation/ProblemMatrixEssential.cpp new file mode 100644 index 0000000000..ee996df747 --- /dev/null +++ b/src/solver/optimisation/ProblemMatrixEssential.cpp @@ -0,0 +1,41 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/optimisation/ProblemMatrixEssential.h" + +ProblemMatrixEssential::ProblemMatrixEssential(PROBLEME_HEBDO* problemeHebdo): + problemeHebdo_(problemeHebdo) +{ +} + +void ProblemMatrixEssential::Run() +{ + for (auto& group: constraintgroups_) + { + group->BuildConstraints(); + } +} + +void ProblemMatrixEssential::InitializeProblemAResoudreCounters() +{ + auto& ProblemeAResoudre = problemeHebdo_->ProblemeAResoudre; + ProblemeAResoudre->NombreDeContraintes = 0; + ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; +} diff --git a/src/solver/optimisation/QuadraticProblemMatrix.cpp b/src/solver/optimisation/QuadraticProblemMatrix.cpp new file mode 100644 index 0000000000..66a15be308 --- /dev/null +++ b/src/solver/optimisation/QuadraticProblemMatrix.cpp @@ -0,0 +1,29 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/QuadraticProblemMatrix.h" + +void QuadraticProblemMatrix::Run() +{ + InitializeProblemAResoudreCounters(); + + ProblemMatrixEssential::Run(); +} diff --git a/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.cpp b/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.cpp index a1cd932a88..63789a5c76 100644 --- a/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.cpp @@ -1,50 +1,45 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "adq_patch_curtailment_sharing.h" -#include "../opt_fonctions.h" -#include "csr_quadratic_problem.h" -#include "count_constraints_variables.h" -#include "../simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h" #include +#include "antares/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h" +#include "antares/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" + using namespace Yuni; namespace Antares::Data::AdequacyPatch { -double LmrViolationAreaHour(const PROBLEME_HEBDO* problemeHebdo, +double LmrViolationAreaHour(PROBLEME_HEBDO* problemeHebdo, double totalNodeBalance, - const double threshold, + double threshold, int Area, int hour) { - const double ensInit - = problemeHebdo->ResultatsHoraires[Area].ValeursHorairesDeDefaillancePositive[hour]; + const double ensInit = problemeHebdo->ResultatsHoraires[Area] + .ValeursHorairesDeDefaillancePositive[hour]; problemeHebdo->ResultatsHoraires[Area].ValeursHorairesLmrViolations[hour] = 0; // check LMR violations @@ -77,8 +72,8 @@ std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* prob else if (problemeHebdo->adequacyPatchRuntimeData->extremityAreaMode[Interco] == physicalAreaOutsideAdqPatch) { - flowsNode1toNodeA - -= std::min(0.0, problemeHebdo->ValeursDeNTC[hour].ValeurDuFlux[Interco]); + flowsNode1toNodeA -= std::min(0.0, + problemeHebdo->ValeursDeNTC[hour].ValeurDuFlux[Interco]); } Interco = problemeHebdo->IndexSuivantIntercoOrigine[Interco]; } @@ -93,14 +88,14 @@ std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* prob else if (problemeHebdo->adequacyPatchRuntimeData->originAreaMode[Interco] == physicalAreaOutsideAdqPatch) { - flowsNode1toNodeA - += std::max(0.0, problemeHebdo->ValeursDeNTC[hour].ValeurDuFlux[Interco]); + flowsNode1toNodeA += std::max(0.0, + problemeHebdo->ValeursDeNTC[hour].ValeurDuFlux[Interco]); } Interco = problemeHebdo->IndexSuivantIntercoExtremite[Interco]; } - double ensInit - = problemeHebdo->ResultatsHoraires[Area].ValeursHorairesDeDefaillancePositive[hour]; + double ensInit = problemeHebdo->ResultatsHoraires[Area] + .ValeursHorairesDeDefaillancePositive[hour]; if (!setNTCOutsideToInsideToZero) { densNew = std::max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); @@ -128,15 +123,15 @@ void HourlyCSRProblem::calculateCsrParameters() problemeHebdo_->adequacyPatchRuntimeData->addCSRTriggeredAtAreaHour(Area, hour); // calculate netPositionInit and the RHS of the AreaBalance constraints - std::tie(netPositionInit, std::ignore, std::ignore) - = calculateAreaFlowBalance(problemeHebdo_, - adqPatchParams_.localMatching.setToZeroOutsideInsideLinks, - Area, - hour); - double ensInit - = problemeHebdo_->ResultatsHoraires[Area].ValeursHorairesDeDefaillancePositive[hour]; - double spillageInit - = problemeHebdo_->ResultatsHoraires[Area].ValeursHorairesDeDefaillanceNegative[hour]; + std::tie(netPositionInit, std::ignore, std::ignore) = calculateAreaFlowBalance( + problemeHebdo_, + adqPatchParams_.localMatching.setToZeroOutsideInsideLinks, + Area, + hour); + double ensInit = problemeHebdo_->ResultatsHoraires[Area] + .ValeursHorairesDeDefaillancePositive[hour]; + double spillageInit = problemeHebdo_->ResultatsHoraires[Area] + .ValeursHorairesDeDefaillanceNegative[hour]; rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; } @@ -150,8 +145,8 @@ void HourlyCSRProblem::allocateProblem() problemeAResoudre_.NombreDeVariables = countVariables(problemeHebdo_); nbConst = problemeAResoudre_.NombreDeContraintes = countConstraints(problemeHebdo_); - int nbTerms - = 3 * nbConst; // This is a rough estimate, reallocations may happen later if it's too low + int nbTerms = 3 * nbConst; // This is a rough estimate, reallocations may happen later if it's + // too low OPT_AllocateFromNumberOfVariableConstraints(&problemeAResoudre_, nbTerms); } @@ -166,14 +161,18 @@ void HourlyCSRProblem::buildProblemVariables() void HourlyCSRProblem::buildProblemConstraintsLHS() { - Antares::Solver::Optimization::CsrQuadraticProblem csrProb(problemeHebdo_, problemeAResoudre_, *this); + Antares::Solver::Optimization::CsrQuadraticProblem csrProb(problemeHebdo_, + problemeAResoudre_, + *this); csrProb.buildConstraintMatrix(); } void HourlyCSRProblem::setVariableBounds() { for (int var = 0; var < problemeAResoudre_.NombreDeVariables; var++) + { problemeAResoudre_.AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; + } logs.debug() << "[CSR] bounds"; setBoundsOnENS(); @@ -197,7 +196,9 @@ void HourlyCSRProblem::setProblemCost() setQuadraticCost(); if (adqPatchParams_.curtailmentSharing.includeHurdleCost) + { setLinearCost(); + } } void HourlyCSRProblem::solveProblem(uint week, int year) diff --git a/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h b/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h deleted file mode 100644 index fb92eae287..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include "sim_structure_probleme_economique.h" - -namespace Antares::Data::AdequacyPatch -{ - -/*! - * Calculates curtailment sharing rule parameters netPositionInit, densNew and totalNodeBalance per - * given area and hour. - */ -std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* problemeHebdo, - bool setNTCOutsideToInsideToZero, - int Area, - int hour); - -/*! - * Calculate total local matching rule violation per one area, per one hour. - */ -double LmrViolationAreaHour(const PROBLEME_HEBDO* problemeHebdo, - double totalNodeBalance, - const double threshold, - int Area, - int hour); - -/*! - * Calculate densNew values for all hours and areas inside adequacy patch and places them into - * problemeHebdo->ResultatsHoraires[Area].ValeursHorairesDENS[hour] to be displayed in output. - * copy-pastes spilled Energy values into spilled Energy values after CSR - * calculates total LMR violations and LMR violations per area per hour inside - * problemeHebdo->ResultatsHoraires[Area].ValeursHorairesLmrViolations[hour] - */ -double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - uint numSpace); -} // namespace Antares::Data::AdequacyPatch diff --git a/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.cpp b/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.cpp index 9bf0665d4b..1ed1e80371 100644 --- a/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.cpp @@ -1,57 +1,65 @@ -#include "adq_patch_post_process_list.h" -#include "../post_process_commands.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h" + +#include "antares/solver/optimisation/post_process_commands.h" namespace Antares::Solver::Simulation { - AdqPatchPostProcessList::AdqPatchPostProcessList(const AdqPatchParams& adqPatchParams, PROBLEME_HEBDO* problemeHebdo, uint thread_number, AreaList& areas, SheddingPolicy sheddingPolicy, SimplexOptimization splxOptimization, - Calendar& calendar) - : interfacePostProcessList(problemeHebdo, thread_number) + Calendar& calendar): + interfacePostProcessList(problemeHebdo, thread_number) { - post_process_list.push_back(std::make_unique( - problemeHebdo_, - thread_number_, - areas)); + post_process_list.push_back( + std::make_unique(problemeHebdo_, thread_number_, areas)); // Here a post process particular to adq patch - post_process_list.push_back(std::make_unique( - adqPatchParams, - problemeHebdo_, - areas, - thread_number_)); - post_process_list.push_back(std::make_unique( - problemeHebdo_, - areas, - false, - false)); - post_process_list.push_back(std::make_unique( - problemeHebdo_, - areas, - sheddingPolicy, - splxOptimization, - thread_number)); + post_process_list.push_back(std::make_unique(adqPatchParams, + problemeHebdo_, + areas, + thread_number_)); + post_process_list.push_back( + std::make_unique(problemeHebdo_, areas, false, false)); + post_process_list.push_back(std::make_unique(problemeHebdo_, + areas, + sheddingPolicy, + splxOptimization, + thread_number)); // Here a post process particular to adq patch - post_process_list.push_back(std::make_unique( - problemeHebdo_, - areas, - thread_number)); - post_process_list.push_back(std::make_unique( - problemeHebdo_, - areas, - true, - false)); - post_process_list.push_back(std::make_unique( - problemeHebdo_, - areas, - calendar)); - post_process_list.push_back(std::make_unique( - problemeHebdo_, - areas)); + post_process_list.push_back( + std::make_unique(adqPatchParams, + problemeHebdo_, + areas, + thread_number)); + post_process_list.push_back( + std::make_unique(problemeHebdo_, areas, true, false)); + post_process_list.push_back( + std::make_unique(problemeHebdo_, areas, calendar)); + post_process_list.push_back( + std::make_unique(problemeHebdo_, areas)); } -} // namespace Antares::Solver::Simulation \ No newline at end of file +} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h b/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h deleted file mode 100644 index 204a75e401..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - - -#include "../simulation/base_post_process.h" -#include "antares/study/parameters/adq-patch-params.h" - -namespace Antares::Solver::Simulation -{ - -class AdqPatchPostProcessList : public interfacePostProcessList -{ - using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; -public: - AdqPatchPostProcessList(const AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemeHebdo, - uint thread_number, - AreaList& areas, - SheddingPolicy sheddingPolicy, - SimplexOptimization splxOptimization, - Calendar& calendar); - - virtual ~AdqPatchPostProcessList() = default; -}; - -} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.cpp b/src/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.cpp new file mode 100644 index 0000000000..329fe38a6d --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.cpp @@ -0,0 +1,89 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.h" + +void CsrAreaBalance::add() +{ + for (uint32_t Area = 0; Area < data.NombreDePays; ++Area) + { + if (data.areaMode[Area] != Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + continue; + } + + // + ENS + builder.updateHourWithinWeek(data.hour).PositiveUnsuppliedEnergy(Area, 1.0); + + // - export flows + int Interco = data.IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + if (data.extremityAreaMode[Interco] != Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + Interco = data.IndexSuivantIntercoOrigine[Interco]; + continue; + } + + // flow (A->2) + builder.NTCDirect(Interco, -1.0); + + logs.debug() << "S-Interco number: [" << std::to_string(Interco) << "] between: [" + << builder.data.NomsDesPays[Area] << "]-[" + << builder.data.NomsDesPays[data.PaysExtremiteDeLInterconnexion[Interco]] + << "]"; + + Interco = data.IndexSuivantIntercoOrigine[Interco]; + } + + // or + import flows + Interco = data.IndexDebutIntercoExtremite[Area]; + while (Interco >= 0) + { + if (data.originAreaMode[Interco] != Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + Interco = data.IndexSuivantIntercoExtremite[Interco]; + continue; + } + // flow (2 -> A) + builder.NTCDirect(Interco, 1.0); + + logs.debug() << "E-Interco number: [" << std::to_string(Interco) << "] between: [" + << builder.data.NomsDesPays[Area] << "]-[" + << builder.data.NomsDesPays[data.PaysOrigineDeLInterconnexion[Interco]] + << "]"; + + Interco = data.IndexSuivantIntercoExtremite[Interco]; + } + + // - Spilled Energy + builder.NegativeUnsuppliedEnergy(Area, -1.0); + + data.numberOfConstraintCsrAreaBalance[Area] = builder.data.nombreDeContraintes; + + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(data.hour); + namer.UpdateArea(builder.data.NomsDesPays[Area]); + namer.CsrAreaBalance(builder.data.nombreDeContraintes); + builder.equalTo(); + builder.build(); + } +} diff --git a/src/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.cpp b/src/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.cpp new file mode 100644 index 0000000000..3ce24b7d50 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.cpp @@ -0,0 +1,64 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.h" + +void CsrBindingConstraintHour::add(int CntCouplante) +{ + if (data.MatriceDesContraintesCouplantes[CntCouplante].TypeDeContrainteCouplante + != CONTRAINTE_HORAIRE) + { + return; + } + + int NbInterco = data.MatriceDesContraintesCouplantes[CntCouplante] + .NombreDInterconnexionsDansLaContrainteCouplante; + builder.updateHourWithinWeek(data.hour); + + for (int Index = 0; Index < NbInterco; Index++) + { + int Interco = data.MatriceDesContraintesCouplantes[CntCouplante] + .NumeroDeLInterconnexion[Index]; + double Poids = data.MatriceDesContraintesCouplantes[CntCouplante] + .PoidsDeLInterconnexion[Index]; + + if (data.originAreaMode[Interco] == Data::AdequacyPatch::physicalAreaInsideAdqPatch + && data.extremityAreaMode[Interco] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + builder.NTCDirect(Interco, Poids); + } + } + + if (builder.NumberOfVariables() + > 0) // current binding constraint contains an interco type 2<->2 + { + data.numberOfConstraintCsrHourlyBinding[CntCouplante] = builder.data.nombreDeContraintes; + + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(data.hour); + namer.CsrBindingConstraintHour( + builder.data.nombreDeContraintes, + data.MatriceDesContraintesCouplantes[CntCouplante].NomDeLaContrainteCouplante); + builder.SetOperator( + data.MatriceDesContraintesCouplantes[CntCouplante].SensDeLaContrainteCouplante); + builder.build(); + } +} diff --git a/src/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.cpp b/src/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.cpp new file mode 100644 index 0000000000..24743fb28e --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.cpp @@ -0,0 +1,53 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.h" + +void CsrFlowDissociation::add() +{ + builder.updateHourWithinWeek(data.hour); + + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(data.hour); + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes + // of type 2. + for (uint32_t interco = 0; interco < data.NombreDInterconnexions; interco++) + { + if (data.originAreaMode[interco] == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch + && data.extremityAreaMode[interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + builder.NTCDirect(interco, 1.0) + .IntercoDirectCost(interco, -1.0) + .IntercoIndirectCost(interco, 1.0); + + data.numberOfConstraintCsrFlowDissociation[interco] = builder.data.nombreDeContraintes; + + const auto& origin = builder.data + .NomsDesPays[data.PaysOrigineDeLInterconnexion[interco]]; + const auto& destination = builder.data + .NomsDesPays[data.PaysExtremiteDeLInterconnexion[interco]]; + namer.CsrFlowDissociation(builder.data.nombreDeContraintes, origin, destination); + builder.equalTo(); + builder.build(); + } + } +} diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp index 46b588d180..6efbde35b4 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp @@ -1,34 +1,28 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "hourly_csr_problem.h" #include -#include -#include "adequacy_patch_runtime_data.h" +#include "antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" void HourlyCSRProblem::setRHSvalueOnFlows() { @@ -92,7 +86,9 @@ void HourlyCSRProblem::setRHSbindingConstraintsValue() { if (numberOfConstraintCsrHourlyBinding.find(CntCouplante) == numberOfConstraintCsrHourlyBinding.end()) + { continue; + } const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes = problemeHebdo_->MatriceDesContraintesCouplantes[CntCouplante]; @@ -100,12 +96,12 @@ void HourlyCSRProblem::setRHSbindingConstraintsValue() int Cnt = numberOfConstraintCsrHourlyBinding[CntCouplante]; // 1. The original RHS of bingding constraint - SecondMembre[Cnt] - = MatriceDesContraintesCouplantes.SecondMembreDeLaContrainteCouplante[triggeredHour]; + SecondMembre[Cnt] = MatriceDesContraintesCouplantes + .SecondMembreDeLaContrainteCouplante[triggeredHour]; // 2. RHS part 2: flow other than 2<->2 - int NbInterco - = MatriceDesContraintesCouplantes.NombreDInterconnexionsDansLaContrainteCouplante; + int NbInterco = MatriceDesContraintesCouplantes + .NombreDInterconnexionsDansLaContrainteCouplante; for (int Index = 0; Index < NbInterco; Index++) { int Interco = MatriceDesContraintesCouplantes.NumeroDeLInterconnexion[Index]; @@ -116,22 +112,22 @@ void HourlyCSRProblem::setRHSbindingConstraintsValue() || problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode[Interco] != Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - double ValueOfFlow - = problemeHebdo_->ValeursDeNTC[triggeredHour].ValeurDuFlux[Interco]; + double ValueOfFlow = problemeHebdo_->ValeursDeNTC[triggeredHour] + .ValeurDuFlux[Interco]; SecondMembre[Cnt] -= ValueOfFlow * Poids; } } // 3. RHS part 3: - cluster - int NbClusters - = MatriceDesContraintesCouplantes.NombreDePaliersDispatchDansLaContrainteCouplante; + int NbClusters = MatriceDesContraintesCouplantes + .NombreDePaliersDispatchDansLaContrainteCouplante; for (int Index = 0; Index < NbClusters; Index++) { int Area = MatriceDesContraintesCouplantes.PaysDuPalierDispatch[Index]; - int IndexNumeroDuPalierDispatch - = MatriceDesContraintesCouplantes.NumeroDuPalierDispatch[Index]; + int IndexNumeroDuPalierDispatch = MatriceDesContraintesCouplantes + .NumeroDuPalierDispatch[Index]; double Poids = MatriceDesContraintesCouplantes.PoidsDuPalierDispatch[Index]; diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp index 75ac2287b3..9cf6fa949b 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -1,42 +1,35 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" -#include "../simulation/adequacy_patch_runtime_data.h" -#include "sim_structure_probleme_economique.h" -#include "hourly_csr_problem.h" +#include "antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" #include "pi_constantes_externes.h" + void HourlyCSRProblem::constructVariableENS() { int& NumberOfVariables = problemeAResoudre_.NombreDeVariables; NumberOfVariables = 0; - auto& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; // variables: ENS of each area inside adq patch logs.debug() << " ENS of each area inside adq patch: "; @@ -46,8 +39,7 @@ void HourlyCSRProblem::constructVariableENS() if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[area] - = NumberOfVariables; + variableManager_.PositiveUnsuppliedEnergy(area, triggeredHour) = NumberOfVariables; problemeAResoudre_.TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); ensVariablesInsideAdqPatch.insert(NumberOfVariables); @@ -61,8 +53,6 @@ void HourlyCSRProblem::constructVariableENS() void HourlyCSRProblem::constructVariableSpilledEnergy() { - auto& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; int& NumberOfVariables = problemeAResoudre_.NombreDeVariables; // variables: Spilled Energy of each area inside adq patch @@ -73,8 +63,7 @@ void HourlyCSRProblem::constructVariableSpilledEnergy() if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillanceNegative[area] - = NumberOfVariables; + variableManager_.NegativeUnsuppliedEnergy(area, triggeredHour) = NumberOfVariables; problemeAResoudre_.TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "].-[" @@ -87,8 +76,6 @@ void HourlyCSRProblem::constructVariableSpilledEnergy() void HourlyCSRProblem::constructVariableFlows() { - auto& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; int& NumberOfVariables = problemeAResoudre_.NombreDeVariables; // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 @@ -106,8 +93,7 @@ void HourlyCSRProblem::constructVariableFlows() int algebraicFluxVar; int directVar; int indirectVar; - algebraicFluxVar - = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[Interco] + algebraicFluxVar = variableManager_.NTCDirect(Interco, triggeredHour) = NumberOfVariables; problemeAResoudre_.TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() @@ -119,15 +105,13 @@ void HourlyCSRProblem::constructVariableFlows() << "]."; NumberOfVariables++; - directVar = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + directVar = variableManager_.IntercoDirectCost(Interco, triggeredHour) = NumberOfVariables; problemeAResoudre_.TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() << NumberOfVariables << " direct flow[" << Interco << "]. "; NumberOfVariables++; - indirectVar = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + indirectVar = variableManager_.IntercoIndirectCost(Interco, triggeredHour) = NumberOfVariables; problemeAResoudre_.TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() << NumberOfVariables << " indirect flow[" << Interco << "]. "; diff --git a/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.cpp b/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.cpp index 7e5ea15cf2..4dcec5c9d0 100644 --- a/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.cpp @@ -1,32 +1,27 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "count_constraints_variables.h" -#include "../simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h" + +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" namespace Antares::Data::AdequacyPatch { @@ -41,7 +36,9 @@ int countConstraints(const PROBLEME_HEBDO* problemeHebdo) == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch && problemeHebdo->adequacyPatchRuntimeData->extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { numberOfConstraints++; + } } // constraint: @@ -54,7 +51,9 @@ int countConstraints(const PROBLEME_HEBDO* problemeHebdo) { if (problemeHebdo->adequacyPatchRuntimeData->areaMode[Area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { numberOfConstraints++; + } } // Special case of the hourly binding constraints const auto MatrixBindingConstraints = problemeHebdo->MatriceDesContraintesCouplantes; @@ -62,7 +61,9 @@ int countConstraints(const PROBLEME_HEBDO* problemeHebdo) CntCouplante++) { if (MatrixBindingConstraints[CntCouplante].TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) + { numberOfConstraints++; + } } return numberOfConstraints; } @@ -76,7 +77,9 @@ int countVariables(const PROBLEME_HEBDO* problemeHebdo) // Only ENS for areas inside adq patch are considered as variables if (problemeHebdo->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { numberOfVariables += 2; // ENS, spilled energy + } } for (uint32_t Interco = 0; Interco < problemeHebdo->NombreDInterconnexions; Interco++) diff --git a/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h b/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h deleted file mode 100644 index 4d82c4a09a..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include "../../simulation/sim_structure_probleme_economique.h" - -namespace Antares::Data::AdequacyPatch -{ -int countConstraints(const PROBLEME_HEBDO* problemeHebdo); -int countVariables(const PROBLEME_HEBDO* problemeHebdo); -} // namespace Antares::Data::AdequacyPatch diff --git a/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.cpp index 90ac4709c1..6c9b54d6d0 100644 --- a/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.cpp @@ -1,101 +1,63 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h" + #include -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" -#include "../simulation/adequacy_patch_runtime_data.h" -#include "../solver/optimisation/opt_fonctions.h" -#include "csr_quadratic_problem.h" -#include "hourly_csr_problem.h" -#include "sim_structure_probleme_economique.h" +#include "antares/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.h" +#include "antares/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.h" +#include "antares/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.h" +#include "antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h" +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" using namespace Antares::Data; namespace Antares::Solver::Optimization { -void CsrQuadraticProblem::setConstraintsOnFlows(std::vector& Pi, std::vector& Colonne) + +void CsrQuadraticProblem::setConstraintsOnFlows(ConstraintBuilder& builder) { int hour = hourlyCsrProblem_.triggeredHour; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[hour]; - - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of - // type 2. - for (uint32_t Interco = 0; Interco < problemeHebdo_->NombreDInterconnexions; Interco++) - { - if (problemeHebdo_->adequacyPatchRuntimeData->originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - int NombreDeTermes = 0; - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[Interco]; - if (var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - if (var >= 0) - { - Pi[NombreDeTermes] = -1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - } - - hourlyCsrProblem_.numberOfConstraintCsrFlowDissociation[Interco] - = problemeAResoudre_.NombreDeContraintes; - - std::string NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); - logs.debug() << "C Interco: " << problemeAResoudre_.NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - &problemeAResoudre_, Pi, Colonne, NombreDeTermes, '='); - } - } + //!\ TODO not associated problemHebdo && probleamAressoudre + CsrFlowDissociationData csrFlowDissociationData = { + .numberOfConstraintCsrFlowDissociation = hourlyCsrProblem_ + .numberOfConstraintCsrFlowDissociation, + .NombreDInterconnexions = problemeHebdo_->NombreDInterconnexions, + .originAreaMode = problemeHebdo_->adequacyPatchRuntimeData->originAreaMode, + .extremityAreaMode = problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode, + .PaysOrigineDeLInterconnexion = problemeHebdo_->PaysOrigineDeLInterconnexion, + .PaysExtremiteDeLInterconnexion = problemeHebdo_->PaysExtremiteDeLInterconnexion, + .hour = hour}; + CsrFlowDissociation csrFlowDissociation(builder, csrFlowDissociationData); + csrFlowDissociation.add(); } -void CsrQuadraticProblem::setNodeBalanceConstraints(std::vector& Pi, std::vector& Colonne) +void CsrQuadraticProblem::setNodeBalanceConstraints(ConstraintBuilder& builder) { int hour = hourlyCsrProblem_.triggeredHour; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[hour]; // constraint: // ENS(node A) + @@ -104,158 +66,42 @@ void CsrQuadraticProblem::setNodeBalanceConstraints(std::vector& Pi, std // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - for (uint32_t Area = 0; Area < problemeHebdo_->NombreDePays; ++Area) - { - if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[Area] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch) - continue; - - // + ENS - int NombreDeTermes = 0; - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[Area]; - if (var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - } - - // - export flows - int Interco = problemeHebdo_->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode[Interco] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Interco = problemeHebdo_->IndexSuivantIntercoOrigine[Interco]; - continue; - } - - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDeLInterconnexion[Interco]; // flow (A->2) - if (var >= 0) - { - Pi[NombreDeTermes] = -1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - logs.debug() - << "S-Interco number: [" << std::to_string(Interco) << "] between: [" - << problemeHebdo_->NomsDesPays[Area] << "]-[" - << problemeHebdo_ - ->NomsDesPays[problemeHebdo_->PaysExtremiteDeLInterconnexion[Interco]] - << "]"; - } - Interco = problemeHebdo_->IndexSuivantIntercoOrigine[Interco]; - } - - // or + import flows - Interco = problemeHebdo_->IndexDebutIntercoExtremite[Area]; - while (Interco >= 0) - { - if (problemeHebdo_->adequacyPatchRuntimeData->originAreaMode[Interco] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Interco = problemeHebdo_->IndexSuivantIntercoExtremite[Interco]; - continue; - } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDeLInterconnexion[Interco]; // flow (2 -> A) - if (var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - logs.debug() - << "E-Interco number: [" << std::to_string(Interco) << "] between: [" - << problemeHebdo_->NomsDesPays[Area] << "]-[" - << problemeHebdo_ - ->NomsDesPays[problemeHebdo_->PaysOrigineDeLInterconnexion[Interco]] - << "]"; - } - Interco = problemeHebdo_->IndexSuivantIntercoExtremite[Interco]; - } - - // - Spilled Energy - var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillanceNegative[Area]; - if (var >= 0) - { - Pi[NombreDeTermes] = -1.0; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - } - - hourlyCsrProblem_.numberOfConstraintCsrAreaBalance[Area] - = problemeAResoudre_.NombreDeContraintes; - - std::string NomDeLaContrainte - = "Area Balance, Area:" + std::to_string(Area) + "; " + problemeHebdo_->NomsDesPays[Area]; - - logs.debug() << "C: " << problemeAResoudre_.NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - &problemeAResoudre_, Pi, Colonne, NombreDeTermes, '='); - } + CsrAreaBalanceData csrAreaBalanceData{ + .areaMode = problemeHebdo_->adequacyPatchRuntimeData->areaMode, + .hour = hour, + .IndexDebutIntercoOrigine = problemeHebdo_->IndexDebutIntercoOrigine, + .IndexSuivantIntercoOrigine = problemeHebdo_->IndexSuivantIntercoOrigine, + .IndexDebutIntercoExtremite = problemeHebdo_->IndexDebutIntercoExtremite, + .IndexSuivantIntercoExtremite = problemeHebdo_->IndexSuivantIntercoExtremite, + .originAreaMode = problemeHebdo_->adequacyPatchRuntimeData->originAreaMode, + .extremityAreaMode = problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode, + .PaysOrigineDeLInterconnexion = problemeHebdo_->PaysOrigineDeLInterconnexion, + .PaysExtremiteDeLInterconnexion = problemeHebdo_->PaysExtremiteDeLInterconnexion, + .numberOfConstraintCsrAreaBalance = hourlyCsrProblem_.numberOfConstraintCsrAreaBalance, + .NombreDePays = problemeHebdo_->NombreDePays}; + + CsrAreaBalance csrAreaBalance(builder, csrAreaBalanceData); + csrAreaBalance.add(); } -void CsrQuadraticProblem::setBindingConstraints(std::vector& Pi, std::vector& Colonne) +void CsrQuadraticProblem::setBindingConstraints(ConstraintBuilder& builder) { int hour = hourlyCsrProblem_.triggeredHour; - // Special case of the binding constraints + CsrBindingConstraintHourData csrBindingConstraintHourData = { + .MatriceDesContraintesCouplantes = problemeHebdo_->MatriceDesContraintesCouplantes, + .originAreaMode = problemeHebdo_->adequacyPatchRuntimeData->originAreaMode, + .extremityAreaMode = problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode, + .hour = hour, + .numberOfConstraintCsrHourlyBinding = hourlyCsrProblem_.numberOfConstraintCsrHourlyBinding}; + + CsrBindingConstraintHour csrBindingConstraintHour( + builder, + csrBindingConstraintHourData); // Special case of the binding constraints for (uint32_t CntCouplante = 0; CntCouplante < problemeHebdo_->NombreDeContraintesCouplantes; CntCouplante++) { - const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes - = problemeHebdo_->MatriceDesContraintesCouplantes[CntCouplante]; - - if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante != CONTRAINTE_HORAIRE) - continue; - - int NbInterco - = MatriceDesContraintesCouplantes.NombreDInterconnexionsDansLaContrainteCouplante; - int NombreDeTermes = 0; - for (int Index = 0; Index < NbInterco; Index++) - { - int Interco = MatriceDesContraintesCouplantes.NumeroDeLInterconnexion[Index]; - double Poids = MatriceDesContraintesCouplantes.PoidsDeLInterconnexion[Index]; - - if (problemeHebdo_->adequacyPatchRuntimeData->originAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch - && problemeHebdo_->adequacyPatchRuntimeData->extremityAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - int var = problemeHebdo_->CorrespondanceVarNativesVarOptim[hour] - .NumeroDeVariableDeLInterconnexion[Interco]; - - if (var >= 0) - { - Pi[NombreDeTermes] = Poids; - Colonne[NombreDeTermes] = var; - NombreDeTermes++; - } - } - } - - if (NombreDeTermes > 0) // current binding constraint contains an interco type 2<->2 - { - hourlyCsrProblem_.numberOfConstraintCsrHourlyBinding[CntCouplante] - = problemeAResoudre_.NombreDeContraintes; - - std::string NomDeLaContrainte - = "bc::hourly::" + std::to_string(hour) - + "::" + MatriceDesContraintesCouplantes.NomDeLaContrainteCouplante; - - logs.debug() << "C (bc): " << problemeAResoudre_.NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - &problemeAResoudre_, - Pi, - Colonne, - NombreDeTermes, - MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante); - } + csrBindingConstraintHour.add(CntCouplante); } } @@ -268,10 +114,14 @@ void CsrQuadraticProblem::buildConstraintMatrix() problemeAResoudre_.NombreDeContraintes = 0; problemeAResoudre_.NombreDeTermesDansLaMatriceDesContraintes = 0; - - setConstraintsOnFlows(Pi, Colonne); - setNodeBalanceConstraints(Pi, Colonne); - setBindingConstraints(Pi, Colonne); + auto builder_data = NewGetConstraintBuilderFromProblemHebdoAndProblemAResoudre( + problemeHebdo_, + problemeAResoudre_); + + auto builder = ConstraintBuilder(builder_data); + setConstraintsOnFlows(builder); + setNodeBalanceConstraints(builder); + setBindingConstraints(builder); } } // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h b/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h deleted file mode 100644 index cd8931ae48..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -class HourlyCSRProblem; - -namespace Antares::Solver::Optimization -{ - -class CsrQuadraticProblem -{ -public: - CsrQuadraticProblem(const PROBLEME_HEBDO* p, PROBLEME_ANTARES_A_RESOUDRE& pa, HourlyCSRProblem& hourly) : - problemeHebdo_(p), problemeAResoudre_(pa), hourlyCsrProblem_(hourly) - { - } - - void buildConstraintMatrix(); - -private: - const PROBLEME_HEBDO* problemeHebdo_; - PROBLEME_ANTARES_A_RESOUDRE& problemeAResoudre_; - HourlyCSRProblem& hourlyCsrProblem_; - - void setConstraintsOnFlows(std::vector& Pi, std::vector& Colonne); - void setNodeBalanceConstraints(std::vector& Pi, std::vector& Colonne); - void setBindingConstraints(std::vector& Pi, std::vector& Colonne); -}; - -} //namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h b/src/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h deleted file mode 100644 index a09bb68de0..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h +++ /dev/null @@ -1,136 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -// TODO[FOM] Remove this, it is only required for PROBLEME_HEBDO -// but this problem has nothing to do with PROBLEME_HEBDO -#include -#include -#include -#include "../opt_structure_probleme_a_resoudre.h" - -struct PROBLEME_HEBDO; -class HourlyCSRProblem -{ -private: - void calculateCsrParameters(); - - void buildProblemVariables(); - void setVariableBounds(); - void buildProblemConstraintsLHS(); - void buildProblemConstraintsRHS(); - void setProblemCost(); - void solveProblem(uint week, int year); - void allocateProblem(); - - // variable construction - void constructVariableENS(); - void constructVariableSpilledEnergy(); - void constructVariableFlows(); - - // variable bounds - void setBoundsOnENS(); - void setBoundsOnSpilledEnergy(); - void setBoundsOnFlows(); - - // Constraints - void setRHSvalueOnFlows(); - void setRHSnodeBalanceValue(); - void setRHSbindingConstraintsValue(); - - // Costs - void setQuadraticCost(); - void setLinearCost(); - -private: - using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; - const AdqPatchParams& adqPatchParams_; - -public: - void run(uint week, uint year); - - // TODO[FOM] Make these members private - int triggeredHour; - double belowThisThresholdSetToZero; - PROBLEME_HEBDO* problemeHebdo_; - PROBLEME_ANTARES_A_RESOUDRE problemeAResoudre_; - - explicit HourlyCSRProblem(const AdqPatchParams& adqPatchParams,PROBLEME_HEBDO* p) : - adqPatchParams_(adqPatchParams), - problemeHebdo_(p) - { - double temp = pow(10, -adqPatchParams.curtailmentSharing.thresholdVarBoundsRelaxation); - belowThisThresholdSetToZero = std::min(temp, 0.1); - - allocateProblem(); - } - - ~HourlyCSRProblem() = default; - - HourlyCSRProblem(const HourlyCSRProblem&) = delete; - HourlyCSRProblem& operator=(const HourlyCSRProblem&) = delete; - - inline void setHour(int hour) - { - triggeredHour = hour; - } - - std::map numberOfConstraintCsrEns; - std::map numberOfConstraintCsrAreaBalance; - std::map numberOfConstraintCsrFlowDissociation; - std::map numberOfConstraintCsrHourlyBinding; // length is number of binding constraint - // contains interco 2-2 - - std::map rhsAreaBalanceValues; - std::set varToBeSetToZeroIfBelowThreshold; // place inside only ENS and Spillage variable - std::set ensVariablesInsideAdqPatch; // place inside only ENS inside adq-patch - - struct LinkVariable - { - LinkVariable() : directVar(-1), indirectVar(-1) - { - } - LinkVariable(int direct, int indirect) : directVar(direct), indirectVar(indirect) - { - } - inline bool check() const - { - if (directVar < 0) - Antares::logs.warning() << "directVar < 0 detected, this should not happen"; - if (indirectVar < 0) - Antares::logs.warning() << "indirectVar < 0 detected, this should not happen"; - - return (directVar >= 0) && (indirectVar >= 0); - } - int directVar; - int indirectVar; - }; - - // links between two areas inside the adq-patch domain - std::map linkInsideAdqPatch; -}; diff --git a/src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp b/src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp index 56ee0cb63f..0a10f007d0 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp @@ -1,50 +1,47 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" -#include "../simulation/adequacy_patch_runtime_data.h" - -#include "../solver/optimisation/opt_fonctions.h" -#include "sim_structure_probleme_economique.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" namespace { using namespace Antares::Data::AdequacyPatch; -double calculateQuadraticCost(const PROBLEME_HEBDO* problemeHebdo, const AdqPatchPTO priceTakingOrder, int hour, int area) +double calculateQuadraticCost(const PROBLEME_HEBDO* problemeHebdo, + const AdqPatchPTO priceTakingOrder, + int hour, + int area) { using namespace Data::AdequacyPatch; double priceTakingOrders = 0.0; // PTO if (priceTakingOrder == AdqPatchPTO::isLoad) { - priceTakingOrders - = problemeHebdo->ConsommationsAbattues[hour].ConsommationAbattueDuPays[area] - + problemeHebdo->AllMustRunGeneration[hour].AllMustRunGenerationOfArea[area]; + priceTakingOrders = problemeHebdo->ConsommationsAbattues[hour] + .ConsommationAbattueDuPays[area] + + problemeHebdo->AllMustRunGeneration[hour] + .AllMustRunGenerationOfArea[area]; } else // AdqPatchPTO::isDens { @@ -52,17 +49,18 @@ double calculateQuadraticCost(const PROBLEME_HEBDO* problemeHebdo, const AdqPatc } if (priceTakingOrders <= 0.0) + { return 0.0; + } else + { return (1. / priceTakingOrders); + } } } // namespace void HourlyCSRProblem::setQuadraticCost() { - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; - // variables: ENS for each area inside adq patch // obj function term is: 1 / (PTO) * ENS * ENS // => quadratic cost: 1 / (PTO) @@ -75,13 +73,14 @@ void HourlyCSRProblem::setQuadraticCost() if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[area]; + int var = variableManager_.PositiveUnsuppliedEnergy(area, triggeredHour); if (var >= 0 && var < problemeAResoudre_.NombreDeVariables) { - problemeAResoudre_.CoutQuadratique[var] = calculateQuadraticCost(problemeHebdo_, - adqPatchParams_.curtailmentSharing.priceTakingOrder, - triggeredHour, - area); + problemeAResoudre_.CoutQuadratique[var] = calculateQuadraticCost( + problemeHebdo_, + adqPatchParams_.curtailmentSharing.priceTakingOrder, + triggeredHour, + area); logs.debug() << var << ". Quad C = " << problemeAResoudre_.CoutQuadratique[var]; } } @@ -91,8 +90,6 @@ void HourlyCSRProblem::setQuadraticCost() void HourlyCSRProblem::setLinearCost() { int var; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; // variables: transmission cost for links between nodes of type 2 (area inside adequacy patch) // obj function term is: Sum ( hurdle_cost_direct x flow_direct )+ Sum ( hurdle_cost_indirect x @@ -111,39 +108,49 @@ void HourlyCSRProblem::setLinearCost() { continue; } - const double coeff - = problemeHebdo_->adequacyPatchRuntimeData->hurdleCostCoefficients[Interco]; + const double coeff = problemeHebdo_->adequacyPatchRuntimeData + ->hurdleCostCoefficients[Interco]; const COUTS_DE_TRANSPORT& TransportCost = problemeHebdo_->CoutDeTransport[Interco]; // flow - var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[Interco]; + var = variableManager_.NTCDirect(Interco, triggeredHour); if (var >= 0 && var < problemeAResoudre_.NombreDeVariables) { problemeAResoudre_.CoutLineaire[var] = 0.0; logs.debug() << var << ". Linear C = " << problemeAResoudre_.CoutLineaire[var]; } // direct / indirect flow - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + var = variableManager_.IntercoDirectCost(Interco, triggeredHour); if (var >= 0 && var < problemeAResoudre_.NombreDeVariables) { if (!TransportCost.IntercoGereeAvecDesCouts) + { problemeAResoudre_.CoutLineaire[var] = 0; + } else - problemeAResoudre_.CoutLineaire[var] - = TransportCost.CoutDeTransportOrigineVersExtremite[triggeredHour] * coeff; + { + problemeAResoudre_.CoutLineaire[var] = TransportCost + .CoutDeTransportOrigineVersExtremite + [triggeredHour] + * coeff; + } logs.debug() << var << ". Linear C = " << problemeAResoudre_.CoutLineaire[var]; } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + var = variableManager_.IntercoIndirectCost(Interco, triggeredHour); if (var >= 0 && var < problemeAResoudre_.NombreDeVariables) { if (!TransportCost.IntercoGereeAvecDesCouts) + { problemeAResoudre_.CoutLineaire[var] = 0; + } else - problemeAResoudre_.CoutLineaire[var] - = TransportCost.CoutDeTransportExtremiteVersOrigine[triggeredHour] * coeff; + { + problemeAResoudre_.CoutLineaire[var] = TransportCost + .CoutDeTransportExtremiteVersOrigine + [triggeredHour] + * coeff; + } logs.debug() << var << ". Linear C = " << problemeAResoudre_.CoutLineaire[var]; } } diff --git a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp index 0bb5d91925..1ec76ca553 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -1,49 +1,36 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/sim_structure_donnees.h" -#include "../simulation/adequacy_patch_runtime_data.h" +#include -#include "../solver/optimisation/opt_fonctions.h" - -#include "pi_constantes_externes.h" -#include "sim_structure_probleme_economique.h" - -#include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" using namespace Yuni; void HourlyCSRProblem::setBoundsOnENS() { double* AdresseDuResultat; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; // variables: ENS for each area inside adq patch for (uint32_t area = 0; area < problemeHebdo_->NombreDePays; ++area) @@ -51,12 +38,12 @@ void HourlyCSRProblem::setBoundsOnENS() if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[area]; + int var = variableManager_.PositiveUnsuppliedEnergy(area, triggeredHour); problemeAResoudre_.Xmin[var] = -belowThisThresholdSetToZero; - problemeAResoudre_.Xmax[var] - = problemeHebdo_->ResultatsHoraires[area].ValeursHorairesDENS[triggeredHour] - + belowThisThresholdSetToZero; + problemeAResoudre_.Xmax[var] = problemeHebdo_->ResultatsHoraires[area] + .ValeursHorairesDENS[triggeredHour] + + belowThisThresholdSetToZero; problemeAResoudre_.X[var] = problemeHebdo_->ResultatsHoraires[area] .ValeursHorairesDeDefaillancePositive[triggeredHour]; @@ -75,16 +62,13 @@ void HourlyCSRProblem::setBoundsOnENS() void HourlyCSRProblem::setBoundsOnSpilledEnergy() { - const auto& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; - // variables: Spilled Energy for each area inside adq patch for (uint32_t area = 0; area < problemeHebdo_->NombreDePays; ++area) { if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillanceNegative[area]; + int var = variableManager_.NegativeUnsuppliedEnergy(area, triggeredHour); problemeAResoudre_.Xmin[var] = -belowThisThresholdSetToZero; problemeAResoudre_.Xmax[var] = LINFINI_ANTARES; @@ -106,8 +90,6 @@ void HourlyCSRProblem::setBoundsOnSpilledEnergy() void HourlyCSRProblem::setBoundsOnFlows() { - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo_->CorrespondanceVarNativesVarOptim[triggeredHour]; std::vector& Xmin = problemeAResoudre_.Xmin; std::vector& Xmax = problemeAResoudre_.Xmax; VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeNTC = problemeHebdo_->ValeursDeNTC[triggeredHour]; @@ -127,24 +109,34 @@ void HourlyCSRProblem::setBoundsOnFlows() } // flow - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[Interco] + belowThisThresholdSetToZero; - Xmin[var] = -(ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[Interco]) - belowThisThresholdSetToZero; + int var = variableManager_.NTCDirect(Interco, triggeredHour); + Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[Interco] + + belowThisThresholdSetToZero; + Xmin[var] = -(ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[Interco]) + - belowThisThresholdSetToZero; problemeAResoudre_.X[var] = ValeursDeNTC.ValeurDuFlux[Interco]; - if (Math::Infinite(Xmax[var]) == 1) + if (std::isinf(Xmax[var])) { - if (Math::Infinite(Xmin[var]) == -1) + if (std::isinf(Xmin[var])) + { problemeAResoudre_.TypeDeVariable[var] = VARIABLE_NON_BORNEE; + } else + { problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; + } } else { - if (Math::Infinite(Xmin[var]) == -1) + if (std::isinf(Xmin[var])) + { problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_SUPERIEUREMENT; + } else + { problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } } double* AdresseDuResultat = &(ValeursDeNTC.ValeurDuFlux[Interco]); @@ -154,13 +146,13 @@ void HourlyCSRProblem::setBoundsOnFlows() << problemeAResoudre_.Xmax[var]; // direct / indirect flow - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + var = variableManager_.IntercoDirectCost(Interco, triggeredHour); Xmin[var] = -belowThisThresholdSetToZero; - Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[Interco] + belowThisThresholdSetToZero; + Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[Interco] + + belowThisThresholdSetToZero; problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[var]) == 1) + if (std::isinf(Xmax[var])) { problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; } @@ -168,13 +160,13 @@ void HourlyCSRProblem::setBoundsOnFlows() logs.debug() << var << ": " << problemeAResoudre_.Xmin[var] << ", " << problemeAResoudre_.Xmax[var]; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + var = variableManager_.IntercoIndirectCost(Interco, triggeredHour); Xmin[var] = -belowThisThresholdSetToZero; - Xmax[var] = ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[Interco] + belowThisThresholdSetToZero; + Xmax[var] = ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[Interco] + + belowThisThresholdSetToZero; problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[var]) == 1) + if (std::isinf(Xmax[var])) { problemeAResoudre_.TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; } diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index a7b3e90af4..4d209f1ade 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -1,36 +1,28 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_structure_probleme_economique.h" - -#include "../solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/solver/simulation/simulation.h" /* pi_define.h doesn't include this header, yet it uses struct jmp_buf. @@ -70,8 +62,9 @@ std::unique_ptr buildInteriorPointProblem( Probleme->IndicesDebutDeLigne = ProblemeAResoudre.IndicesDebutDeLigne.data(); Probleme->NombreDeTermesDesLignes = ProblemeAResoudre.NombreDeTermesDesLignes.data(); Probleme->IndicesColonnes = ProblemeAResoudre.IndicesColonnes.data(); - Probleme->CoefficientsDeLaMatriceDesContraintes - = ProblemeAResoudre.CoefficientsDeLaMatriceDesContraintes.data(); + Probleme->CoefficientsDeLaMatriceDesContraintes = ProblemeAResoudre + .CoefficientsDeLaMatriceDesContraintes + .data(); Probleme->Sens = ProblemeAResoudre.Sens.data(); Probleme->SecondMembre = ProblemeAResoudre.SecondMembre.data(); @@ -98,7 +91,9 @@ void setToZeroIfBelowThreshold(PROBLEME_ANTARES_A_RESOUDRE& ProblemeAResoudre, != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); bool belowLimit = ProblemeAResoudre.X[var] < hourlyCsrProblem.belowThisThresholdSetToZero; if (inSet && belowLimit) + { ProblemeAResoudre.X[var] = 0.0; + } } } @@ -107,7 +102,9 @@ void storeInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE& ProblemeAResou for (int var = 0; var < ProblemeAResoudre.NombreDeVariables; var++) { if (double* pt = ProblemeAResoudre.AdresseOuPlacerLaValeurDesVariablesOptimisees[var]; pt) + { *pt = ProblemeAResoudre.X[var]; + } logs.debug() << "[CSR] X[" << var << "] = " << ProblemeAResoudre.X[var]; } @@ -133,12 +130,16 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE& Pro } if (!checkCost || (checkCost && deltaCost < 0.0)) + { storeInteriorPointResults(ProblemeAResoudre); + } else if (checkCost && deltaCost >= 0.0) + { logs.warning() << "[adq-patch] CSR optimization is providing solution with greater costs, optimum " "solution is set as LMR . year: " << yearNb + 1 << ". hour: " << weekNb * hoursInWeek + hourlyCsrProblem.triggeredHour + 1; + } } double calculateCSRcost(const PROBLEME_POINT_INTERIEUR& Probleme, @@ -157,7 +158,7 @@ double calculateCSRcost(const PROBLEME_POINT_INTERIEUR& Probleme, { logs.debug() << "i: " << i; if (hourlyCsrProblem.ensVariablesInsideAdqPatch.find(i) - != hourlyCsrProblem.ensVariablesInsideAdqPatch.end()) + != hourlyCsrProblem.ensVariablesInsideAdqPatch.end()) { cost += Probleme.X[i] * Probleme.X[i] * Probleme.CoutQuadratique[i]; logs.debug() << "X-Q: " << Probleme.X[i] * 1e3; @@ -167,9 +168,10 @@ double calculateCSRcost(const PROBLEME_POINT_INTERIEUR& Probleme, auto itLink = hourlyCsrProblem.linkInsideAdqPatch.find(i); if ((itLink == hourlyCsrProblem.linkInsideAdqPatch.end()) - || adqPatchParams.curtailmentSharing.includeHurdleCost - || !itLink->second.check()) + || adqPatchParams.curtailmentSharing.includeHurdleCost || !itLink->second.check()) + { continue; + } if (Probleme.X[i] >= 0) { @@ -191,7 +193,6 @@ double calculateCSRcost(const PROBLEME_POINT_INTERIEUR& Probleme, { logs.warning() << "VarIndirect < 0 detected, this should not happen"; continue; - } cost -= Probleme.X[i] * Probleme.CoutLineaire[varIndirect]; logs.debug() << "X-: " << Probleme.X[i] * 1e3; @@ -217,8 +218,10 @@ void CSR_DEBUG_HANDLE(const PROBLEME_POINT_INTERIEUR& Probleme) } for (int Cnt = 0; Cnt < Probleme.NombreDeContraintes; Cnt++) { - logs.info().appendFormat( - "Constraint %ld sens %c B %e", Cnt, Probleme.Sens[Cnt], Probleme.SecondMembre[Cnt]); + logs.info().appendFormat("Constraint %ld sens %c B %e", + Cnt, + Probleme.Sens[Cnt], + Probleme.SecondMembre[Cnt]); int il = Probleme.IndicesDebutDeLigne[Cnt]; int ilMax = il + Probleme.NombreDeTermesDesLignes[Cnt]; @@ -235,7 +238,7 @@ void CSR_DEBUG_HANDLE(const PROBLEME_POINT_INTERIEUR& Probleme) } } -void handleInteriorPointError(const PROBLEME_POINT_INTERIEUR& Probleme, +void handleInteriorPointError([[maybe_unused]] const PROBLEME_POINT_INTERIEUR& Probleme, int hour, uint weekNb, int yearNb) @@ -257,13 +260,17 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE& ProblemeAResoudre, int yearNb) { auto interiorPointProblem = buildInteriorPointProblem(ProblemeAResoudre); - double costPriorToCsr = calculateCSRcost(*interiorPointProblem, hourlyCsrProblem, adqPatchParams); + double costPriorToCsr = calculateCSRcost(*interiorPointProblem, + hourlyCsrProblem, + adqPatchParams); PI_Quamin(interiorPointProblem.get()); // resolution if (interiorPointProblem->ExistenceDUneSolution == OUI_PI) { setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); - double costAfterCsr = calculateCSRcost(*interiorPointProblem, hourlyCsrProblem, adqPatchParams); - storeOrDisregardInteriorPointResults(ProblemeAResoudre, + double costAfterCsr = calculateCSRcost(*interiorPointProblem, + hourlyCsrProblem, + adqPatchParams); + storeOrDisregardInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem, adqPatchParams, weekNb, @@ -274,7 +281,10 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE& ProblemeAResoudre, } else { - handleInteriorPointError(*interiorPointProblem, hourlyCsrProblem.triggeredHour, weekNb, yearNb); + handleInteriorPointError(*interiorPointProblem, + hourlyCsrProblem.triggeredHour, + weekNb, + yearNb); return false; } } diff --git a/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.cpp b/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.cpp index 21b7a0712e..8129d10845 100644 --- a/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.cpp +++ b/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.cpp @@ -1,34 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ -#include "adequacy_patch_weekly_optimization.h" -#include "../opt_fonctions.h" -#include "../simulation/simulation.h" -#include "../simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h" + +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" #include "antares/study/fwd.h" using namespace Antares::Data::AdequacyPatch; @@ -41,29 +36,43 @@ AdequacyPatchOptimization::AdequacyPatchOptimization(const Antares::Data::Study& PROBLEME_HEBDO* problemeHebdo, AdqPatchParams& adqPatchParams, uint thread_number, - IResultWriter& writer) : - WeeklyOptimization(options, problemeHebdo, adqPatchParams, thread_number, writer), study_(study) + IResultWriter& writer, + Simulation::ISimulationObserver& observer): + WeeklyOptimization(options, problemeHebdo, adqPatchParams, thread_number, writer, observer), + study_(study) { } -void AdequacyPatchOptimization::solve(uint weekInTheYear, int hourInTheYear) +void AdequacyPatchOptimization::solve() { + Simulation::NullSimulationObserver nullSimulationObserver; problemeHebdo_->adequacyPatchRuntimeData->AdequacyFirstStep = true; - OPT_OptimisationHebdomadaire(options_, problemeHebdo_, adqPatchParams_, writer_); + OPT_OptimisationHebdomadaire(options_, + problemeHebdo_, + adqPatchParams_, + writer_, + nullSimulationObserver); problemeHebdo_->adequacyPatchRuntimeData->AdequacyFirstStep = false; for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; ++pays) { if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[pays] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { problemeHebdo_->ResultatsHoraires[pays].ValeursHorairesDENS - = problemeHebdo_->ResultatsHoraires[pays].ValeursHorairesDeDefaillancePositive; + = problemeHebdo_->ResultatsHoraires[pays].ValeursHorairesDeDefaillancePositive; + } else - std::fill(problemeHebdo_->ResultatsHoraires[pays].ValeursHorairesDENS.begin(), - problemeHebdo_->ResultatsHoraires[pays].ValeursHorairesDENS.end(), 0); + { + std::ranges::fill(problemeHebdo_->ResultatsHoraires[pays].ValeursHorairesDENS, 0); + } } - - OPT_OptimisationHebdomadaire(options_, problemeHebdo_, adqPatchParams_, writer_); + + OPT_OptimisationHebdomadaire(options_, + problemeHebdo_, + adqPatchParams_, + writer_, + nullSimulationObserver); } } // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h b/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h deleted file mode 100644 index d62c53a10c..0000000000 --- a/src/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include "../base_weekly_optimization.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include "../simulation/sim_structure_donnees.h" -#include "antares/study/area/area.h" - -using Antares::Data::AreaList; - -namespace Antares::Solver::Optimization -{ -class AdequacyPatchOptimization : public WeeklyOptimization -{ -public: - explicit AdequacyPatchOptimization(const Antares::Data::Study& study, - const OptimizationOptions& options, - PROBLEME_HEBDO* problemeHebdo, - Antares::Data::AdequacyPatch::AdqPatchParams&, - uint numSpace, - IResultWriter& writer); - - ~AdequacyPatchOptimization() override = default; - void solve(uint weekInTheYear, int hourInTheYear) override; -private: - const Antares::Data::Study& study_; -}; -} // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.cpp b/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.cpp index 7bdb3f93a2..e61b843403 100644 --- a/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.cpp +++ b/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.cpp @@ -1,32 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "adq_patch_local_matching.h" -#include "../simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h" + +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" namespace Antares::Data::AdequacyPatch { @@ -101,12 +96,14 @@ static NtcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* probl const AdqPatchParams& adqPatchParams, int Interco) { - AdequacyPatchMode OriginNodeAdequacyPatchType - = problemeHebdo->adequacyPatchRuntimeData->originAreaMode[Interco]; - AdequacyPatchMode ExtremityNodeAdequacyPatchType - = problemeHebdo->adequacyPatchRuntimeData->extremityAreaMode[Interco]; - bool setToZeroNTCfromOutToIn_AdqPatch = adqPatchParams.localMatching.setToZeroOutsideInsideLinks; - bool setToZeroNTCfromOutToOut_AdqPatch = adqPatchParams.localMatching.setToZeroOutsideOutsideLinks; + AdequacyPatchMode OriginNodeAdequacyPatchType = problemeHebdo->adequacyPatchRuntimeData + ->originAreaMode[Interco]; + AdequacyPatchMode ExtremityNodeAdequacyPatchType = problemeHebdo->adequacyPatchRuntimeData + ->extremityAreaMode[Interco]; + bool setToZeroNTCfromOutToIn_AdqPatch = adqPatchParams.localMatching + .setToZeroOutsideInsideLinks; + bool setToZeroNTCfromOutToOut_AdqPatch = adqPatchParams.localMatching + .setToZeroOutsideOutsideLinks; switch (OriginNodeAdequacyPatchType) { diff --git a/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h b/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h deleted file mode 100644 index a6bc6dae2c..0000000000 --- a/src/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include "../simulation/sim_structure_probleme_economique.h" - -namespace Antares::Data::AdequacyPatch -{ -/*! - * Sets link bounds for first step of adequacy patch or leaves default values if adequacy patch is - * not used. - */ -void setNTCbounds(double& Xmax, - double& Xmin, - const VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeNTC, - const int Interco, - PROBLEME_HEBDO* problemeHebdo, - const AdqPatchParams& adqPatchParams); - -} // namespace Antares::Data::AdequacyPatch diff --git a/src/solver/optimisation/base_weekly_optimization.cpp b/src/solver/optimisation/base_weekly_optimization.cpp index a808444861..623331485e 100644 --- a/src/solver/optimisation/base_weekly_optimization.cpp +++ b/src/solver/optimisation/base_weekly_optimization.cpp @@ -1,34 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/optimisation/base_weekly_optimization.h" #include -#include "base_weekly_optimization.h" -#include "weekly_optimization.h" -#include "adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h" + +#include "antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h" +#include "antares/solver/optimisation/weekly_optimization.h" using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; @@ -38,27 +34,45 @@ WeeklyOptimization::WeeklyOptimization(const OptimizationOptions& options, PROBLEME_HEBDO* problemesHebdo, AdqPatchParams& adqPatchParams, uint thread_number, - IResultWriter& writer) : + IResultWriter& writer, + Simulation::ISimulationObserver& simulationObserver): options_(options), problemeHebdo_(problemesHebdo), adqPatchParams_(adqPatchParams), thread_number_(thread_number), - writer_(writer) + writer_(writer), + simulationObserver_(simulationObserver) { } std::unique_ptr WeeklyOptimization::create( - const Antares::Data::Study& study, - const OptimizationOptions& options, - AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemeHebdo, - uint thread_number, - IResultWriter& writer) + const Antares::Data::Study& study, + const OptimizationOptions& options, + AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + uint thread_number, + IResultWriter& writer, + Simulation::ISimulationObserver& simulationObserver) { if (adqPatchParams.enabled && adqPatchParams.localMatching.enabled) - return std::make_unique(study, options, problemeHebdo, adqPatchParams, thread_number, writer); + { + return std::make_unique(study, + options, + problemeHebdo, + adqPatchParams, + thread_number, + writer, + simulationObserver); + } else - return std::make_unique(options, problemeHebdo, adqPatchParams, thread_number, writer); + { + return std::make_unique(options, + problemeHebdo, + adqPatchParams, + thread_number, + writer, + simulationObserver); + } } } // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/base_weekly_optimization.h b/src/solver/optimisation/base_weekly_optimization.h deleted file mode 100644 index 41fa3fa43d..0000000000 --- a/src/solver/optimisation/base_weekly_optimization.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include // for "uint" definition -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include - -namespace Antares::Solver::Optimization -{ -class WeeklyOptimization -{ -public: - virtual void solve(uint weekInTheYear, int hourInTheYear) = 0; - virtual ~WeeklyOptimization() = default; - static std::unique_ptr create(const Antares::Data::Study& study, - const OptimizationOptions& options, - Antares::Data::AdequacyPatch::AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemesHebdo, - uint numSpace, - IResultWriter& writer); - -protected: - explicit WeeklyOptimization(const OptimizationOptions& options, - PROBLEME_HEBDO* problemesHebdo, - Antares::Data::AdequacyPatch::AdqPatchParams&, - uint numSpace, - IResultWriter& writer); - Antares::Solver::Optimization::OptimizationOptions options_; - PROBLEME_HEBDO* const problemeHebdo_ = nullptr; - Antares::Data::AdequacyPatch::AdqPatchParams& adqPatchParams_; - const uint thread_number_ = 0; - IResultWriter& writer_; -}; -} // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/constraints/AbstractStartUpCostsGroup.cpp b/src/solver/optimisation/constraints/AbstractStartUpCostsGroup.cpp new file mode 100644 index 0000000000..6e0cfc0e93 --- /dev/null +++ b/src/solver/optimisation/constraints/AbstractStartUpCostsGroup.cpp @@ -0,0 +1,36 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/AbstractStartUpCostsGroup.h" + +AbstractStartUpCostsGroup::AbstractStartUpCostsGroup(PROBLEME_HEBDO* problemeHebdo, + bool simulation, + ConstraintBuilder& builder): + ConstraintGroup(problemeHebdo, builder), + simulation_(simulation) +{ +} + +StartUpCostsData AbstractStartUpCostsGroup::GetStartUpCostsDataFromProblemHebdo() +{ + return {.PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .Simulation = simulation_}; +} diff --git a/src/solver/optimisation/constraints/AreaBalance.cpp b/src/solver/optimisation/constraints/AreaBalance.cpp index 2a39f3be83..c0c254854d 100644 --- a/src/solver/optimisation/constraints/AreaBalance.cpp +++ b/src/solver/optimisation/constraints/AreaBalance.cpp @@ -1,51 +1,70 @@ -#include "AreaBalance.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/AreaBalance.h" static void shortTermStorageBalance(const ::ShortTermStorage::AREA_INPUT& shortTermStorageInput, ConstraintBuilder& constraintBuilder) { - for (const auto& storage : shortTermStorageInput) + for (const auto& storage: shortTermStorageInput) { unsigned index = storage.clusterGlobalIndex; constraintBuilder.ShortTermStorageInjection(index, 1.0) - .ShortTermStorageWithdrawal(index, -1.0); + .ShortTermStorageWithdrawal(index, -1.0); } } void AreaBalance::add(int pdt, int pays) { - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesBilansPays[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.CorrespondanceCntNativesCntOptim[pdt].NumeroDeContrainteDesBilansPays[pays] + = builder.data.nombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.AreaBalance(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.AreaBalance(builder.data.nombreDeContraintes); - builder.updateHourWithinWeek(pdt); + builder.updateHourWithinWeek(pdt); - int interco = problemeHebdo->IndexDebutIntercoOrigine[pays]; - while (interco >= 0) - { + int interco = data.IndexDebutIntercoOrigine[pays]; + while (interco >= 0) + { builder.NTCDirect(interco, 1.0); - interco = problemeHebdo->IndexSuivantIntercoOrigine[interco]; - } + interco = data.IndexSuivantIntercoOrigine[interco]; + } - interco = problemeHebdo->IndexDebutIntercoExtremite[pays]; + interco = data.IndexDebutIntercoExtremite[pays]; while (interco >= 0) { builder.NTCDirect(interco, -1.0); - interco = problemeHebdo->IndexSuivantIntercoExtremite[interco]; + interco = data.IndexSuivantIntercoExtremite[interco]; } - exportPaliers(*problemeHebdo, builder, pays); + ExportPaliers(data.PaliersThermiquesDuPays[pays], builder); builder.HydProd(pays, -1.0) .Pumping(pays, 1.0) .PositiveUnsuppliedEnergy(pays, -1.0) .NegativeUnsuppliedEnergy(pays, 1.0); - shortTermStorageBalance(problemeHebdo->ShortTermStorage[pays], builder); + shortTermStorageBalance(data.ShortTermStorage[pays], builder); builder.equalTo(); builder.build(); diff --git a/src/solver/optimisation/constraints/AreaBalance.h b/src/solver/optimisation/constraints/AreaBalance.h deleted file mode 100644 index a800a288ed..0000000000 --- a/src/solver/optimisation/constraints/AreaBalance.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Area Balance' constraint type - */ -class AreaBalance : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param pays : area - */ - void add(int pdt, int pays); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/AreaHydroLevel.cpp b/src/solver/optimisation/constraints/AreaHydroLevel.cpp index 228620b519..dffda330ca 100644 --- a/src/solver/optimisation/constraints/AreaHydroLevel.cpp +++ b/src/solver/optimisation/constraints/AreaHydroLevel.cpp @@ -1,32 +1,53 @@ -#include "AreaHydroLevel.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/AreaHydroLevel.h" void AreaHydroLevel::add(int pays, int pdt) { - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesNiveauxPays[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - if (problemeHebdo->CaracteristiquesHydrauliques[pays].SuiviNiveauHoraire) + data.CorrespondanceCntNativesCntOptim[pdt].NumeroDeContrainteDesNiveauxPays[pays] + = builder.data.nombreDeContraintes; + if (data.CaracteristiquesHydrauliques[pays].SuiviNiveauHoraire) { builder.updateHourWithinWeek(pdt).HydroLevel(pays, 1.0); if (pdt > 0) { builder.updateHourWithinWeek(pdt - 1).HydroLevel(pays, -1.0); } - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.AreaHydroLevel(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesNiveauxPays[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.AreaHydroLevel(builder.data.nombreDeContraintes); + data.CorrespondanceCntNativesCntOptim[pdt].NumeroDeContrainteDesNiveauxPays[pays] + = builder.data.nombreDeContraintes; builder.updateHourWithinWeek(pdt) .HydProd(pays, 1.0) - .Pumping(pays, -problemeHebdo->CaracteristiquesHydrauliques[pays].PumpingRatio) + .Pumping(pays, -data.CaracteristiquesHydrauliques[pays].PumpingRatio) .Overflow(pays, 1.) .equalTo() .build(); } else - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesNiveauxPays[pays] = -1; -} \ No newline at end of file + { + data.CorrespondanceCntNativesCntOptim[pdt].NumeroDeContrainteDesNiveauxPays[pays] = -1; + } +} diff --git a/src/solver/optimisation/constraints/AreaHydroLevel.h b/src/solver/optimisation/constraints/AreaHydroLevel.h deleted file mode 100644 index 2af93b076c..0000000000 --- a/src/solver/optimisation/constraints/AreaHydroLevel.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Area Hydraulic Level' constraint type - */ -class AreaHydroLevel : private ConstraintFactory -{ - public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param pays : area - */ - void add(int pays, int pdt); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/AreaHydroLevelGroup.cpp b/src/solver/optimisation/constraints/AreaHydroLevelGroup.cpp new file mode 100644 index 0000000000..c8c7e4a515 --- /dev/null +++ b/src/solver/optimisation/constraints/AreaHydroLevelGroup.cpp @@ -0,0 +1,42 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/AreaHydroLevelGroup.h" + +AreaHydroLevelData AreaHydroLevelGroup::GetAreaHydroLevelData() +{ + return {.CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim, + .CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques}; +} + +void AreaHydroLevelGroup::BuildConstraints() +{ + auto areaHydroLevelData = GetAreaHydroLevelData(); + AreaHydroLevel areaHydroLevel(builder_, areaHydroLevelData); + + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + areaHydroLevel.add(pays, pdt); + } + } +} diff --git a/src/solver/optimisation/constraints/BindingConstraintDay.cpp b/src/solver/optimisation/constraints/BindingConstraintDay.cpp index d55a7edb15..fb460c4da0 100644 --- a/src/solver/optimisation/constraints/BindingConstraintDay.cpp +++ b/src/solver/optimisation/constraints/BindingConstraintDay.cpp @@ -1,26 +1,47 @@ -#include "BindingConstraintDay.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/BindingConstraintDay.h" void BindingConstraintDay::add(int cntCouplante) { const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes - = problemeHebdo->MatriceDesContraintesCouplantes[cntCouplante]; + = data.MatriceDesContraintesCouplantes[cntCouplante]; if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante != CONTRAINTE_JOURNALIERE) + { return; + } - const int nbInterco - = MatriceDesContraintesCouplantes.NombreDInterconnexionsDansLaContrainteCouplante; - const int nbClusters - = MatriceDesContraintesCouplantes.NombreDePaliersDispatchDansLaContrainteCouplante; + const int nbInterco = MatriceDesContraintesCouplantes + .NombreDInterconnexionsDansLaContrainteCouplante; + const int nbClusters = MatriceDesContraintesCouplantes + .NombreDePaliersDispatchDansLaContrainteCouplante; - const int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; - const int NombreDePasDeTempsDUneJournee = problemeHebdo->NombreDePasDeTempsDUneJournee; + const int NombreDePasDeTempsPourUneOptimisation = builder.data + .NombreDePasDeTempsPourUneOptimisation; + const int NombreDePasDeTempsDUneJournee = data.NombreDePasDeTempsDUneJournee; int pdtDebut = 0; while (pdtDebut < NombreDePasDeTempsPourUneOptimisation) { - int jour = problemeHebdo->NumeroDeJourDuPasDeTemps[pdtDebut]; - CORRESPONDANCES_DES_CONTRAINTES_JOURNALIERES& CorrespondanceCntNativesCntOptimJournalieres - = problemeHebdo->CorrespondanceCntNativesCntOptimJournalieres[jour]; + int jour = data.NumeroDeJourDuPasDeTemps[pdtDebut]; for (int index = 0; index < nbInterco; index++) { @@ -30,40 +51,42 @@ void BindingConstraintDay::add(int cntCouplante) for (int pdt = pdtDebut; pdt < pdtDebut + NombreDePasDeTempsDUneJournee; pdt++) { - builder.updateHourWithinWeek(pdt).NTCDirect( - interco, poids, offset, problemeHebdo->NombreDePasDeTemps); + builder.updateHourWithinWeek(pdt).NTCDirect(interco, + poids, + offset, + builder.data.NombreDePasDeTemps); } } for (int index = 0; index < nbClusters; index++) { int pays = MatriceDesContraintesCouplantes.PaysDuPalierDispatch[index]; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques - [MatriceDesContraintesCouplantes.NumeroDuPalierDispatch[index]]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = data.PaliersThermiquesDuPays[pays]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques + [MatriceDesContraintesCouplantes.NumeroDuPalierDispatch[index]]; double poids = MatriceDesContraintesCouplantes.PoidsDuPalierDispatch[index]; int offset = MatriceDesContraintesCouplantes.OffsetTemporelSurLePalierDispatch[index]; for (int pdt = pdtDebut; pdt < pdtDebut + NombreDePasDeTempsDUneJournee; pdt++) { - builder.updateHourWithinWeek(pdt).DispatchableProduction( - palier, poids, offset, problemeHebdo->NombreDePasDeTemps); + builder.updateHourWithinWeek(pdt) + .DispatchableProduction(palier, poids, offset, builder.data.NombreDePasDeTemps); } } - CorrespondanceCntNativesCntOptimJournalieres + data.CorrespondanceCntNativesCntOptimJournalieres[jour] .NumeroDeContrainteDesContraintesCouplantes[cntCouplante] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + = builder.data.nombreDeContraintes; - char op = MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante; - builder.SetOperator(op); - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateTimeStep(jour); - namer.BindingConstraintDay(problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - MatriceDesContraintesCouplantes.NomDeLaContrainteCouplante); + builder.SetOperator(MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante); + { + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(jour); + namer.BindingConstraintDay(builder.data.nombreDeContraintes, + MatriceDesContraintesCouplantes.NomDeLaContrainteCouplante); + } builder.build(); - pdtDebut += problemeHebdo->NombreDePasDeTempsDUneJournee; + pdtDebut += data.NombreDePasDeTempsDUneJournee; } } diff --git a/src/solver/optimisation/constraints/BindingConstraintDay.h b/src/solver/optimisation/constraints/BindingConstraintDay.h deleted file mode 100644 index 1fff7b54a7..0000000000 --- a/src/solver/optimisation/constraints/BindingConstraintDay.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Daily Binding Constraint' type - */ -class BindingConstraintDay : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param cntCouplante : the binding constraint number - */ - void add(int cntCouplante); -}; diff --git a/src/solver/optimisation/constraints/BindingConstraintDayGroup.cpp b/src/solver/optimisation/constraints/BindingConstraintDayGroup.cpp new file mode 100644 index 0000000000..7947db7c50 --- /dev/null +++ b/src/solver/optimisation/constraints/BindingConstraintDayGroup.cpp @@ -0,0 +1,45 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/BindingConstraintDayGroup.h" + +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" + +BindingConstraintDayData BindingConstraintDayGroup::GetBindingConstraintDayDataFromProblemHebdo() +{ + return {.MatriceDesContraintesCouplantes = problemeHebdo_->MatriceDesContraintesCouplantes, + .PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .CorrespondanceCntNativesCntOptimJournalieres + = problemeHebdo_->CorrespondanceCntNativesCntOptimJournalieres, + .NombreDePasDeTempsDUneJournee = problemeHebdo_->NombreDePasDeTempsDUneJournee, + .NumeroDeJourDuPasDeTemps = problemeHebdo_->NumeroDeJourDuPasDeTemps}; +} + +void BindingConstraintDayGroup::BuildConstraints() +{ + auto bindingConstraintDayData = GetBindingConstraintDayDataFromProblemHebdo(); + BindingConstraintDay bindingConstraintDay(builder_, bindingConstraintDayData); + for (uint32_t cntCouplante = 0; cntCouplante < problemeHebdo_->NombreDeContraintesCouplantes; + cntCouplante++) + { + bindingConstraintDay.add(cntCouplante); + } +} diff --git a/src/solver/optimisation/constraints/BindingConstraintHour.cpp b/src/solver/optimisation/constraints/BindingConstraintHour.cpp index d6dfe999ac..d907f994c0 100644 --- a/src/solver/optimisation/constraints/BindingConstraintHour.cpp +++ b/src/solver/optimisation/constraints/BindingConstraintHour.cpp @@ -1,53 +1,79 @@ -#include "BindingConstraintHour.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/BindingConstraintHour.h" void BindingConstraintHour::add(int pdt, int cntCouplante) { + data.CorrespondanceCntNativesCntOptim[pdt] + .NumeroDeContrainteDesContraintesCouplantes[cntCouplante] + = builder.data.nombreDeContraintes; + const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes - = problemeHebdo->MatriceDesContraintesCouplantes[cntCouplante]; - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesContraintesCouplantes[cntCouplante] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + = data.MatriceDesContraintesCouplantes[cntCouplante]; if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante != CONTRAINTE_HORAIRE) + { return; + } builder.updateHourWithinWeek(pdt); // Links - const int nbInterco - = MatriceDesContraintesCouplantes.NombreDInterconnexionsDansLaContrainteCouplante; + const int nbInterco = MatriceDesContraintesCouplantes + .NombreDInterconnexionsDansLaContrainteCouplante; for (int index = 0; index < nbInterco; index++) { const int interco = MatriceDesContraintesCouplantes.NumeroDeLInterconnexion[index]; const double poids = MatriceDesContraintesCouplantes.PoidsDeLInterconnexion[index]; const int offset = MatriceDesContraintesCouplantes.OffsetTemporelSurLInterco[index]; - - builder.updateHourWithinWeek(pdt).NTCDirect( - interco, poids, offset, problemeHebdo->NombreDePasDeTemps); + builder.updateHourWithinWeek(pdt).NTCDirect(interco, + poids, + offset, + builder.data.NombreDePasDeTemps); } // Thermal clusters - const int nbClusters - = MatriceDesContraintesCouplantes.NombreDePaliersDispatchDansLaContrainteCouplante; + const int nbClusters = MatriceDesContraintesCouplantes + .NombreDePaliersDispatchDansLaContrainteCouplante; for (int index = 0; index < nbClusters; index++) { const int pays = MatriceDesContraintesCouplantes.PaysDuPalierDispatch[index]; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = data.PaliersThermiquesDuPays[pays]; const int palier = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques [MatriceDesContraintesCouplantes.NumeroDuPalierDispatch[index]]; const double poids = MatriceDesContraintesCouplantes.PoidsDuPalierDispatch[index]; const int offset = MatriceDesContraintesCouplantes.OffsetTemporelSurLePalierDispatch[index]; - builder.updateHourWithinWeek(pdt).DispatchableProduction( - palier, poids, offset, problemeHebdo->NombreDePasDeTemps); + builder.updateHourWithinWeek(pdt).DispatchableProduction(palier, + poids, + offset, + builder.data.NombreDePasDeTemps); } - char op = MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante; - builder.SetOperator(op); - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.BindingConstraintHour(problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - MatriceDesContraintesCouplantes.NomDeLaContrainteCouplante); + builder.SetOperator(MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante); + { + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.BindingConstraintHour(builder.data.nombreDeContraintes, + MatriceDesContraintesCouplantes.NomDeLaContrainteCouplante); + } builder.build(); } diff --git a/src/solver/optimisation/constraints/BindingConstraintHour.h b/src/solver/optimisation/constraints/BindingConstraintHour.h deleted file mode 100644 index bad823047d..0000000000 --- a/src/solver/optimisation/constraints/BindingConstraintHour.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Hourly Binding Constraint' type - */ -class BindingConstraintHour : private ConstraintFactory -{ - public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param cntCouplante : the binding constraint number - */ - void add(int pdt, int cntCouplante); -}; diff --git a/src/solver/optimisation/constraints/BindingConstraintWeek.cpp b/src/solver/optimisation/constraints/BindingConstraintWeek.cpp index 4524c2702b..8802d7c7bd 100644 --- a/src/solver/optimisation/constraints/BindingConstraintWeek.cpp +++ b/src/solver/optimisation/constraints/BindingConstraintWeek.cpp @@ -1,59 +1,79 @@ -#include "BindingConstraintWeek.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/BindingConstraintWeek.h" void BindingConstraintWeek::add(int cntCouplante) { + int semaine = builder.data.weekInTheYear; + const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes - = problemeHebdo->MatriceDesContraintesCouplantes[cntCouplante]; - int semaine = problemeHebdo->weekInTheYear; - CORRESPONDANCES_DES_CONTRAINTES_HEBDOMADAIRES& CorrespondanceCntNativesCntOptimHebdomadaires - = problemeHebdo->CorrespondanceCntNativesCntOptimHebdomadaires; + = data.MatriceDesContraintesCouplantes[cntCouplante]; if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante != CONTRAINTE_HEBDOMADAIRE) + { return; + } - const int nbInterco - = MatriceDesContraintesCouplantes.NombreDInterconnexionsDansLaContrainteCouplante; - const int nbClusters - = MatriceDesContraintesCouplantes.NombreDePaliersDispatchDansLaContrainteCouplante; + const int nbInterco = MatriceDesContraintesCouplantes + .NombreDInterconnexionsDansLaContrainteCouplante; + const int nbClusters = MatriceDesContraintesCouplantes + .NombreDePaliersDispatchDansLaContrainteCouplante; for (int index = 0; index < nbInterco; index++) { int interco = MatriceDesContraintesCouplantes.NumeroDeLInterconnexion[index]; double poids = MatriceDesContraintesCouplantes.PoidsDeLInterconnexion[index]; int offset = MatriceDesContraintesCouplantes.OffsetTemporelSurLInterco[index]; - for (int pdt = 0; pdt < problemeHebdo->NombreDePasDeTempsPourUneOptimisation; pdt++) + for (int pdt = 0; pdt < builder.data.NombreDePasDeTempsPourUneOptimisation; pdt++) { - builder.updateHourWithinWeek(pdt).NTCDirect( - interco, poids, offset, problemeHebdo->NombreDePasDeTemps); + builder.updateHourWithinWeek(pdt).NTCDirect(interco, + poids, + offset, + builder.data.NombreDePasDeTemps); } } - for (int index = 0; index < nbClusters; index++) + for (int index = 0; index < nbClusters; index++) + { + int pays = MatriceDesContraintesCouplantes.PaysDuPalierDispatch[index]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = data.PaliersThermiquesDuPays[pays]; + const int palier = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques + [MatriceDesContraintesCouplantes.NumeroDuPalierDispatch[index]]; + double poids = MatriceDesContraintesCouplantes.PoidsDuPalierDispatch[index]; + int offset = MatriceDesContraintesCouplantes.OffsetTemporelSurLePalierDispatch[index]; + for (int pdt = 0; pdt < builder.data.NombreDePasDeTempsPourUneOptimisation; pdt++) { - int pays = MatriceDesContraintesCouplantes.PaysDuPalierDispatch[index]; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques - [MatriceDesContraintesCouplantes.NumeroDuPalierDispatch[index]]; - double poids = MatriceDesContraintesCouplantes.PoidsDuPalierDispatch[index]; - int offset = MatriceDesContraintesCouplantes.OffsetTemporelSurLePalierDispatch[index]; - for (int pdt = 0; pdt < problemeHebdo->NombreDePasDeTempsPourUneOptimisation; pdt++) - { - builder.updateHourWithinWeek(pdt).DispatchableProduction( - palier, poids, offset, problemeHebdo->NombreDePasDeTemps); - } + builder.updateHourWithinWeek(pdt) + .DispatchableProduction(palier, poids, offset, builder.data.NombreDePasDeTemps); } + } - char op = MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante; - builder.SetOperator(op); + builder.SetOperator(MatriceDesContraintesCouplantes.SensDeLaContrainteCouplante); - CorrespondanceCntNativesCntOptimHebdomadaires - .NumeroDeContrainteDesContraintesCouplantes[cntCouplante] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteDesContraintesCouplantes[cntCouplante] = builder.data + .nombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); namer.UpdateTimeStep(semaine); - namer.BindingConstraintWeek(problemeHebdo->ProblemeAResoudre->NombreDeContraintes, + namer.BindingConstraintWeek(builder.data.nombreDeContraintes, MatriceDesContraintesCouplantes.NomDeLaContrainteCouplante); builder.build(); } diff --git a/src/solver/optimisation/constraints/BindingConstraintWeek.h b/src/solver/optimisation/constraints/BindingConstraintWeek.h deleted file mode 100644 index b94698e5d0..0000000000 --- a/src/solver/optimisation/constraints/BindingConstraintWeek.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Hourly Binding Constraint' type - */ -class BindingConstraintWeek : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param cntCouplante : the binding constraint number - */ - void add(int cntCouplante); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/BindingConstraintWeekGroup.cpp b/src/solver/optimisation/constraints/BindingConstraintWeekGroup.cpp new file mode 100644 index 0000000000..acd038c30d --- /dev/null +++ b/src/solver/optimisation/constraints/BindingConstraintWeekGroup.cpp @@ -0,0 +1,52 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/BindingConstraintWeekGroup.h" + +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" + +BindingConstraintWeekData BindingConstraintWeekGroup::GetBindingConstraintWeekDataFromProblemHebdo() +{ + return {.MatriceDesContraintesCouplantes = problemeHebdo_->MatriceDesContraintesCouplantes, + .PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .NumeroDeContrainteDesContraintesCouplantes + = problemeHebdo_->CorrespondanceCntNativesCntOptimHebdomadaires + .NumeroDeContrainteDesContraintesCouplantes}; +} + +void BindingConstraintWeekGroup::BuildConstraints() +{ + auto bindingConstraintWeekData = GetBindingConstraintWeekDataFromProblemHebdo(); + BindingConstraintWeek bindingConstraintWeek(builder_, bindingConstraintWeekData); + + if (problemeHebdo_->NombreDePasDeTempsPourUneOptimisation + > problemeHebdo_->NombreDePasDeTempsDUneJournee) + { + CORRESPONDANCES_DES_CONTRAINTES_HEBDOMADAIRES& CorrespondanceCntNativesCntOptimHebdomadaires + = problemeHebdo_->CorrespondanceCntNativesCntOptimHebdomadaires; + for (uint32_t cntCouplante = 0; + cntCouplante < problemeHebdo_->NombreDeContraintesCouplantes; + cntCouplante++) + { + bindingConstraintWeek.add(cntCouplante); + } + } +} diff --git a/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.cpp b/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.cpp index 03119ed030..300cdbaef5 100644 --- a/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.cpp +++ b/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.cpp @@ -1,22 +1,40 @@ -#include "ConsistenceNumberOfDispatchableUnits.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void ConsistenceNumberOfDispatchableUnits::add(int pays, - int cluster, - int clusterIndex, - int pdt, - bool Simulation) +#include "antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h" + +void ConsistenceNumberOfDispatchableUnits::add(int pays, int index, int pdt) { - if (!Simulation) + if (!data.Simulation) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = builder.data + .NombreDePasDeTempsPourUneOptimisation; + auto cluster = data.PaliersThermiquesDuPays[pays] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; int Pdtmoins1 = pdt - 1; if (Pdtmoins1 < 0) + { Pdtmoins1 = NombreDePasDeTempsPourUneOptimisation + Pdtmoins1; + } builder.updateHourWithinWeek(pdt) .NumberOfDispatchableUnits(cluster, 1.0) @@ -29,19 +47,20 @@ void ConsistenceNumberOfDispatchableUnits::add(int pays, if (builder.NumberOfVariables() > 0) { - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.ConsistenceNODU(problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - PaliersThermiquesDuPays.NomsDesPaliersThermiques[clusterIndex]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.ConsistenceNODU( + builder.data.nombreDeContraintes, + data.PaliersThermiquesDuPays[pays].NomsDesPaliersThermiques[index]); builder.build(); } } else { - problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage += 4; - problemeHebdo->ProblemeAResoudre->NombreDeContraintes++; + builder.data.NbTermesContraintesPourLesCoutsDeDemarrage += 4; + builder.data.nombreDeContraintes++; } } diff --git a/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h b/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h deleted file mode 100644 index 43af772514..0000000000 --- a/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Consistence Number Of Dispatchable Units Constraint' type - */ -class ConsistenceNumberOfDispatchableUnits : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - * @param cluster : global index of the cluster - * @param pdt : timestep - * @param Simulation : --- - */ - void add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.cpp b/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.cpp new file mode 100644 index 0000000000..b0ef9ec842 --- /dev/null +++ b/src/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.cpp @@ -0,0 +1,46 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.h" + +#include "antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h" + +/** + * @brief build ConsistenceNumberOfDispatchableUnits constraints with + * respect to default order + */ +void ConsistenceNumberOfDispatchableUnitsGroup::BuildConstraints() +{ + auto data = GetStartUpCostsDataFromProblemHebdo(); + ConsistenceNumberOfDispatchableUnits consistenceNumberOfDispatchableUnits(builder_, data); + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo_ + ->PaliersThermiquesDuPays[pays]; + for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) + { + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + consistenceNumberOfDispatchableUnits.add(pays, index, pdt); + } + } + } +} diff --git a/src/solver/optimisation/constraints/ConstraintBuilder.cpp b/src/solver/optimisation/constraints/ConstraintBuilder.cpp index 195d8dad30..edac845526 100644 --- a/src/solver/optimisation/constraints/ConstraintBuilder.cpp +++ b/src/solver/optimisation/constraints/ConstraintBuilder.cpp @@ -1,100 +1,78 @@ -#include "ConstraintBuilder.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/ConstraintBuilder.h" void ConstraintBuilder::build() { - std::vector& Pi = problemeAResoudre.Pi; - std::vector& Colonne = problemeAResoudre.Colonne; - if (nombreDeTermes_ > 0) { - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - &problemeAResoudre, Pi, Colonne, nombreDeTermes_, operator_); + OPT_ChargerLaContrainteDansLaMatriceDesContraintes(); } nombreDeTermes_ = 0; } -int ConstraintBuilder::GetShiftedTimeStep(int offset, int delta) const -{ - int pdt = hourInWeek_ + offset; - const int nbTimeSteps = problemeHebdo.NombreDePasDeTempsPourUneOptimisation; - - if (const bool shifted_timestep = offset != 0; shifted_timestep) - { - if (offset >= 0) - { - pdt = pdt % nbTimeSteps; - } - else - { - pdt = (pdt + delta) % nbTimeSteps; - } - } - return pdt; -} - void ConstraintBuilder::AddVariable(int varIndex, double coeff) { - std::vector& Pi = problemeAResoudre.Pi; - std::vector& Colonne = problemeAResoudre.Colonne; if (varIndex >= 0) { - Pi[nombreDeTermes_] = coeff; - Colonne[nombreDeTermes_] = varIndex; + data.Pi[nombreDeTermes_] = coeff; + data.Colonne[nombreDeTermes_] = varIndex; nombreDeTermes_++; } } -Variable::VariableManager ConstraintBuilder::GetVariableManager(int offset, int delta) const -{ - auto pdt = GetShiftedTimeStep(offset, delta); - return Variable::VariableManager(varNative[pdt], - problemeHebdo.NumeroDeVariableStockFinal, - problemeHebdo.NumeroDeVariableDeTrancheDeStock); -} - ConstraintBuilder& ConstraintBuilder::DispatchableProduction(unsigned int index, double coeff, int offset, int delta) { - AddVariable(GetVariableManager(offset, delta).DispatchableProduction(index), coeff); + AddVariable(variableManager_.DispatchableProduction(index, hourInWeek_, offset, delta), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::NumberOfDispatchableUnits(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::NumberOfDispatchableUnits(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).NumberOfDispatchableUnits(index), coeff); + AddVariable(variableManager_.NumberOfDispatchableUnits(index, hourInWeek_), coeff); return *this; } ConstraintBuilder& ConstraintBuilder::NumberStoppingDispatchableUnits(unsigned int index, - double coeff, - int offset, - int delta) + double coeff) { - AddVariable(GetVariableManager(offset, delta).NumberStoppingDispatchableUnits(index), coeff); + AddVariable(variableManager_.NumberStoppingDispatchableUnits(index, hourInWeek_), coeff); return *this; } ConstraintBuilder& ConstraintBuilder::NumberStartingDispatchableUnits(unsigned int index, - double coeff, - int offset, - int delta) + double coeff) { - AddVariable(GetVariableManager(offset, delta).NumberStartingDispatchableUnits(index), coeff); + AddVariable(variableManager_.NumberStartingDispatchableUnits(index, hourInWeek_), coeff); return *this; } ConstraintBuilder& ConstraintBuilder::NumberBreakingDownDispatchableUnits(unsigned int index, - double coeff, - int offset, - int delta) + double coeff) { - AddVariable(GetVariableManager(offset, delta).NumberBreakingDownDispatchableUnits(index), - coeff); + AddVariable(variableManager_.NumberBreakingDownDispatchableUnits(index, hourInWeek_), coeff); return *this; } @@ -103,43 +81,31 @@ ConstraintBuilder& ConstraintBuilder::NTCDirect(unsigned int index, int offset, int delta) { - AddVariable(GetVariableManager(offset, delta).NTCDirect(index), coeff); + AddVariable(variableManager_.NTCDirect(index, hourInWeek_, offset, delta), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::IntercoDirectCost(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::IntercoDirectCost(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).IntercoDirectCost(index), coeff); + AddVariable(variableManager_.IntercoDirectCost(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::IntercoIndirectCost(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::IntercoIndirectCost(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).IntercoIndirectCost(index), coeff); + AddVariable(variableManager_.IntercoIndirectCost(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::ShortTermStorageInjection(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::ShortTermStorageInjection(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).ShortTermStorageInjection(index), coeff); + AddVariable(variableManager_.ShortTermStorageInjection(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::ShortTermStorageWithdrawal(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::ShortTermStorageWithdrawal(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).ShortTermStorageWithdrawal(index), coeff); + AddVariable(variableManager_.ShortTermStorageWithdrawal(index, hourInWeek_), coeff); return *this; } @@ -148,97 +114,107 @@ ConstraintBuilder& ConstraintBuilder::ShortTermStorageLevel(unsigned int index, int offset, int delta) { - AddVariable(GetVariableManager(offset, delta).ShortTermStorageLevel(index), coeff); + AddVariable(variableManager_.ShortTermStorageLevel(index, hourInWeek_, offset, delta), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::HydProd(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::HydProd(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).HydProd(index), coeff); + AddVariable(variableManager_.HydProd(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::HydProdDown(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::HydProdDown(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).HydProdDown(index), coeff); + AddVariable(variableManager_.HydProdDown(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::HydProdUp(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::HydProdUp(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).HydProdUp(index), coeff); + AddVariable(variableManager_.HydProdUp(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::Pumping(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::Pumping(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).Pumping(index), coeff); + AddVariable(variableManager_.Pumping(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::HydroLevel(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::HydroLevel(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).HydroLevel(index), coeff); + AddVariable(variableManager_.HydroLevel(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::Overflow(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::Overflow(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).Overflow(index), coeff); + AddVariable(variableManager_.Overflow(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::FinalStorage(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::FinalStorage(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).FinalStorage(index), coeff); + AddVariable(variableManager_.FinalStorage(index), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::PositiveUnsuppliedEnergy(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::PositiveUnsuppliedEnergy(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).PositiveUnsuppliedEnergy(index), coeff); + AddVariable(variableManager_.PositiveUnsuppliedEnergy(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::NegativeUnsuppliedEnergy(unsigned int index, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::NegativeUnsuppliedEnergy(unsigned int index, double coeff) { - AddVariable(GetVariableManager(offset, delta).NegativeUnsuppliedEnergy(index), coeff); + AddVariable(variableManager_.NegativeUnsuppliedEnergy(index, hourInWeek_), coeff); return *this; } -ConstraintBuilder& ConstraintBuilder::LayerStorage(unsigned area, - unsigned layer, - double coeff, - int offset, - int delta) +ConstraintBuilder& ConstraintBuilder::LayerStorage(unsigned area, unsigned layer, double coeff) { - AddVariable(GetVariableManager(offset, delta).LayerStorage(area, layer), coeff); + AddVariable(variableManager_.LayerStorage(area, layer), coeff); return *this; } + +void ConstraintBuilder::OPT_ChargerLaContrainteDansLaMatriceDesContraintes() +{ + data.IndicesDebutDeLigne[data.nombreDeContraintes] = data + .nombreDeTermesDansLaMatriceDeContrainte; + for (int i = 0; i < nombreDeTermes_; i++) + { + data.CoefficientsDeLaMatriceDesContraintes[data.nombreDeTermesDansLaMatriceDeContrainte] + = data.Pi[i]; + data.IndicesColonnes[data.nombreDeTermesDansLaMatriceDeContrainte] = data.Colonne[i]; + data.nombreDeTermesDansLaMatriceDeContrainte++; + if (data.nombreDeTermesDansLaMatriceDeContrainte + == data.NombreDeTermesAllouesDansLaMatriceDesContraintes) + { + OPT_AugmenterLaTailleDeLaMatriceDesContraintes(); + } + } + data.NombreDeTermesDesLignes[data.nombreDeContraintes] = nombreDeTermes_; + + data.Sens[data.nombreDeContraintes] = operator_; + data.nombreDeContraintes++; + + return; +} + +void ConstraintBuilder::OPT_AugmenterLaTailleDeLaMatriceDesContraintes() +{ + int NbTermes = data.NombreDeTermesAllouesDansLaMatriceDesContraintes; + NbTermes += data.IncrementDAllocationMatriceDesContraintes; + + logs.info(); + logs.info() << " Expected Number of Non-zero terms in Problem Matrix : increased to : " + << NbTermes; + logs.info(); + + data.CoefficientsDeLaMatriceDesContraintes.resize(NbTermes); + + data.IndicesColonnes.resize(NbTermes); + + data.NombreDeTermesAllouesDansLaMatriceDesContraintes = NbTermes; +} diff --git a/src/solver/optimisation/constraints/ConstraintBuilder.h b/src/solver/optimisation/constraints/ConstraintBuilder.h deleted file mode 100644 index 0ef7bf5675..0000000000 --- a/src/solver/optimisation/constraints/ConstraintBuilder.h +++ /dev/null @@ -1,383 +0,0 @@ -#pragma once - -#include -#include "../opt_structure_probleme_a_resoudre.h" -#include "../opt_rename_problem.h" -#include "../opt_fonctions.h" -#include "../../simulation/sim_structure_probleme_economique.h" - -#include - -namespace Variable -{ - -/*! -Factory class that hold variables indices -*/ -class VariableManager -{ -public: - VariableManager(const CORRESPONDANCES_DES_VARIABLES& nativeOptimVar, - const std::vector& NumeroDeVariableStockFinal, - const std::vector>& NumeroDeVariableDeTrancheDeStock) : - nativeOptimVar(nativeOptimVar), - NumeroDeVariableStockFinal(NumeroDeVariableStockFinal), - NumeroDeVariableDeTrancheDeStock(NumeroDeVariableDeTrancheDeStock) - { - } - - int DispatchableProduction(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDuPalierThermique[index]; - } - - int NumberOfDispatchableUnits(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDuNombreDeGroupesEnMarcheDuPalierThermique[index]; - } - - int NumberStoppingDispatchableUnits(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDuNombreDeGroupesQuiSArretentDuPalierThermique[index]; - } - - int NumberStartingDispatchableUnits(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDuNombreDeGroupesQuiDemarrentDuPalierThermique[index]; - } - - int NumberBreakingDownDispatchableUnits(unsigned int index) const - { - return nativeOptimVar - .NumeroDeVariableDuNombreDeGroupesQuiTombentEnPanneDuPalierThermique[index]; - } - - int NTCDirect(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDeLInterconnexion[index]; - } - - int IntercoDirectCost(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[index]; - } - - int IntercoIndirectCost(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[index]; - } - - int ShortTermStorageInjection(unsigned int index) const - { - return nativeOptimVar.SIM_ShortTermStorage.InjectionVariable[index]; - } - - int ShortTermStorageWithdrawal(unsigned int index) const - { - return nativeOptimVar.SIM_ShortTermStorage.WithdrawalVariable[index]; - } - - int ShortTermStorageLevel(unsigned int index) const - { - return nativeOptimVar.SIM_ShortTermStorage.LevelVariable[index]; - } - - int HydProd(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariablesDeLaProdHyd[index]; - } - - int HydProdDown(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariablesVariationHydALaBaisse[index]; - } - - int HydProdUp(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariablesVariationHydALaHausse[index]; - } - - int Pumping(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariablesDePompage[index]; - } - - int HydroLevel(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariablesDeNiveau[index]; - } - - int Overflow(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariablesDeDebordement[index]; - } - - int FinalStorage(unsigned int index) const - { - return NumeroDeVariableStockFinal[index]; - } - - int LayerStorage(unsigned area, unsigned layer) const - { - return NumeroDeVariableDeTrancheDeStock[area][layer]; - } - - int PositiveUnsuppliedEnergy(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDefaillancePositive[index]; - } - - int NegativeUnsuppliedEnergy(unsigned int index) const - { - return nativeOptimVar.NumeroDeVariableDefaillanceNegative[index]; - } - -private: - const CORRESPONDANCES_DES_VARIABLES& nativeOptimVar; - const std::vector& NumeroDeVariableStockFinal; - const std::vector>& NumeroDeVariableDeTrancheDeStock; -}; - -} // namespace Variable - -/*! \verbatim -this class build up the business object 'Constraint', -Math: -|coeff11 coeff12 .. coeff1n||var1| |sign_1| |rhs1| |constraint1||sign_1||rhs1| -|.. .. ...||....| |......| |....| <===> |...........||......||....| -|coeffn1 coeffn2 .. coeffnn||varn| |sign_n| |rhsn| |constraintn||sign_n||rhsn| - -it propose a set of methods to attach 'Variables' to the Constraint -ex: calling NTCDirect() implies adding Direct NTC Variable to the current Constraint -finally the build() method gather all variables and put them into the matrix -\endverbatim -*/ -class ConstraintBuilder -{ -public: - ConstraintBuilder( - PROBLEME_HEBDO& problemeHebdo, - const std::vector& CorrespondanceVarNativesVarOptim) : - problemeHebdo(problemeHebdo), - problemeAResoudre(*problemeHebdo.ProblemeAResoudre), - varNative(CorrespondanceVarNativesVarOptim) - { - } - - ConstraintBuilder& updateHourWithinWeek(unsigned hour) - { - hourInWeek_ = hour; - return *this; - } - - /** @name variables_method - * @brief Documentation for non obvious methods - * @param index: local index of the variable - * @param offset: offset from the current time step - * @param delta: number of time steps for the variable - * @return reference of *this - */ - //@{ - ConstraintBuilder& DispatchableProduction(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& NumberOfDispatchableUnits(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& NumberStoppingDispatchableUnits(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& NumberStartingDispatchableUnits(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& NumberBreakingDownDispatchableUnits(unsigned int index, - double coeff, - int offset = 0, - - int delta = 0); - - ConstraintBuilder& NTCDirect(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& IntercoDirectCost(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& IntercoIndirectCost(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& ShortTermStorageInjection(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& ShortTermStorageWithdrawal(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& ShortTermStorageLevel(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& HydProd(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& HydProdDown(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& HydProdUp(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& Pumping(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& HydroLevel(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& Overflow(unsigned int index, double coeff, int offset = 0, int delta = 0); - - ConstraintBuilder& FinalStorage(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& PositiveUnsuppliedEnergy(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - ConstraintBuilder& NegativeUnsuppliedEnergy(unsigned int index, - double coeff, - int offset = 0, - int delta = 0); - - ConstraintBuilder& LayerStorage(unsigned area, - unsigned layer, - double coeff, - int offset = 0, - int delta = 0); - //@} - - class ConstraintBuilderInvalidOperator : public std::runtime_error - { - public: - using std::runtime_error::runtime_error; - }; - - /*! - @brief set the operator of the constraint (sign) - @param op: the operator of the constraint - @return reference of *this - */ - ConstraintBuilder& SetOperator(char op) - { - if (op == '<' || op == '=' || op == '>') - { - operator_ = op; - } - else - throw ConstraintBuilderInvalidOperator(std::string("Invalid operator: ") + op); - - return *this; - } - - /*! - @brief set the sign of the constraint to '=', - building a constraint equal to rhs - @return reference of *this - */ - ConstraintBuilder& equalTo() - { - operator_ = '='; - return *this; - } - - /*! - @brief set the sign of the constraint to '<', - building a constraint less than rhs - @return reference of *this - */ - ConstraintBuilder& lessThan() - { - operator_ = '<'; - return *this; - } - - /*! - @brief set the sign of the constraint to '>', - building a constraint greather than rhs - @return reference of *this - */ - ConstraintBuilder& greaterThan() - { - operator_ = '>'; - return *this; - } - - /*! - @brief add the constraint in the matrix - @return - */ - void build(); - - int NumberOfVariables() const - { - return nombreDeTermes_; - } - -private: - PROBLEME_HEBDO& problemeHebdo; - PROBLEME_ANTARES_A_RESOUDRE& problemeAResoudre; - const std::vector& varNative; - - unsigned int hourInWeek_ = 0; - - char operator_ = '='; - int nombreDeTermes_ = 0; - - int GetShiftedTimeStep(int offset, int delta) const; - void AddVariable(int index, double coeff); - - /*! - * @brief - * @param offset: offset from the current time step - * @param delta: number of time steps for the variable - * @return VariableManager object - */ - Variable::VariableManager GetVariableManager(int offset = 0, int delta = 0) const; -}; - -/*! factory class to build a Constraint */ -class ConstraintFactory -{ -public: - explicit ConstraintFactory(PROBLEME_HEBDO* problemeHebdo) : - problemeHebdo(problemeHebdo), - builder(*problemeHebdo, problemeHebdo->CorrespondanceVarNativesVarOptim) - { - } - - PROBLEME_HEBDO* problemeHebdo; - ConstraintBuilder builder; -}; - -// Helper functions -inline void exportPaliers(const PROBLEME_HEBDO& problemeHebdo, - ConstraintBuilder& constraintBuilder, - int pays) -{ - const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo.PaliersThermiquesDuPays[pays]; - - for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) - { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - constraintBuilder.DispatchableProduction(palier, -1.0); - } -} diff --git a/src/solver/optimisation/constraints/ExchangeBalance.cpp b/src/solver/optimisation/constraints/ExchangeBalance.cpp new file mode 100644 index 0000000000..f268f37953 --- /dev/null +++ b/src/solver/optimisation/constraints/ExchangeBalance.cpp @@ -0,0 +1,45 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/ExchangeBalance.h" + +void ExchangeBalance::add(uint32_t pays) +{ + builder.updateHourWithinWeek(0); + + int interco = data.IndexDebutIntercoOrigine[pays]; + while (interco >= 0) + { + builder.NTCDirect(interco, 1.0); + interco = data.IndexSuivantIntercoOrigine[interco]; + } + interco = data.IndexDebutIntercoExtremite[pays]; + while (interco >= 0) + { + builder.NTCDirect(interco, -1.0); + + interco = data.IndexSuivantIntercoExtremite[interco]; + } + + data.NumeroDeContrainteDeSoldeDEchange[pays] = builder.data.nombreDeContraintes; + builder.equalTo(); + builder.build(); +} diff --git a/src/solver/optimisation/constraints/ExchangeBalanceGroup.cpp b/src/solver/optimisation/constraints/ExchangeBalanceGroup.cpp new file mode 100644 index 0000000000..d0c9734057 --- /dev/null +++ b/src/solver/optimisation/constraints/ExchangeBalanceGroup.cpp @@ -0,0 +1,41 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/ExchangeBalanceGroup.h" + +ExchangeBalanceData ExchangeBalanceGroup::GetExchangeBalanceDataFromProblemHebdo() +{ + return {.IndexDebutIntercoOrigine = problemeHebdo_->IndexDebutIntercoOrigine, + .IndexSuivantIntercoOrigine = problemeHebdo_->IndexSuivantIntercoOrigine, + .IndexDebutIntercoExtremite = problemeHebdo_->IndexDebutIntercoExtremite, + .IndexSuivantIntercoExtremite = problemeHebdo_->IndexSuivantIntercoExtremite, + .NumeroDeContrainteDeSoldeDEchange = problemeHebdo_->NumeroDeContrainteDeSoldeDEchange}; +} + +void ExchangeBalanceGroup::BuildConstraints() +{ + auto data = GetExchangeBalanceDataFromProblemHebdo(); + ExchangeBalance exchangeBalance(builder_, data); + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays - 1; pays++) + { + exchangeBalance.add(pays); + } +} diff --git a/src/solver/optimisation/constraints/FictitiousLoad.cpp b/src/solver/optimisation/constraints/FictitiousLoad.cpp index 2a818dbed9..f8d63cd8df 100644 --- a/src/solver/optimisation/constraints/FictitiousLoad.cpp +++ b/src/solver/optimisation/constraints/FictitiousLoad.cpp @@ -1,22 +1,40 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -#include "FictitiousLoad.h" +#include "antares/solver/optimisation/constraints/FictitiousLoad.h" void FictitiousLoad::add(int pdt, int pays) { - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContraintePourEviterLesChargesFictives[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.CorrespondanceCntNativesCntOptim[pdt].NumeroDeContraintePourEviterLesChargesFictives[pays] + = builder.data.nombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.FictiveLoads(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.FictiveLoads(builder.data.nombreDeContraintes); builder.updateHourWithinWeek(pdt); - exportPaliers(*problemeHebdo, builder, pays); - auto coeff = problemeHebdo->DefaillanceNegativeUtiliserHydro[pays] ? -1 : 0; + ExportPaliers(data.PaliersThermiquesDuPays[pays], builder); + auto coeff = data.DefaillanceNegativeUtiliserHydro[pays] ? -1 : 0; builder.HydProd(pays, coeff).NegativeUnsuppliedEnergy(pays, 1.0); builder.lessThan(); diff --git a/src/solver/optimisation/constraints/FictitiousLoad.h b/src/solver/optimisation/constraints/FictitiousLoad.h deleted file mode 100644 index 077f3cfba5..0000000000 --- a/src/solver/optimisation/constraints/FictitiousLoad.h +++ /dev/null @@ -1,19 +0,0 @@ - -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Fictitious Load' constraint type - */ -class FictitiousLoad : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param pays : area - */ - void add(int pdt, int pays); -}; diff --git a/src/solver/optimisation/constraints/FinalStockEquivalent.cpp b/src/solver/optimisation/constraints/FinalStockEquivalent.cpp index a00c9bd55a..6649a7a2c3 100644 --- a/src/solver/optimisation/constraints/FinalStockEquivalent.cpp +++ b/src/solver/optimisation/constraints/FinalStockEquivalent.cpp @@ -1,23 +1,43 @@ -#include "FinalStockEquivalent.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/FinalStockEquivalent.h" void FinalStockEquivalent::add(int pays) { - const auto pdt = problemeHebdo->NombreDePasDeTempsPourUneOptimisation - 1; - if (problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue - && problemeHebdo->CaracteristiquesHydrauliques[pays].DirectLevelAccess) + const auto pdt = builder.data.NombreDePasDeTempsPourUneOptimisation - 1; + if (data.CaracteristiquesHydrauliques[pays].AccurateWaterValue + && data.CaracteristiquesHydrauliques[pays].DirectLevelAccess) { /* equivalence constraint : StockFinal- Niveau[T]= 0*/ - problemeHebdo->NumeroDeContrainteEquivalenceStockFinal[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); + data.NumeroDeContrainteEquivalenceStockFinal[pays] = builder.data.nombreDeContraintes; + ConstraintNamer namer(builder.data.NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.FinalStockEquivalent(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.FinalStockEquivalent(builder.data.nombreDeContraintes); builder.updateHourWithinWeek(pdt) .FinalStorage(pays, 1.0) - .updateHourWithinWeek(problemeHebdo->NombreDePasDeTempsPourUneOptimisation - 1) + .updateHourWithinWeek(builder.data.NombreDePasDeTempsPourUneOptimisation - 1) .HydroLevel(pays, -1.0) .equalTo() .build(); diff --git a/src/solver/optimisation/constraints/FinalStockEquivalent.h b/src/solver/optimisation/constraints/FinalStockEquivalent.h deleted file mode 100644 index 19eb89985f..0000000000 --- a/src/solver/optimisation/constraints/FinalStockEquivalent.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Final Stock Equivalent' constraint type - */ -class FinalStockEquivalent : private ConstraintFactory -{ - public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; diff --git a/src/solver/optimisation/constraints/FinalStockExpression.cpp b/src/solver/optimisation/constraints/FinalStockExpression.cpp index 083936ae9b..f9c1b3751d 100644 --- a/src/solver/optimisation/constraints/FinalStockExpression.cpp +++ b/src/solver/optimisation/constraints/FinalStockExpression.cpp @@ -1,10 +1,31 @@ -#include "FinalStockExpression.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/FinalStockExpression.h" void FinalStockExpression::add(int pays) { - const auto pdt = problemeHebdo->NombreDePasDeTempsPourUneOptimisation - 1; + const auto pdt = builder.data.NombreDePasDeTempsPourUneOptimisation - 1; - if (problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) + if (data.CaracteristiquesHydrauliques[pays].AccurateWaterValue) /* expression constraint : - StockFinal +sum (stocklayers) = 0*/ { builder.updateHourWithinWeek(pdt).FinalStorage(pays, -1.0); @@ -12,14 +33,13 @@ void FinalStockExpression::add(int pays) { builder.LayerStorage(pays, layerindex, 1.0); } - problemeHebdo->NumeroDeContrainteExpressionStockFinal[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteExpressionStockFinal[pays] = builder.data.nombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.FinalStockExpression(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.FinalStockExpression(builder.data.nombreDeContraintes); builder.equalTo().build(); } } diff --git a/src/solver/optimisation/constraints/FinalStockExpression.h b/src/solver/optimisation/constraints/FinalStockExpression.h deleted file mode 100644 index ea96c0319e..0000000000 --- a/src/solver/optimisation/constraints/FinalStockExpression.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include "ConstraintBuilder.h" - -/*! - * represent 'Final Stock Expression' constraint type - */ -class FinalStockExpression : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; diff --git a/src/solver/optimisation/constraints/FinalStockGroup.cpp b/src/solver/optimisation/constraints/FinalStockGroup.cpp new file mode 100644 index 0000000000..43f47a6cf5 --- /dev/null +++ b/src/solver/optimisation/constraints/FinalStockGroup.cpp @@ -0,0 +1,52 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/FinalStockGroup.h" + +FinalStockEquivalentData FinalStockGroup::GetFinalStockEquivalentData() +{ + return {.CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques, + .NumeroDeContrainteEquivalenceStockFinal = problemeHebdo_ + ->NumeroDeContrainteEquivalenceStockFinal}; +} + +FinalStockExpressionData FinalStockGroup::GetFinalStockExpressionData() +{ + return {.CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques, + .NumeroDeContrainteExpressionStockFinal = problemeHebdo_ + ->NumeroDeContrainteExpressionStockFinal}; +} + +void FinalStockGroup::BuildConstraints() +{ + auto finalStockEquivalentData = GetFinalStockEquivalentData(); + FinalStockEquivalent finalStockEquivalent(builder_, finalStockEquivalentData); + auto finalStockExpressionData = GetFinalStockExpressionData(); + FinalStockExpression finalStockExpression(builder_, finalStockExpressionData); + + /* For each area with ad hoc properties, two possible sets of two additional constraints */ + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + finalStockEquivalent.add(pays); + + finalStockExpression.add(pays); + } +} diff --git a/src/solver/optimisation/constraints/FlowDissociation.cpp b/src/solver/optimisation/constraints/FlowDissociation.cpp index af172ffd11..06cabaa3f8 100644 --- a/src/solver/optimisation/constraints/FlowDissociation.cpp +++ b/src/solver/optimisation/constraints/FlowDissociation.cpp @@ -1,23 +1,39 @@ -#include "FlowDissociation.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/FlowDissociation.h" void FlowDissociation::add(int pdt, int interco) { - if (const COUTS_DE_TRANSPORT& CoutDeTransport = problemeHebdo->CoutDeTransport[interco]; + if (const COUTS_DE_TRANSPORT& CoutDeTransport = data.CoutDeTransport[interco]; CoutDeTransport.IntercoGereeAvecDesCouts) { - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDeDissociationDeFlux[interco] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - - const auto origin - = problemeHebdo->NomsDesPays[problemeHebdo->PaysOrigineDeLInterconnexion[interco]]; - const auto destination - = problemeHebdo->NomsDesPays[problemeHebdo->PaysExtremiteDeLInterconnexion[interco]]; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.FlowDissociation( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes, origin, destination); + data.CorrespondanceCntNativesCntOptim[pdt].NumeroDeContrainteDeDissociationDeFlux[interco] + = builder.data.nombreDeContraintes; + const auto origin = builder.data.NomsDesPays[data.PaysOrigineDeLInterconnexion[interco]]; + const auto destination = builder.data + .NomsDesPays[data.PaysExtremiteDeLInterconnexion[interco]]; + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.FlowDissociation(builder.data.nombreDeContraintes, origin, destination); builder.updateHourWithinWeek(pdt); builder.NTCDirect(interco, 1.0) diff --git a/src/solver/optimisation/constraints/FlowDissociation.h b/src/solver/optimisation/constraints/FlowDissociation.h deleted file mode 100644 index 27d30af947..0000000000 --- a/src/solver/optimisation/constraints/FlowDissociation.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Flow Dissociation' constraint type - */ -class FlowDissociation : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param interco : interconnection number - */ - void add(int pdt, int interco); -}; diff --git a/src/solver/optimisation/constraints/Group1.cpp b/src/solver/optimisation/constraints/Group1.cpp new file mode 100644 index 0000000000..61e9c8a0fc --- /dev/null +++ b/src/solver/optimisation/constraints/Group1.cpp @@ -0,0 +1,108 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/Group1.h" + +AreaBalanceData Group1::GetAreaBalanceData() +{ + return {.CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim, + .IndexDebutIntercoOrigine = problemeHebdo_->IndexDebutIntercoOrigine, + .IndexSuivantIntercoOrigine = problemeHebdo_->IndexSuivantIntercoOrigine, + .IndexDebutIntercoExtremite = problemeHebdo_->IndexDebutIntercoExtremite, + .IndexSuivantIntercoExtremite = problemeHebdo_->IndexSuivantIntercoExtremite, + .PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .ShortTermStorage = problemeHebdo_->ShortTermStorage}; +} + +FictitiousLoadData Group1::GetFictitiousLoadData() +{ + return {.CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim, + .PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .DefaillanceNegativeUtiliserHydro = problemeHebdo_->DefaillanceNegativeUtiliserHydro}; +} + +ShortTermStorageLevelData Group1::GetShortTermStorageLevelData() +{ + return { + .CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim, + .ShortTermStorage = problemeHebdo_->ShortTermStorage, + }; +} + +FlowDissociationData Group1::GetFlowDissociationData() +{ + return {.CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim, + .CoutDeTransport = problemeHebdo_->CoutDeTransport, + .PaysOrigineDeLInterconnexion = problemeHebdo_->PaysOrigineDeLInterconnexion, + .PaysExtremiteDeLInterconnexion = problemeHebdo_->PaysExtremiteDeLInterconnexion}; +} + +BindingConstraintHourData Group1::GetBindingConstraintHourData() +{ + return + + {.MatriceDesContraintesCouplantes = problemeHebdo_->MatriceDesContraintesCouplantes, + .CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim, + .PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays}; +} + +void Group1::BuildConstraints() +{ + auto areaBalanceData = GetAreaBalanceData(); + AreaBalance areaBalance(builder_, areaBalanceData); + + auto fictitiousLoadData = GetFictitiousLoadData(); + FictitiousLoad fictitiousLoad(builder_, fictitiousLoadData); + + auto shortTermStorageLevelData = GetShortTermStorageLevelData(); + ShortTermStorageLevel shortTermStorageLevel(builder_, shortTermStorageLevelData); + + auto flowDissociationData = GetFlowDissociationData(); + FlowDissociation flowDissociation(builder_, flowDissociationData); + + auto bindingConstraintHourData = GetBindingConstraintHourData(); + BindingConstraintHour bindingConstraintHour(builder_, bindingConstraintHourData); + + int nombreDePasDeTempsPourUneOptimisation = problemeHebdo_ + ->NombreDePasDeTempsPourUneOptimisation; + + for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) + { + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + areaBalance.add(pdt, pays); + fictitiousLoad.add(pdt, pays); + shortTermStorageLevel.add(pdt, pays); + } + + for (uint32_t interco = 0; interco < problemeHebdo_->NombreDInterconnexions; interco++) + { + flowDissociation.add(pdt, interco); + } + + for (uint32_t cntCouplante = 0; + cntCouplante < problemeHebdo_->NombreDeContraintesCouplantes; + cntCouplante++) + { + bindingConstraintHour.add(pdt, cntCouplante); + } + } +} diff --git a/src/solver/optimisation/constraints/HydraulicSmoothingGroup.cpp b/src/solver/optimisation/constraints/HydraulicSmoothingGroup.cpp new file mode 100644 index 0000000000..b545ceb03e --- /dev/null +++ b/src/solver/optimisation/constraints/HydraulicSmoothingGroup.cpp @@ -0,0 +1,64 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/HydraulicSmoothingGroup.h" + +#include "antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h" +#include "antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h" +#include "antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h" + +void HydraulicSmoothingGroup::BuildConstraints() +{ + HydroPowerSmoothingUsingVariationSum hydroPowerSmoothingUsingVariationSum(builder_); + HydroPowerSmoothingUsingVariationMaxDown hydroPowerSmoothingUsingVariationMaxDown(builder_); + HydroPowerSmoothingUsingVariationMaxUp hydroPowerSmoothingUsingVariationMaxUp(builder_); + + if (problemeHebdo_->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_SOMME_DES_VARIATIONS) + { + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + if (!problemeHebdo_->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) + { + continue; + } + + hydroPowerSmoothingUsingVariationSum + .add(pays, problemeHebdo_->NombreDePasDeTempsPourUneOptimisation); + } + } + + else if (problemeHebdo_->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_VARIATION_MAX) + { + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + if (!problemeHebdo_->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) + { + continue; + } + + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + hydroPowerSmoothingUsingVariationMaxDown.add(pays, pdt); + hydroPowerSmoothingUsingVariationMaxUp.add(pays, pdt); + } + } + } +} diff --git a/src/solver/optimisation/constraints/HydroPower.cpp b/src/solver/optimisation/constraints/HydroPower.cpp index abc04f52bc..b30300e89a 100644 --- a/src/solver/optimisation/constraints/HydroPower.cpp +++ b/src/solver/optimisation/constraints/HydroPower.cpp @@ -1,47 +1,65 @@ -#include "HydroPower.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/HydroPower.h" void HydroPower::add(int pays) { - bool presenceHydro - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable; - bool TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; - - const int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; - if (presenceHydro && !TurbEntreBornes) + const int NombreDePasDeTempsPourUneOptimisation = builder.data + .NombreDePasDeTempsPourUneOptimisation; + const auto& caracteristiquesHydrauliques = data.CaracteristiquesHydrauliques[pays]; + if (caracteristiquesHydrauliques.PresenceDHydrauliqueModulable + && !caracteristiquesHydrauliques.TurbinageEntreBornes) { - if (bool presencePompage - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable) + if (caracteristiquesHydrauliques.PresenceDePompageModulable) { - problemeHebdo->NumeroDeContrainteEnergieHydraulique[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteEnergieHydraulique[pays] = builder.data.nombreDeContraintes; - const double pumpingRatio - = problemeHebdo->CaracteristiquesHydrauliques[pays].PumpingRatio; + const double pumpingRatio = caracteristiquesHydrauliques.PumpingRatio; for (int pdt = 0; pdt < NombreDePasDeTempsPourUneOptimisation; pdt++) { - builder.updateHourWithinWeek(pdt); - builder.HydProd(pays, 1.0).Pumping(pays, -pumpingRatio); + builder.updateHourWithinWeek(pdt) + .HydProd(pays, 1.0) + .Pumping(pays, -pumpingRatio) + .Overflow(pays, 1.0); } } else { for (int pdt = 0; pdt < NombreDePasDeTempsPourUneOptimisation; pdt++) { - builder.updateHourWithinWeek(pdt); - builder.HydProd(pays, 1.0); + builder.updateHourWithinWeek(pdt).HydProd(pays, 1.0).Overflow(pays, 1.0); } } - problemeHebdo->NumeroDeContrainteEnergieHydraulique[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteEnergieHydraulique[pays] = builder.data.nombreDeContraintes; builder.equalTo(); - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear); - namer.HydroPower(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear); + namer.HydroPower(builder.data.nombreDeContraintes); builder.build(); } else - problemeHebdo->NumeroDeContrainteEnergieHydraulique[pays] = -1; + { + data.NumeroDeContrainteEnergieHydraulique[pays] = -1; + } } diff --git a/src/solver/optimisation/constraints/HydroPower.h b/src/solver/optimisation/constraints/HydroPower.h deleted file mode 100644 index 50ecc1de14..0000000000 --- a/src/solver/optimisation/constraints/HydroPower.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Hydraulic Power' constraint type - */ -class HydroPower : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; diff --git a/src/solver/optimisation/constraints/HydroPowerGroup.cpp b/src/solver/optimisation/constraints/HydroPowerGroup.cpp new file mode 100644 index 0000000000..76a68eb7b5 --- /dev/null +++ b/src/solver/optimisation/constraints/HydroPowerGroup.cpp @@ -0,0 +1,42 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/HydroPowerGroup.h" + +HydroPowerData HydroPowerGroup::GetHydroPowerDataFromProblemHebdo() +{ + return { + .CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques, + .NombreDePasDeTempsPourUneOptimisation = problemeHebdo_ + ->NombreDePasDeTempsPourUneOptimisation, + .NumeroDeContrainteEnergieHydraulique = problemeHebdo_->NumeroDeContrainteEnergieHydraulique}; +} + +void HydroPowerGroup::BuildConstraints() +{ + auto hydroPowerData = GetHydroPowerDataFromProblemHebdo(); + HydroPower hydroPower(builder_, hydroPowerData); + + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + hydroPower.add(pays); + } +} diff --git a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.cpp b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.cpp index dbe0760d92..dc031b0648 100644 --- a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.cpp +++ b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.cpp @@ -1,17 +1,32 @@ -#include "HydroPowerSmoothingUsingVariationMaxDown.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h" void HydroPowerSmoothingUsingVariationMaxDown::add(int pays, int pdt) { - if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) - { - return; - } - - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.HydroPowerSmoothingUsingVariationMaxDown( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.HydroPowerSmoothingUsingVariationMaxDown(builder.data.nombreDeContraintes); builder.updateHourWithinWeek(pdt) .HydProd(pays, 1.0) @@ -19,4 +34,4 @@ void HydroPowerSmoothingUsingVariationMaxDown::add(int pays, int pdt) .HydProdDown(pays, -1.0) .lessThan() .build(); -} \ No newline at end of file +} diff --git a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h deleted file mode 100644 index a802cf76af..0000000000 --- a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Hydraulic Power Smoothing Using Variation Max Down' constraint type - */ -class HydroPowerSmoothingUsingVariationMaxDown : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param pays : area - */ - void add(int pays, int pdt); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.cpp b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.cpp index 5692ba998c..ef0c8a679d 100644 --- a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.cpp +++ b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.cpp @@ -1,17 +1,32 @@ -#include "HydroPowerSmoothingUsingVariationMaxUp.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h" void HydroPowerSmoothingUsingVariationMaxUp::add(int pays, int pdt) { - if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) - { - return; - } - - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.HydroPowerSmoothingUsingVariationMaxUp( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.HydroPowerSmoothingUsingVariationMaxUp(builder.data.nombreDeContraintes); builder.updateHourWithinWeek(pdt) .HydProd(pays, 1.0) @@ -19,4 +34,4 @@ void HydroPowerSmoothingUsingVariationMaxUp::add(int pays, int pdt) .HydProdUp(pays, -1.0) .greaterThan() .build(); -} \ No newline at end of file +} diff --git a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h deleted file mode 100644 index d1d6300c81..0000000000 --- a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Hydraulic Power Smoothing Using Variation Max Up' constraint type - */ -class HydroPowerSmoothingUsingVariationMaxUp : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pdt : timestep - * @param pays : area - */ - void add(int pays, int pdt); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.cpp b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.cpp index 898f55dfda..50d015cb9f 100644 --- a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.cpp +++ b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.cpp @@ -1,24 +1,40 @@ -#include "HydroPowerSmoothingUsingVariationSum.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void HydroPowerSmoothingUsingVariationSum::add(int pays) -{ - if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) - { - return; - } +#include "antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h" - const int nombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; +void HydroPowerSmoothingUsingVariationSum::add(int pays, + const int nombreDePasDeTempsPourUneOptimisation) +{ for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) { int pdt1 = pdt + 1; if (pdt1 >= nombreDePasDeTempsPourUneOptimisation) + { pdt1 = 0; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.HydroPowerSmoothingUsingVariationSum( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + } + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.HydroPowerSmoothingUsingVariationSum(builder.data.nombreDeContraintes); builder.updateHourWithinWeek(pdt) .HydProd(pays, 1.0) @@ -30,4 +46,4 @@ void HydroPowerSmoothingUsingVariationSum::add(int pays) .equalTo() .build(); } -} \ No newline at end of file +} diff --git a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h b/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h deleted file mode 100644 index 1a671b27fd..0000000000 --- a/src/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h +++ /dev/null @@ -1,17 +0,0 @@ - -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Hydraulic Power Smoothing Using Variation Sum' constraint type - */ -class HydroPowerSmoothingUsingVariationSum : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/MaxHydroPower.cpp b/src/solver/optimisation/constraints/MaxHydroPower.cpp index 80edf424a6..3f0a77cf51 100644 --- a/src/solver/optimisation/constraints/MaxHydroPower.cpp +++ b/src/solver/optimisation/constraints/MaxHydroPower.cpp @@ -1,35 +1,50 @@ -#include "MaxHydroPower.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/MaxHydroPower.h" void MaxHydroPower::add(int pays) { - bool presenceHydro - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable; - bool TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; - if (presenceHydro - && (TurbEntreBornes - || problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) + if (data.CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable + && (data.CaracteristiquesHydrauliques[pays].TurbinageEntreBornes + || data.CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) { - problemeHebdo->NumeroDeContrainteMaxEnergieHydraulique[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - - const int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + data.NumeroDeContrainteMaxEnergieHydraulique[pays] = builder.data.nombreDeContraintes; - for (int pdt = 0; pdt < NombreDePasDeTempsPourUneOptimisation; pdt++) + for (int pdt = 0; pdt < builder.data.NombreDePasDeTempsPourUneOptimisation; pdt++) { builder.updateHourWithinWeek(pdt); builder.HydProd(pays, 1.0); } - problemeHebdo->NumeroDeContrainteMaxEnergieHydraulique[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteMaxEnergieHydraulique[pays] = builder.data.nombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear); - namer.MaxHydroPower(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear); + namer.MaxHydroPower(builder.data.nombreDeContraintes); builder.lessThan().build(); } else - problemeHebdo->NumeroDeContrainteMaxEnergieHydraulique[pays] = -1; -} \ No newline at end of file + { + data.NumeroDeContrainteMaxEnergieHydraulique[pays] = -1; + } +} diff --git a/src/solver/optimisation/constraints/MaxHydroPower.h b/src/solver/optimisation/constraints/MaxHydroPower.h deleted file mode 100644 index f89ae370f4..0000000000 --- a/src/solver/optimisation/constraints/MaxHydroPower.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Max Hydraulic Power' constraint type - */ -class MaxHydroPower : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/MaxPumping.cpp b/src/solver/optimisation/constraints/MaxPumping.cpp index 94e68f6ed4..4ff84c8b74 100644 --- a/src/solver/optimisation/constraints/MaxPumping.cpp +++ b/src/solver/optimisation/constraints/MaxPumping.cpp @@ -1,28 +1,46 @@ -#include "MaxPumping.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/MaxPumping.h" void MaxPumping::add(int pays) { - if (problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable) + if (data.CaracteristiquesHydrauliques[pays].PresenceDePompageModulable) { - problemeHebdo->NumeroDeContrainteMaxPompage[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - - const int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + data.NumeroDeContrainteMaxPompage[pays] = builder.data.nombreDeContraintes; - for (int pdt = 0; pdt < NombreDePasDeTempsPourUneOptimisation; pdt++) + for (int pdt = 0; pdt < builder.data.NombreDePasDeTempsPourUneOptimisation; pdt++) { builder.updateHourWithinWeek(pdt); builder.Pumping(pays, 1.0); } - problemeHebdo->NumeroDeContrainteMaxPompage[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear); - namer.MaxPumping(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + data.NumeroDeContrainteMaxPompage[pays] = builder.data.nombreDeContraintes; + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear); + namer.MaxPumping(builder.data.nombreDeContraintes); builder.lessThan().build(); } else - problemeHebdo->NumeroDeContrainteMaxPompage[pays] = -1; -} \ No newline at end of file + { + data.NumeroDeContrainteMaxPompage[pays] = -1; + } +} diff --git a/src/solver/optimisation/constraints/MaxPumping.h b/src/solver/optimisation/constraints/MaxPumping.h deleted file mode 100644 index 6e1a9f4809..0000000000 --- a/src/solver/optimisation/constraints/MaxPumping.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Max Pumping' constraint type - */ -class MaxPumping : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/MaxPumpingGroup.cpp b/src/solver/optimisation/constraints/MaxPumpingGroup.cpp new file mode 100644 index 0000000000..0697a6de36 --- /dev/null +++ b/src/solver/optimisation/constraints/MaxPumpingGroup.cpp @@ -0,0 +1,39 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/MaxPumpingGroup.h" + +MaxPumpingData MaxPumpingGroup::GetMaxPumpingData() +{ + return {.CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques, + .NumeroDeContrainteMaxPompage = problemeHebdo_->NumeroDeContrainteMaxPompage}; +} + +void MaxPumpingGroup::BuildConstraints() +{ + auto maxPumpingData = GetMaxPumpingData(); + MaxPumping maxPumping(builder_, maxPumpingData); + + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + maxPumping.add(pays); + } +} diff --git a/src/solver/optimisation/constraints/MinDownTime.cpp b/src/solver/optimisation/constraints/MinDownTime.cpp index ca4805d007..a7467e742c 100644 --- a/src/solver/optimisation/constraints/MinDownTime.cpp +++ b/src/solver/optimisation/constraints/MinDownTime.cpp @@ -1,19 +1,40 @@ -#include "MinDownTime.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void MinDownTime::add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation) +#include "antares/solver/optimisation/constraints/MinDownTime.h" + +void MinDownTime::add(int pays, int index, int pdt) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; const int DureeMinimaleDArretDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.DureeMinimaleDArretDUnGroupeDuPalierThermique[clusterIndex]; + = data.PaliersThermiquesDuPays[pays].DureeMinimaleDArretDUnGroupeDuPalierThermique[index]; + auto cluster = data.PaliersThermiquesDuPays[pays] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesContraintesDeDureeMinDArret[cluster] = -1; - if (!Simulation) + data.CorrespondanceCntNativesCntOptim[pdt] + .NumeroDeContrainteDesContraintesDeDureeMinDArret[cluster] + = -1; + if (!data.Simulation) { - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = builder.data + .NombreDePasDeTempsPourUneOptimisation; builder.updateHourWithinWeek(pdt).NumberOfDispatchableUnits(cluster, 1.0); @@ -21,30 +42,32 @@ void MinDownTime::add(int pays, int cluster, int clusterIndex, int pdt, bool Sim { int t1 = k; if (t1 < 0) + { t1 = NombreDePasDeTempsPourUneOptimisation + t1; + } builder.updateHourWithinWeek(t1).NumberStoppingDispatchableUnits(cluster, 1.0); } builder.lessThan(); if (builder.NumberOfVariables() > 1) { - CorrespondanceCntNativesCntOptim + data.CorrespondanceCntNativesCntOptim[pdt] .NumeroDeContrainteDesContraintesDeDureeMinDArret[cluster] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); + = builder.data.nombreDeContraintes; + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.MinDownTime(problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - PaliersThermiquesDuPays.NomsDesPaliersThermiques[clusterIndex]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.MinDownTime(builder.data.nombreDeContraintes, + data.PaliersThermiquesDuPays[pays].NomsDesPaliersThermiques[index]); builder.build(); } } else { - problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage + builder.data.NbTermesContraintesPourLesCoutsDeDemarrage += 1 + DureeMinimaleDArretDUnGroupeDuPalierThermique; - problemeHebdo->ProblemeAResoudre->NombreDeContraintes++; + builder.data.nombreDeContraintes++; } } diff --git a/src/solver/optimisation/constraints/MinDownTime.h b/src/solver/optimisation/constraints/MinDownTime.h deleted file mode 100644 index 567a766b6d..0000000000 --- a/src/solver/optimisation/constraints/MinDownTime.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'MinDownTime' Constraint type - */ -class MinDownTime : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - * @param cluster : global index of the cluster - * @param pdt : timestep - * @param Simulation : --- - */ - void add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/MinDownTimeGroup.cpp b/src/solver/optimisation/constraints/MinDownTimeGroup.cpp new file mode 100644 index 0000000000..8dd805f826 --- /dev/null +++ b/src/solver/optimisation/constraints/MinDownTimeGroup.cpp @@ -0,0 +1,51 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/MinDownTimeGroup.h" + +MinDownTimeData MinDownTimeGroup::GetMinDownTimeDataFromProblemHebdo() +{ + return {.PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .Simulation = simulation_, + .CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim}; +} + +/** + * @brief build MinDownTime constraints with + * respect to default order + */ +void MinDownTimeGroup::BuildConstraints() +{ + auto data = GetMinDownTimeDataFromProblemHebdo(); + MinDownTime minDownTime(builder_, data); + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo_ + ->PaliersThermiquesDuPays[pays]; + for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) + { + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + minDownTime.add(pays, index, pdt); + } + } + } +} diff --git a/src/solver/optimisation/constraints/MinHydroPower.cpp b/src/solver/optimisation/constraints/MinHydroPower.cpp index 025542f9ba..f4f5016476 100644 --- a/src/solver/optimisation/constraints/MinHydroPower.cpp +++ b/src/solver/optimisation/constraints/MinHydroPower.cpp @@ -1,34 +1,50 @@ -#include "MinHydroPower.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/MinHydroPower.h" void MinHydroPower::add(int pays) { - bool presenceHydro - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable; - bool TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; - if (presenceHydro - && (TurbEntreBornes - || problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) + if (data.CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable + && (data.CaracteristiquesHydrauliques[pays].TurbinageEntreBornes + || data.CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) { - problemeHebdo->NumeroDeContrainteMinEnergieHydraulique[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteMinEnergieHydraulique[pays] = builder.data.nombreDeContraintes; - const int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear); + namer.MinHydroPower(builder.data.nombreDeContraintes); - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear); - namer.MinHydroPower(problemeHebdo->ProblemeAResoudre->NombreDeContraintes); - for (int pdt = 0; pdt < NombreDePasDeTempsPourUneOptimisation; pdt++) + for (int pdt = 0; pdt < data.NombreDePasDeTempsPourUneOptimisation; pdt++) { builder.updateHourWithinWeek(pdt); builder.HydProd(pays, 1.0); } - problemeHebdo->NumeroDeContrainteMinEnergieHydraulique[pays] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.NumeroDeContrainteMinEnergieHydraulique[pays] = builder.data.nombreDeContraintes; builder.greaterThan().build(); } else - problemeHebdo->NumeroDeContrainteMinEnergieHydraulique[pays] = -1; + { + data.NumeroDeContrainteMinEnergieHydraulique[pays] = -1; + } } diff --git a/src/solver/optimisation/constraints/MinHydroPower.h b/src/solver/optimisation/constraints/MinHydroPower.h deleted file mode 100644 index 8b7dfb1892..0000000000 --- a/src/solver/optimisation/constraints/MinHydroPower.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Min Hydraulic Power' constraint type - */ -class MinHydroPower : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - */ - void add(int pays); -}; - diff --git a/src/solver/optimisation/constraints/MinMaxHydroPowerGroup.cpp b/src/solver/optimisation/constraints/MinMaxHydroPowerGroup.cpp new file mode 100644 index 0000000000..2a00844da0 --- /dev/null +++ b/src/solver/optimisation/constraints/MinMaxHydroPowerGroup.cpp @@ -0,0 +1,54 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/MinMaxHydroPowerGroup.h" + +MinHydroPowerData MinMaxHydroPowerGroup::GetMinHydroPowerData() +{ + return {.CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques, + .NombreDePasDeTempsPourUneOptimisation = problemeHebdo_ + ->NombreDePasDeTempsPourUneOptimisation, + .NumeroDeContrainteMinEnergieHydraulique = problemeHebdo_ + ->NumeroDeContrainteMinEnergieHydraulique}; +} + +MaxHydroPowerData MinMaxHydroPowerGroup::GetMaxHydroPowerData() +{ + return {.CaracteristiquesHydrauliques = problemeHebdo_->CaracteristiquesHydrauliques, + .NombreDePasDeTempsPourUneOptimisation = problemeHebdo_ + ->NombreDePasDeTempsPourUneOptimisation, + .NumeroDeContrainteMaxEnergieHydraulique = problemeHebdo_ + ->NumeroDeContrainteMaxEnergieHydraulique}; +} + +void MinMaxHydroPowerGroup::BuildConstraints() +{ + auto minHydroPowerData = GetMinHydroPowerData(); + MinHydroPower minHydroPower(builder_, minHydroPowerData); + auto maxHydroPowerData = GetMaxHydroPowerData(); + MaxHydroPower maxHydroPower(builder_, maxHydroPowerData); + + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + minHydroPower.add(pays); + maxHydroPower.add(pays); + } +} diff --git a/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.cpp b/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.cpp index 06a341f14d..13f03df1c1 100644 --- a/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.cpp +++ b/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.cpp @@ -1,24 +1,40 @@ -#include "NbDispUnitsMinBoundSinceMinUpTime.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void NbDispUnitsMinBoundSinceMinUpTime::add(int pays, - int cluster, - int clusterIndex, - int pdt, - bool Simulation) +#include "antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h" + +void NbDispUnitsMinBoundSinceMinUpTime::add(int pays, int index, int pdt) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + auto cluster = data.PaliersThermiquesDuPays[pays] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; const int DureeMinimaleDeMarcheDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[clusterIndex]; + = data.PaliersThermiquesDuPays[pays].DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[index]; - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesContraintesDeDureeMinDeMarche[cluster] + data.CorrespondanceCntNativesCntOptim[pdt] + .NumeroDeContrainteDesContraintesDeDureeMinDeMarche[cluster] = -1; - if (!Simulation) + if (!data.Simulation) { - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = builder.data + .NombreDePasDeTempsPourUneOptimisation; builder.updateHourWithinWeek(pdt).NumberOfDispatchableUnits(cluster, 1.0); @@ -26,7 +42,9 @@ void NbDispUnitsMinBoundSinceMinUpTime::add(int pays, { int t1 = k; if (t1 < 0) + { t1 = NombreDePasDeTempsPourUneOptimisation + t1; + } builder.updateHourWithinWeek(t1) .NumberStartingDispatchableUnits(cluster, -1.0) @@ -36,24 +54,24 @@ void NbDispUnitsMinBoundSinceMinUpTime::add(int pays, builder.greaterThan(); if (builder.NumberOfVariables() > 1) { - CorrespondanceCntNativesCntOptim + data.CorrespondanceCntNativesCntOptim[pays] .NumeroDeContrainteDesContraintesDeDureeMinDeMarche[cluster] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + = builder.data.nombreDeContraintes; - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); namer.NbDispUnitsMinBoundSinceMinUpTime( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - PaliersThermiquesDuPays.NomsDesPaliersThermiques[clusterIndex]); + builder.data.nombreDeContraintes, + data.PaliersThermiquesDuPays[pays].NomsDesPaliersThermiques[index]); builder.build(); } } else { - problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage + builder.data.NbTermesContraintesPourLesCoutsDeDemarrage += 1 + 2 * DureeMinimaleDeMarcheDUnGroupeDuPalierThermique; - problemeHebdo->ProblemeAResoudre->NombreDeContraintes++; + builder.data.nombreDeContraintes++; } } diff --git a/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h b/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h deleted file mode 100644 index ab86556a21..0000000000 --- a/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'Number of Dispatchable Units Min Bound Since Min Up Time' type - */ -class NbDispUnitsMinBoundSinceMinUpTime : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - * @param cluster : global index of the cluster - * @param pdt : timestep - * @param Simulation : --- - */ - void add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.cpp b/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.cpp new file mode 100644 index 0000000000..37ad0c6a2f --- /dev/null +++ b/src/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.cpp @@ -0,0 +1,57 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.h" + +NbDispUnitsMinBoundSinceMinUpTimeData +NbDispUnitsMinBoundSinceMinUpTimeGroup::GetNbDispUnitsMinBoundSinceMinUpTimeDataFromProblemHebdo() +{ + return {.PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .Simulation = simulation_, + .CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim}; +} + +/** + * @brief build NbUnitsOutageLessThanNbUnitsStopGroup constraints with + * respect to default order + */ +void NbDispUnitsMinBoundSinceMinUpTimeGroup::BuildConstraints() +{ + auto data = GetNbDispUnitsMinBoundSinceMinUpTimeDataFromProblemHebdo(); + NbDispUnitsMinBoundSinceMinUpTime nbDispUnitsMinBoundSinceMinUpTime(builder_, data); + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo_ + ->PaliersThermiquesDuPays[pays]; + for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) + { + if (PaliersThermiquesDuPays.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[index] <= 0) + { + continue; + } + + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + nbDispUnitsMinBoundSinceMinUpTime.add(pays, index, pdt); + } + } + } +} diff --git a/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.cpp b/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.cpp index 472aedc323..4d90766da3 100644 --- a/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.cpp +++ b/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.cpp @@ -1,19 +1,34 @@ -#include "NbUnitsOutageLessThanNbUnitsStop.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void NbUnitsOutageLessThanNbUnitsStop::add(int pays, - int cluster, - int clusterIndex, - int pdt, - bool Simulation) +#include "antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h" + +void NbUnitsOutageLessThanNbUnitsStop::add(int pays, int index, int pdt) { - if (!Simulation) + if (!data.Simulation) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesContraintesDeDureeMinDeMarche[cluster] + auto cluster = data.PaliersThermiquesDuPays[pays] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + data.CorrespondanceCntNativesCntOptim[pdt] + .NumeroDeContrainteDesContraintesDeDureeMinDeMarche[cluster] = -1; builder.updateHourWithinWeek(pdt) @@ -23,19 +38,19 @@ void NbUnitsOutageLessThanNbUnitsStop::add(int pays, if (builder.NumberOfVariables() > 0) { - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); namer.NbUnitsOutageLessThanNbUnitsStop( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - PaliersThermiquesDuPays.NomsDesPaliersThermiques[clusterIndex]); + builder.data.nombreDeContraintes, + data.PaliersThermiquesDuPays[pays].NomsDesPaliersThermiques[index]); builder.build(); } } else { - problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage += 2; - problemeHebdo->ProblemeAResoudre->NombreDeContraintes++; + builder.data.NbTermesContraintesPourLesCoutsDeDemarrage += 2; + builder.data.nombreDeContraintes++; } } diff --git a/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h b/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h deleted file mode 100644 index 79c9f714fb..0000000000 --- a/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'NbUnitsOutageLessThanNbUnitsStop' type - */ -class NbUnitsOutageLessThanNbUnitsStop : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - * @param cluster : global index of the cluster - * @param pdt : timestep - * @param Simulation : --- - */ - void add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.cpp b/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.cpp new file mode 100644 index 0000000000..a2e85f955b --- /dev/null +++ b/src/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.cpp @@ -0,0 +1,53 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.h" + +NbUnitsOutageLessThanNbUnitsStopData +NbUnitsOutageLessThanNbUnitsStopGroup::GetNbUnitsOutageLessThanNbUnitsStopDataFromProblemHebdo() +{ + return {.PaliersThermiquesDuPays = problemeHebdo_->PaliersThermiquesDuPays, + .Simulation = simulation_, + .CorrespondanceCntNativesCntOptim = problemeHebdo_->CorrespondanceCntNativesCntOptim}; +} + +/** + * @brief build NbUnitsOutageLessThanNbUnitsStopGroup constraints with + * respect to default order + */ +void NbUnitsOutageLessThanNbUnitsStopGroup::BuildConstraints() +{ + auto data = GetNbUnitsOutageLessThanNbUnitsStopDataFromProblemHebdo(); + NbUnitsOutageLessThanNbUnitsStop nbUnitsOutageLessThanNbUnitsStop(builder_, data); + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo_ + ->PaliersThermiquesDuPays[pays]; + + for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) + { + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + nbUnitsOutageLessThanNbUnitsStop.add(pays, index, pdt); + } + } + } +} diff --git a/src/solver/optimisation/constraints/PMaxDispatchableGeneration.cpp b/src/solver/optimisation/constraints/PMaxDispatchableGeneration.cpp index 92f4d06eed..a3d7fef5b8 100644 --- a/src/solver/optimisation/constraints/PMaxDispatchableGeneration.cpp +++ b/src/solver/optimisation/constraints/PMaxDispatchableGeneration.cpp @@ -1,38 +1,54 @@ -#include "PMaxDispatchableGeneration.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void PMaxDispatchableGeneration::add(int pays, - int cluster, - int clusterIndex, - int pdt, - bool Simulation) +#include "antares/solver/optimisation/constraints/PMaxDispatchableGeneration.h" + +void PMaxDispatchableGeneration::add(int pays, int index, int pdt) { - if (!Simulation) + if (!data.Simulation) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - double pmaxDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.PmaxDUnGroupeDuPalierThermique[clusterIndex]; - + double pmaxDUnGroupeDuPalierThermique = data.PaliersThermiquesDuPays[pays] + .PmaxDUnGroupeDuPalierThermique[index]; + int cluster = data.PaliersThermiquesDuPays[pays] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; builder.updateHourWithinWeek(pdt) .DispatchableProduction(cluster, 1.0) .NumberOfDispatchableUnits(cluster, -pmaxDUnGroupeDuPalierThermique) .lessThan(); if (builder.NumberOfVariables() > 0) { - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); + ConstraintNamer namer(builder.data.NomDesContraintes); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); + namer.UpdateArea(builder.data.NomsDesPays[pays]); namer.PMaxDispatchableGeneration( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - PaliersThermiquesDuPays.NomsDesPaliersThermiques[clusterIndex]); + builder.data.nombreDeContraintes, + data.PaliersThermiquesDuPays[pays].NomsDesPaliersThermiques[index]); } builder.build(); } else { - problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage += 2; - problemeHebdo->ProblemeAResoudre->NombreDeContraintes++; + builder.data.NbTermesContraintesPourLesCoutsDeDemarrage += 2; + builder.data.nombreDeContraintes++; } } diff --git a/src/solver/optimisation/constraints/PMaxDispatchableGeneration.h b/src/solver/optimisation/constraints/PMaxDispatchableGeneration.h deleted file mode 100644 index b82c5dd196..0000000000 --- a/src/solver/optimisation/constraints/PMaxDispatchableGeneration.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'PMaxDispatchableGeneration' Constraint type - */ -class PMaxDispatchableGeneration : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - * @param cluster : global index of the cluster - * @param pdt : timestep - * @param Simulation : --- - */ - void add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/PMinDispatchableGeneration.cpp b/src/solver/optimisation/constraints/PMinDispatchableGeneration.cpp index c2fe75b9ea..df22497577 100644 --- a/src/solver/optimisation/constraints/PMinDispatchableGeneration.cpp +++ b/src/solver/optimisation/constraints/PMinDispatchableGeneration.cpp @@ -1,18 +1,35 @@ -#include "PMinDispatchableGeneration.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -void PMinDispatchableGeneration::add(int pays, - int cluster, - int clusterIndex, - int pdt, - bool Simulation) +#include "antares/solver/optimisation/constraints/PMinDispatchableGeneration.h" + +void PMinDispatchableGeneration::add(int pays, int index, int pdt) { - if (!Simulation) + if (!data.Simulation) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - double pminDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.pminDUnGroupeDuPalierThermique[clusterIndex]; + double pminDUnGroupeDuPalierThermique = data.PaliersThermiquesDuPays[pays] + .pminDUnGroupeDuPalierThermique[index]; + int cluster = data.PaliersThermiquesDuPays[pays] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; builder.updateHourWithinWeek(pdt) .DispatchableProduction(cluster, 1.0) .NumberOfDispatchableUnits(cluster, -pminDUnGroupeDuPalierThermique) @@ -20,19 +37,19 @@ void PMinDispatchableGeneration::add(int pays, /*consider Adding naming constraint inside the builder*/ if (builder.NumberOfVariables() > 0) { - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); + ConstraintNamer namer(builder.data.NomDesContraintes); + namer.UpdateArea(builder.data.NomsDesPays[pays]); - namer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); + namer.UpdateTimeStep(builder.data.weekInTheYear * 168 + pdt); namer.PMinDispatchableGeneration( - problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - PaliersThermiquesDuPays.NomsDesPaliersThermiques[clusterIndex]); + builder.data.nombreDeContraintes, + data.PaliersThermiquesDuPays[pays].NomsDesPaliersThermiques[index]); } - builder.build(); + builder.build(); } else { - problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage += 2; - problemeHebdo->ProblemeAResoudre->NombreDeContraintes++; + builder.data.NbTermesContraintesPourLesCoutsDeDemarrage += 2; + builder.data.nombreDeContraintes++; } } diff --git a/src/solver/optimisation/constraints/PMinDispatchableGeneration.h b/src/solver/optimisation/constraints/PMinDispatchableGeneration.h deleted file mode 100644 index 58b1f36438..0000000000 --- a/src/solver/optimisation/constraints/PMinDispatchableGeneration.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -/*! - * represent 'PMinDispatchableGeneration' Constraint type - */ -class PMinDispatchableGeneration : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - - /*! - * @brief Add variables to the constraint and update constraints Matrix - * @param pays : area - * @param cluster : global index of the cluster - * @param pdt : timestep - * @param Simulation : --- - */ - void add(int pays, int cluster, int clusterIndex, int pdt, bool Simulation); -}; \ No newline at end of file diff --git a/src/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.cpp b/src/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.cpp new file mode 100644 index 0000000000..47be47d107 --- /dev/null +++ b/src/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.cpp @@ -0,0 +1,46 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.h" + +/** + * @brief build P{min,max}DispatchableGeneration constraints with + * respect to default order + */ +void PMinMaxDispatchableGenerationGroup::BuildConstraints() +{ + auto data = GetStartUpCostsDataFromProblemHebdo(); + PMaxDispatchableGeneration pMaxDispatchableGeneration(builder_, data); + PMinDispatchableGeneration pMinDispatchableGeneration(builder_, data); + for (uint32_t pays = 0; pays < problemeHebdo_->NombreDePays; pays++) + { + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo_ + ->PaliersThermiquesDuPays[pays]; + for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) + { + for (int pdt = 0; pdt < problemeHebdo_->NombreDePasDeTempsPourUneOptimisation; pdt++) + { + pMaxDispatchableGeneration.add(pays, index, pdt); + pMinDispatchableGeneration.add(pays, index, pdt); + } + } + } +} diff --git a/src/solver/optimisation/constraints/ShortTermStorageLevel.cpp b/src/solver/optimisation/constraints/ShortTermStorageLevel.cpp index 46165a9f79..0faa565a8a 100644 --- a/src/solver/optimisation/constraints/ShortTermStorageLevel.cpp +++ b/src/solver/optimisation/constraints/ShortTermStorageLevel.cpp @@ -1,28 +1,47 @@ -#include "ShortTermStorageLevel.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/ShortTermStorageLevel.h" void ShortTermStorageLevel::add(int pdt, int pays) { - ConstraintNamer namer(problemeHebdo->ProblemeAResoudre->NomDesContraintes); - CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim - = problemeHebdo->CorrespondanceCntNativesCntOptim[pdt]; - - const int hourInTheYear = problemeHebdo->weekInTheYear * 168 + pdt; + ConstraintNamer namer(builder.data.NomDesContraintes); + const int hourInTheYear = builder.data.weekInTheYear * 168 + pdt; namer.UpdateTimeStep(hourInTheYear); - namer.UpdateArea(problemeHebdo->NomsDesPays[pays]); + namer.UpdateArea(builder.data.NomsDesPays[pays]); builder.updateHourWithinWeek(pdt); - for (const auto& storage : problemeHebdo->ShortTermStorage[pays]) + for (const auto& storage: data.ShortTermStorage[pays]) { // L[h] - L[h-1] - efficiency * injection[h] + withdrawal[h] = inflows[h] - namer.ShortTermStorageLevel(problemeHebdo->ProblemeAResoudre->NombreDeContraintes, - storage.name); + namer.ShortTermStorageLevel(builder.data.nombreDeContraintes, storage.name); const auto index = storage.clusterGlobalIndex; - CorrespondanceCntNativesCntOptim.ShortTermStorageLevelConstraint[index] - = problemeHebdo->ProblemeAResoudre->NombreDeContraintes; + data.CorrespondanceCntNativesCntOptim[pdt].ShortTermStorageLevelConstraint[index] + = builder.data.nombreDeContraintes; builder.ShortTermStorageLevel(index, 1.0) - .ShortTermStorageLevel( - index, -1.0, -1, problemeHebdo->NombreDePasDeTempsPourUneOptimisation) + .ShortTermStorageLevel(index, + -1.0, + -1, + builder.data.NombreDePasDeTempsPourUneOptimisation) .ShortTermStorageInjection(index, -1.0 * storage.efficiency) .ShortTermStorageWithdrawal(index, 1.0) .equalTo() diff --git a/src/solver/optimisation/constraints/ShortTermStorageLevel.h b/src/solver/optimisation/constraints/ShortTermStorageLevel.h deleted file mode 100644 index c5377a97ce..0000000000 --- a/src/solver/optimisation/constraints/ShortTermStorageLevel.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -#include "ConstraintBuilder.h" - -class ShortTermStorageLevel : private ConstraintFactory -{ -public: - using ConstraintFactory::ConstraintFactory; - void add(int pdt, int pays); -}; diff --git a/src/solver/optimisation/constraints/constraint_builder_utils.cpp b/src/solver/optimisation/constraints/constraint_builder_utils.cpp new file mode 100644 index 0000000000..77a3228999 --- /dev/null +++ b/src/solver/optimisation/constraints/constraint_builder_utils.cpp @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" + +ConstraintBuilderData NewGetConstraintBuilderFromProblemHebdoAndProblemAResoudre( + PROBLEME_HEBDO* problemeHebdo, + PROBLEME_ANTARES_A_RESOUDRE& ProblemeAResoudre) +{ + return {ProblemeAResoudre.Pi, + ProblemeAResoudre.Colonne, + ProblemeAResoudre.NombreDeContraintes, + ProblemeAResoudre.NombreDeTermesDansLaMatriceDesContraintes, + ProblemeAResoudre.IndicesDebutDeLigne, + ProblemeAResoudre.CoefficientsDeLaMatriceDesContraintes, + ProblemeAResoudre.IndicesColonnes, + ProblemeAResoudre.NombreDeTermesAllouesDansLaMatriceDesContraintes, + ProblemeAResoudre.NombreDeTermesDesLignes, + ProblemeAResoudre.Sens, + ProblemeAResoudre.IncrementDAllocationMatriceDesContraintes, + problemeHebdo->CorrespondanceVarNativesVarOptim, + problemeHebdo->NombreDePasDeTempsPourUneOptimisation, + problemeHebdo->NumeroDeVariableStockFinal, + problemeHebdo->NumeroDeVariableDeTrancheDeStock, + ProblemeAResoudre.NomDesContraintes, + problemeHebdo->NamedProblems, + problemeHebdo->NomsDesPays, + problemeHebdo->weekInTheYear, + problemeHebdo->NombreDePasDeTemps, + problemeHebdo->NbTermesContraintesPourLesCoutsDeDemarrage}; +} diff --git a/src/solver/optimisation/include/antares/solver/optimisation/HebdoProblemToLpsTranslator.h b/src/solver/optimisation/include/antares/solver/optimisation/HebdoProblemToLpsTranslator.h new file mode 100644 index 0000000000..7deb23a0ca --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/HebdoProblemToLpsTranslator.h @@ -0,0 +1,81 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/lps/LpsFromAntares.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace Antares::Solver +{ + +/** + * @class WeeklyProblemTranslationException + * @brief Exception class for errors during the translation of a weekly problem. + * + * This class is a custom exception class that is thrown when an error occurs during the translation + * of a weekly problem. + */ +class WeeklyProblemTranslationException: public std::runtime_error +{ +public: + explicit WeeklyProblemTranslationException(const std::string& string) noexcept; +}; + +/** + * @class HebdoProblemToLpsTranslator + * @brief Class for translating a weekly problem to a linear programming problem. + * + * This class is responsible for translating a weekly problem to a linear programming problem. + */ +class HebdoProblemToLpsTranslator +{ +public: + /** + * @brief Translates a weekly problem to a linear programming problem. + * + * This function takes a pointer to a PROBLEME_ANTARES_A_RESOUDRE object and a string_view + * representing the name of the problem. It translates the weekly problem to a linear + * programming problem and returns a WeeklyDataFromAntaresPtr to the translated problem. Datas + * from the PROBLEME_ANTARES_A_RESOUDRE are copied to the WeeklyDataFromAntaresPtr. + * + * @param problem A pointer to the weekly problem to be translated. + * @param name The name of the problem. + * @return WeeklyDataFromAntaresPtr A WeeklyDataFromAntaresPtr to the translated problem. + */ + [[nodiscard]] WeeklyDataFromAntares translate(const PROBLEME_ANTARES_A_RESOUDRE* problem, + std::string_view name) const; + + /** + * @brief Retrieves common problem data, the part common to every weekly problems + * + * This function takes a pointer to a PROBLEME_ANTARES_A_RESOUDRE object and retrieves the + * common problem data. It returns a ConstantDataFromAntaresPtr to the common problem data. + * + * @param problem A pointer to the problem from which to retrieve the common data. + * @return ConstantDataFromAntaresPtr A ConstantDataFromAntaresPtr to the common problem data. + */ + [[nodiscard]] ConstantDataFromAntares commonProblemData( + const PROBLEME_ANTARES_A_RESOUDRE* problem) const; +}; + +} // namespace Antares::Solver diff --git a/src/solver/optimisation/include/antares/solver/optimisation/LinearProblemMatrix.h b/src/solver/optimisation/include/antares/solver/optimisation/LinearProblemMatrix.h new file mode 100644 index 0000000000..beb6e867fd --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/LinearProblemMatrix.h @@ -0,0 +1,58 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "ProblemMatrixEssential.h" +#include "constraints/AreaHydroLevelGroup.h" +#include "constraints/BindingConstraintDayGroup.h" +#include "constraints/BindingConstraintWeekGroup.h" +#include "constraints/ConstraintGroup.h" +#include "constraints/FinalStockGroup.h" +#include "constraints/Group1.h" +#include "constraints/HydraulicSmoothingGroup.h" +#include "constraints/HydroPowerGroup.h" +#include "constraints/MaxPumpingGroup.h" +#include "constraints/MinMaxHydroPowerGroup.h" + +using namespace Antares::Data; + +class LinearProblemMatrix: public ProblemMatrixEssential +{ +public: + explicit LinearProblemMatrix(PROBLEME_HEBDO* problemeHebdo, ConstraintBuilder& builder); + + void Run() override; + +private: + ConstraintBuilder& builder_; + Group1 group1_; + BindingConstraintDayGroup bindingConstraintDayGroup_; + BindingConstraintWeekGroup bindingConstraintWeekGroup_; + HydroPowerGroup hydroPowerGroup_; + HydraulicSmoothingGroup hydraulicSmoothingGroup_; + MinMaxHydroPowerGroup minMaxHydroPowerGroup_; + MaxPumpingGroup maxPumpingGroup_; + AreaHydroLevelGroup areaHydroLevelGroup_; + FinalStockGroup finalStockGroup_; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h b/src/solver/optimisation/include/antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h new file mode 100644 index 0000000000..5627020f33 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h @@ -0,0 +1,50 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "ProblemMatrixEssential.h" +#include "constraints/ConsistenceNumberOfDispatchableUnitsGroup.h" +#include "constraints/ConstraintGroup.h" +#include "constraints/MinDownTimeGroup.h" +#include "constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.h" +#include "constraints/NbUnitsOutageLessThanNbUnitsStopGroup.h" +#include "constraints/PMinMaxDispatchableGenerationGroup.h" + +using namespace Antares::Data; + +class LinearProblemMatrixStartUpCosts: public ProblemMatrixEssential +{ +public: + explicit LinearProblemMatrixStartUpCosts(PROBLEME_HEBDO* problemeHebdo, + bool Simulation, + ConstraintBuilder& builder); + +private: + bool simulation_ = false; + PMinMaxDispatchableGenerationGroup pMinMaxDispatchableGenerationGroup_; + ConsistenceNumberOfDispatchableUnitsGroup consistenceNumberOfDispatchableUnitsGroup_; + NbUnitsOutageLessThanNbUnitsStopGroup nbUnitsOutageLessThanNbUnitsStopGroup_; + NbDispUnitsMinBoundSinceMinUpTimeGroup nbDispUnitsMinBoundSinceMinUpTimeGroup_; + MinDownTimeGroup minDownTimeGroup_; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/ProblemMatrixEssential.h b/src/solver/optimisation/include/antares/solver/optimisation/ProblemMatrixEssential.h new file mode 100644 index 0000000000..6249c9f399 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/ProblemMatrixEssential.h @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "constraints/ConstraintGroup.h" + +class ProblemMatrixEssential +{ +public: + explicit ProblemMatrixEssential(PROBLEME_HEBDO* problemeHebdo); + + virtual void Run(); + + void InitializeProblemAResoudreCounters(); + PROBLEME_HEBDO* problemeHebdo_; + std::vector constraintgroups_; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/QuadraticProblemMatrix.h b/src/solver/optimisation/include/antares/solver/optimisation/QuadraticProblemMatrix.h new file mode 100644 index 0000000000..31563498a3 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/QuadraticProblemMatrix.h @@ -0,0 +1,47 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" + +#include "ProblemMatrixEssential.h" +#include "constraints/ExchangeBalanceGroup.h" + +class QuadraticProblemMatrix: public ProblemMatrixEssential +{ +public: + QuadraticProblemMatrix(PROBLEME_HEBDO* problem_hebdo, ConstraintBuilder& builder): + ProblemMatrixEssential(problem_hebdo), + exchangeBalanceGroup_(problem_hebdo, builder) + { + constraintgroups_ = {&exchangeBalanceGroup_}; + } + + void Run() override; + +private: + ExchangeBalanceGroup exchangeBalanceGroup_; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h new file mode 100644 index 0000000000..2679f649bf --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h @@ -0,0 +1,57 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace Antares::Data::AdequacyPatch +{ + +/*! + * Calculates curtailment sharing rule parameters netPositionInit, densNew and totalNodeBalance per + * given area and hour. + */ +std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* problemeHebdo, + bool setNTCOutsideToInsideToZero, + int Area, + int hour); + +/*! + * Calculate total local matching rule violation per one area, per one hour. + */ +double LmrViolationAreaHour(PROBLEME_HEBDO* problemeHebdo, + double totalNodeBalance, + double threshold, + int Area, + int hour); + +/*! + * Calculate densNew values for all hours and areas inside adequacy patch and places them into + * problemeHebdo->ResultatsHoraires[Area].ValeursHorairesDENS[hour] to be displayed in output. + * copy-pastes spilled Energy values into spilled Energy values after CSR + * calculates total LMR violations and LMR violations per area per hour inside + * problemeHebdo->ResultatsHoraires[Area].ValeursHorairesLmrViolations[hour] + */ +double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + uint numSpace); +} // namespace Antares::Data::AdequacyPatch diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h new file mode 100644 index 0000000000..cba4657fb2 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h @@ -0,0 +1,46 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/simulation/base_post_process.h" +#include "antares/study/parameters/adq-patch-params.h" + +namespace Antares::Solver::Simulation +{ + +class AdqPatchPostProcessList: public interfacePostProcessList +{ + using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; + +public: + AdqPatchPostProcessList(const AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + uint thread_number, + AreaList& areas, + SheddingPolicy sheddingPolicy, + SimplexOptimization splxOptimization, + Calendar& calendar); + + virtual ~AdqPatchPostProcessList() = default; +}; + +} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.h new file mode 100644 index 0000000000..562126a296 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrAreaBalance.h @@ -0,0 +1,55 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "antares/solver/optimisation/constraints/ConstraintBuilder.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" + +struct CsrAreaBalanceData +{ + const std::vector& areaMode; + const int hour; + const std::vector& IndexDebutIntercoOrigine; + const std::vector& IndexSuivantIntercoOrigine; + const std::vector& IndexDebutIntercoExtremite; + const std::vector& IndexSuivantIntercoExtremite; + + const std::vector& originAreaMode; + const std::vector& extremityAreaMode; + const std::vector& PaysOrigineDeLInterconnexion; + const std::vector& PaysExtremiteDeLInterconnexion; + std::map& numberOfConstraintCsrAreaBalance; + const uint32_t NombreDePays; +}; + +class CsrAreaBalance: private ConstraintFactory +{ +public: + CsrAreaBalance(ConstraintBuilder& builder, CsrAreaBalanceData& data): + ConstraintFactory(builder), + data(data) + { + } + + void add(); + +private: + CsrAreaBalanceData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.h new file mode 100644 index 0000000000..08bc1f8a4c --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrBindingConstraintHour.h @@ -0,0 +1,47 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "antares/solver/optimisation/constraints/ConstraintBuilder.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" + +struct CsrBindingConstraintHourData +{ + const std::vector MatriceDesContraintesCouplantes; + const std::vector& originAreaMode; + const std::vector& extremityAreaMode; + const int hour; + std::map& numberOfConstraintCsrHourlyBinding; +}; + +class CsrBindingConstraintHour: private ConstraintFactory +{ +public: + CsrBindingConstraintHour(ConstraintBuilder& builder, CsrBindingConstraintHourData& data): + ConstraintFactory(builder), + data(data) + { + } + + void add(int CntCouplante); + +private: + CsrBindingConstraintHourData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.h new file mode 100644 index 0000000000..79ce80b61a --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/constraints/CsrFlowDissociation.h @@ -0,0 +1,51 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "antares/solver/optimisation/constraints/ConstraintBuilder.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" + +struct CsrFlowDissociationData +{ + std::map& numberOfConstraintCsrFlowDissociation; + const uint32_t NombreDInterconnexions; + + const std::vector& originAreaMode; + const std::vector& extremityAreaMode; + + const std::vector& PaysOrigineDeLInterconnexion; + const std::vector& PaysExtremiteDeLInterconnexion; + const int hour; +}; + +class CsrFlowDissociation: private ConstraintFactory +{ +public: + CsrFlowDissociation(ConstraintBuilder& builder, CsrFlowDissociationData& data): + ConstraintFactory(builder), + data(data) + { + } + + void add(); + +private: + CsrFlowDissociationData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h new file mode 100644 index 0000000000..d664067529 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/count_constraints_variables.h @@ -0,0 +1,30 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace Antares::Data::AdequacyPatch +{ +int countConstraints(const PROBLEME_HEBDO* problemeHebdo); +int countVariables(const PROBLEME_HEBDO* problemeHebdo); +} // namespace Antares::Data::AdequacyPatch diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h new file mode 100644 index 0000000000..a0d393aa39 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/csr_quadratic_problem.h @@ -0,0 +1,54 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +#include "../constraints/ConstraintBuilder.h" +class HourlyCSRProblem; + +namespace Antares::Solver::Optimization +{ + +class CsrQuadraticProblem +{ +public: + CsrQuadraticProblem(PROBLEME_HEBDO* p, + PROBLEME_ANTARES_A_RESOUDRE& pa, + HourlyCSRProblem& hourly): + problemeHebdo_(p), + problemeAResoudre_(pa), + hourlyCsrProblem_(hourly) + { + } + + void buildConstraintMatrix(); + +private: + PROBLEME_HEBDO* problemeHebdo_; + PROBLEME_ANTARES_A_RESOUDRE& problemeAResoudre_; + HourlyCSRProblem& hourlyCsrProblem_; + + void setConstraintsOnFlows(ConstraintBuilder& builder); + void setNodeBalanceConstraints(ConstraintBuilder& builder); + void setBindingConstraints(ConstraintBuilder& builder); +}; + +} // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h new file mode 100644 index 0000000000..c7fb554c22 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_csr/hourly_csr_problem.h @@ -0,0 +1,150 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +// TODO[FOM] Remove this, it is only required for PROBLEME_HEBDO +// but this problem has nothing to do with PROBLEME_HEBDO +#include + +#include +#include +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../variables/VariableManagerUtils.h" + +struct PROBLEME_HEBDO; + +class HourlyCSRProblem +{ +private: + void calculateCsrParameters(); + + void buildProblemVariables(); + void setVariableBounds(); + void buildProblemConstraintsLHS(); + void buildProblemConstraintsRHS(); + void setProblemCost(); + void solveProblem(uint week, int year); + void allocateProblem(); + + // variable construction + void constructVariableENS(); + void constructVariableSpilledEnergy(); + void constructVariableFlows(); + + // variable bounds + void setBoundsOnENS(); + void setBoundsOnSpilledEnergy(); + void setBoundsOnFlows(); + + // Constraints + void setRHSvalueOnFlows(); + void setRHSnodeBalanceValue(); + void setRHSbindingConstraintsValue(); + + // Costs + void setQuadraticCost(); + void setLinearCost(); + +private: + using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; + const AdqPatchParams& adqPatchParams_; + VariableManagement::VariableManager variableManager_; + +public: + void run(uint week, uint year); + + // TODO[FOM] Make these members private + int triggeredHour; + double belowThisThresholdSetToZero; + PROBLEME_HEBDO* problemeHebdo_; + PROBLEME_ANTARES_A_RESOUDRE problemeAResoudre_; + + explicit HourlyCSRProblem(const AdqPatchParams& adqPatchParams, PROBLEME_HEBDO* p): + adqPatchParams_(adqPatchParams), + variableManager_(p->CorrespondanceVarNativesVarOptim, + p->NumeroDeVariableStockFinal, + p->NumeroDeVariableDeTrancheDeStock, + p->NombreDePasDeTempsPourUneOptimisation), + problemeHebdo_(p) + { + double temp = pow(10, -adqPatchParams.curtailmentSharing.thresholdVarBoundsRelaxation); + belowThisThresholdSetToZero = std::min(temp, 0.1); + + allocateProblem(); + } + + ~HourlyCSRProblem() = default; + + HourlyCSRProblem(const HourlyCSRProblem&) = delete; + HourlyCSRProblem& operator=(const HourlyCSRProblem&) = delete; + + inline void setHour(int hour) + { + triggeredHour = hour; + } + + std::map numberOfConstraintCsrEns; + std::map numberOfConstraintCsrAreaBalance; + std::map numberOfConstraintCsrFlowDissociation; + std::map numberOfConstraintCsrHourlyBinding; // length is number of binding constraint + // contains interco 2-2 + + std::map rhsAreaBalanceValues; + std::set varToBeSetToZeroIfBelowThreshold; // place inside only ENS and Spillage variable + std::set ensVariablesInsideAdqPatch; // place inside only ENS inside adq-patch + + struct LinkVariable + { + LinkVariable(): + directVar(-1), + indirectVar(-1) + { + } + + LinkVariable(int direct, int indirect): + directVar(direct), + indirectVar(indirect) + { + } + + inline bool check() const + { + if (directVar < 0) + { + Antares::logs.warning() << "directVar < 0 detected, this should not happen"; + } + if (indirectVar < 0) + { + Antares::logs.warning() << "indirectVar < 0 detected, this should not happen"; + } + + return (directVar >= 0) && (indirectVar >= 0); + } + + int directVar; + int indirectVar; + }; + + // links between two areas inside the adq-patch domain + std::map linkInsideAdqPatch; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h new file mode 100644 index 0000000000..b11bdc817a --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h @@ -0,0 +1,51 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/study/area/area.h" + +#include "../base_weekly_optimization.h" + +using Antares::Data::AreaList; + +namespace Antares::Solver::Optimization +{ +class AdequacyPatchOptimization: public WeeklyOptimization +{ +public: + explicit AdequacyPatchOptimization(const Antares::Data::Study& study, + const OptimizationOptions& options, + PROBLEME_HEBDO* problemeHebdo, + Data::AdequacyPatch::AdqPatchParams&, + uint numSpace, + IResultWriter& writer, + Simulation::ISimulationObserver& observer); + + ~AdequacyPatchOptimization() override = default; + void solve() override; + +private: + const Antares::Data::Study& study_; +}; +} // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h new file mode 100644 index 0000000000..eff8842d7b --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h @@ -0,0 +1,39 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace Antares::Data::AdequacyPatch +{ +/*! + * Sets link bounds for first step of adequacy patch or leaves default values if adequacy patch is + * not used. + */ +void setNTCbounds(double& Xmax, + double& Xmin, + const VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* problemeHebdo, + const AdqPatchParams& adqPatchParams); + +} // namespace Antares::Data::AdequacyPatch diff --git a/src/solver/optimisation/include/antares/solver/optimisation/base_weekly_optimization.h b/src/solver/optimisation/include/antares/solver/optimisation/base_weekly_optimization.h new file mode 100644 index 0000000000..acae5d8aed --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/base_weekly_optimization.h @@ -0,0 +1,61 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include // for "uint" definition + +#include +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace Antares::Solver::Optimization +{ +class WeeklyOptimization +{ +public: + virtual void solve() = 0; + virtual ~WeeklyOptimization() = default; + static std::unique_ptr create( + const Antares::Data::Study& study, + const OptimizationOptions& options, + Antares::Data::AdequacyPatch::AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemesHebdo, + uint numSpace, + IResultWriter& writer, + Simulation::ISimulationObserver& simulationObserver); + +protected: + explicit WeeklyOptimization(const OptimizationOptions& options, + PROBLEME_HEBDO* problemesHebdo, + Antares::Data::AdequacyPatch::AdqPatchParams&, + uint numSpace, + IResultWriter& writer, + Simulation::ISimulationObserver& simulationObserver); + Antares::Solver::Optimization::OptimizationOptions options_; + PROBLEME_HEBDO* const problemeHebdo_ = nullptr; + Antares::Data::AdequacyPatch::AdqPatchParams& adqPatchParams_; + const uint thread_number_ = 0; + IResultWriter& writer_; + std::reference_wrapper simulationObserver_; +}; +} // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/AbstractStartUpCostsGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AbstractStartUpCostsGroup.h new file mode 100644 index 0000000000..d98e198798 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AbstractStartUpCostsGroup.h @@ -0,0 +1,39 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" +#include "PMaxDispatchableGeneration.h" +#include "PMinDispatchableGeneration.h" + +class AbstractStartUpCostsGroup: public ConstraintGroup +{ +public: + AbstractStartUpCostsGroup(PROBLEME_HEBDO* problemeHebdo, + bool simulation, + ConstraintBuilder& builder); + + virtual void BuildConstraints() = 0; + StartUpCostsData GetStartUpCostsDataFromProblemHebdo(); + +protected: + bool simulation_ = false; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaBalance.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaBalance.h new file mode 100644 index 0000000000..ed26123579 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaBalance.h @@ -0,0 +1,58 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "ConstraintBuilder.h" + +struct AreaBalanceData +{ + std::vector& CorrespondanceCntNativesCntOptim; + const std::vector& IndexDebutIntercoOrigine; + const std::vector& IndexSuivantIntercoOrigine; + const std::vector& IndexDebutIntercoExtremite; + const std::vector& IndexSuivantIntercoExtremite; + const std::vector& PaliersThermiquesDuPays; + const std::vector<::ShortTermStorage::AREA_INPUT>& ShortTermStorage; +}; + +/*! + * represent 'Area Balance' constraint type + */ + +class AreaBalance: public ConstraintFactory +{ +public: + AreaBalance(ConstraintBuilder& builder, AreaBalanceData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param pays : area + */ + + void add(int pdt, int pays); + +private: + AreaBalanceData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaHydroLevel.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaHydroLevel.h new file mode 100644 index 0000000000..93e54b3a0a --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaHydroLevel.h @@ -0,0 +1,53 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct AreaHydroLevelData +{ + std::vector& CorrespondanceCntNativesCntOptim; + const std::vector CaracteristiquesHydrauliques; +}; + +/*! + * represent 'Area Hydraulic Level' constraint type + */ + +class AreaHydroLevel: private ConstraintFactory +{ +public: + AreaHydroLevel(ConstraintBuilder& builder, AreaHydroLevelData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param pays : area + */ + void add(int pays, int pdt); + +private: + AreaHydroLevelData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaHydroLevelGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaHydroLevelGroup.h new file mode 100644 index 0000000000..85f6a005e3 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/AreaHydroLevelGroup.h @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AreaHydroLevel.h" +#include "ConstraintGroup.h" + +class AreaHydroLevelGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + AreaHydroLevelData GetAreaHydroLevelData(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintDay.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintDay.h new file mode 100644 index 0000000000..9828b82a68 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintDay.h @@ -0,0 +1,55 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "ConstraintBuilder.h" + +struct BindingConstraintDayData +{ + const std::vector& MatriceDesContraintesCouplantes; + const std::vector& PaliersThermiquesDuPays; + std::vector& + CorrespondanceCntNativesCntOptimJournalieres; + const int32_t& NombreDePasDeTempsDUneJournee; + std::vector& NumeroDeJourDuPasDeTemps; +}; + +/*! + * represent 'Daily Binding Constraint' type + */ + +class BindingConstraintDay: private ConstraintFactory +{ +public: + BindingConstraintDay(ConstraintBuilder& builder, BindingConstraintDayData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param cntCouplante : the binding constraint number + */ + void add(int cntCouplante); + +private: + BindingConstraintDayData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintDayGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintDayGroup.h new file mode 100644 index 0000000000..1cdeabe23e --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintDayGroup.h @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "BindingConstraintDay.h" +#include "ConstraintGroup.h" + +class BindingConstraintDayGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + BindingConstraintDayData GetBindingConstraintDayDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintHour.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintHour.h new file mode 100644 index 0000000000..76c809dc98 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintHour.h @@ -0,0 +1,53 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "ConstraintBuilder.h" + +struct BindingConstraintHourData +{ + const std::vector& MatriceDesContraintesCouplantes; + std::vector& CorrespondanceCntNativesCntOptim; + const std::vector& PaliersThermiquesDuPays; +}; + +/*! + * represent 'Hourly Binding Constraint' type + */ +class BindingConstraintHour: private ConstraintFactory +{ +public: + BindingConstraintHour(ConstraintBuilder& builder, BindingConstraintHourData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param cntCouplante : the binding constraint number + */ + void add(int pdt, int cntCouplante); + +private: + BindingConstraintHourData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintWeek.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintWeek.h new file mode 100644 index 0000000000..ef117ec27c --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintWeek.h @@ -0,0 +1,53 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct BindingConstraintWeekData +{ + const std::vector& MatriceDesContraintesCouplantes; + const std::vector& PaliersThermiquesDuPays; + std::vector& NumeroDeContrainteDesContraintesCouplantes; +}; + +/*! + * represent 'Hourly Binding Constraint' type + */ + +class BindingConstraintWeek: private ConstraintFactory +{ +public: + BindingConstraintWeek(ConstraintBuilder& builder, BindingConstraintWeekData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param cntCouplante : the binding constraint number + */ + void add(int cntCouplante); + +private: + BindingConstraintWeekData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintWeekGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintWeekGroup.h new file mode 100644 index 0000000000..49c54806ae --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/BindingConstraintWeekGroup.h @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "BindingConstraintWeek.h" +#include "ConstraintGroup.h" + +class BindingConstraintWeekGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + BindingConstraintWeekData GetBindingConstraintWeekDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h new file mode 100644 index 0000000000..8f7a19bf9d --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnits.h @@ -0,0 +1,48 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +/*! + * represent 'Consistence Number Of Dispatchable Units Constraint' type + */ +class ConsistenceNumberOfDispatchableUnits: private ConstraintFactory +{ +public: + ConsistenceNumberOfDispatchableUnits(ConstraintBuilder& builder, StartUpCostsData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + * @param cluster : global index of the cluster + * @param pdt : timestep + * @param Simulation : --- + */ + void add(int pays, int index, int pdt); + +private: + StartUpCostsData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.h new file mode 100644 index 0000000000..099b8cc484 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConsistenceNumberOfDispatchableUnitsGroup.h @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AbstractStartUpCostsGroup.h" +#include "ConstraintGroup.h" + +/** + * @brief Group of ConsistenceNumberOfDispatchableUnits constraints + * + */ + +class ConsistenceNumberOfDispatchableUnitsGroup: public AbstractStartUpCostsGroup +{ +public: + using AbstractStartUpCostsGroup::AbstractStartUpCostsGroup; + + void BuildConstraints() override; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConstraintBuilder.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConstraintBuilder.h new file mode 100644 index 0000000000..2dfdec8000 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConstraintBuilder.h @@ -0,0 +1,290 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include + +#include +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "../opt_fonctions.h" +#include "../opt_rename_problem.h" +#include "../variables/VariableManagement.h" + +// TODO God struct should be decomposed +class ConstraintBuilderData +{ +public: + std::vector& Pi; + std::vector& Colonne; + int& nombreDeContraintes; + int& nombreDeTermesDansLaMatriceDeContrainte; + std::vector& IndicesDebutDeLigne; + std::vector& CoefficientsDeLaMatriceDesContraintes; + std::vector& IndicesColonnes; + int& NombreDeTermesAllouesDansLaMatriceDesContraintes; // TODO Check if ref is needed + std::vector& NombreDeTermesDesLignes; + std::string& Sens; + int& IncrementDAllocationMatriceDesContraintes; + std::vector& CorrespondanceVarNativesVarOptim; + const int32_t& NombreDePasDeTempsPourUneOptimisation; + std::vector& NumeroDeVariableStockFinal; + std::vector>& NumeroDeVariableDeTrancheDeStock; + std::vector& NomDesContraintes; + const bool& NamedProblems; + const std::vector& NomsDesPays; + const uint32_t& weekInTheYear; + const uint32_t& NombreDePasDeTemps; + uint32_t& NbTermesContraintesPourLesCoutsDeDemarrage; +}; + +/*! \verbatim +this class build up the business object 'Constraint', +Math: +|coeff11 coeff12 .. coeff1n||var1| |sign_1| |rhs1| |constraint1||sign_1||rhs1| +|.. .. ...||....| |......| |....| <===> |...........||......||....| +|coeffn1 coeffn2 .. coeffnn||varn| |sign_n| |rhsn| |constraintn||sign_n||rhsn| + +it propose a set of methods to attach 'Variables' to the Constraint +ex: calling NTCDirect() implies adding Direct NTC Variable to the current Constraint +finally the build() method gather all variables and put them into the matrix +\endverbatim +*/ +class ConstraintBuilder +{ +public: + ConstraintBuilder() = delete; + + explicit ConstraintBuilder(ConstraintBuilderData& data): + data(data), + variableManager_(data.CorrespondanceVarNativesVarOptim, + data.NumeroDeVariableStockFinal, + data.NumeroDeVariableDeTrancheDeStock, + data.NombreDePasDeTempsPourUneOptimisation) + { + } + + ConstraintBuilder& updateHourWithinWeek(unsigned hour) + { + hourInWeek_ = hour; + return *this; + } + + /** @name variables_method + * @brief Documentation for non obvious methods + * @param index: local index of the variable + * @param offset: offset from the current time step + * @param delta: number of time steps for the variable + * @return reference of *this + */ + //@{ + ConstraintBuilder& DispatchableProduction(unsigned int index, + double coeff, + int offset = 0, + int delta = 0); + + ConstraintBuilder& NumberOfDispatchableUnits(unsigned int index, double coeff); + + ConstraintBuilder& NumberStoppingDispatchableUnits(unsigned int index, double coeff); + + ConstraintBuilder& NumberStartingDispatchableUnits(unsigned int index, double coeff); + + ConstraintBuilder& NumberBreakingDownDispatchableUnits(unsigned int index, double coeff); + + ConstraintBuilder& NTCDirect(unsigned int index, double coeff, int offset = 0, int delta = 0); + + ConstraintBuilder& IntercoDirectCost(unsigned int index, double coeff); + + ConstraintBuilder& IntercoIndirectCost(unsigned int index, double coeff); + + ConstraintBuilder& ShortTermStorageInjection(unsigned int index, double coeff); + + ConstraintBuilder& ShortTermStorageWithdrawal(unsigned int index, double coeff); + + ConstraintBuilder& ShortTermStorageLevel(unsigned int index, + double coeff, + int offset = 0, + int delta = 0); + + ConstraintBuilder& HydProd(unsigned int index, double coeff); + + ConstraintBuilder& HydProdDown(unsigned int index, double coeff); + + ConstraintBuilder& HydProdUp(unsigned int index, double coeff); + + ConstraintBuilder& Pumping(unsigned int index, double coeff); + + ConstraintBuilder& HydroLevel(unsigned int index, double coeff); + + ConstraintBuilder& Overflow(unsigned int index, double coeff); + + ConstraintBuilder& FinalStorage(unsigned int index, double coeff); + + ConstraintBuilder& PositiveUnsuppliedEnergy(unsigned int index, double coeff); + + ConstraintBuilder& NegativeUnsuppliedEnergy(unsigned int index, double coeff); + + ConstraintBuilder& LayerStorage(unsigned area, unsigned layer, double coeff); + + //@} + + class ConstraintBuilderInvalidOperator: public std::runtime_error + { + public: + using std::runtime_error::runtime_error; + }; + + /*! + @brief set the operator of the constraint (sign) + @param op: the operator of the constraint + @return reference of *this + */ + ConstraintBuilder& SetOperator(char op) + { + if (op == '<' || op == '=' || op == '>') + { + operator_ = op; + } + else + { + throw ConstraintBuilderInvalidOperator(std::string("Invalid operator: ") + op); + } + + return *this; + } + + /*! + @brief set the sign of the constraint to '=', + building a constraint equal to rhs + @return reference of *this + */ + ConstraintBuilder& equalTo() + { + operator_ = '='; + return *this; + } + + /*! + @brief set the sign of the constraint to '<', + building a constraint less than rhs + @return reference of *this + */ + ConstraintBuilder& lessThan() + { + operator_ = '<'; + return *this; + } + + /*! + @brief set the sign of the constraint to '>', + building a constraint greather than rhs + @return reference of *this + */ + ConstraintBuilder& greaterThan() + { + operator_ = '>'; + return *this; + } + + /*! + @brief add the constraint in the matrix + @return + */ + void build(); + + int NumberOfVariables() const + { + return nombreDeTermes_; + } + + ConstraintBuilderData& data; + +private: + void OPT_ChargerLaContrainteDansLaMatriceDesContraintes(); + + void OPT_AugmenterLaTailleDeLaMatriceDesContraintes(); + + unsigned int hourInWeek_ = 0; + + char operator_ = '='; + int nombreDeTermes_ = 0; + + void AddVariable(int index, double coeff); + + /*! + * @brief + * @param offset: offset from the current time step + * @param delta: number of time steps for the variable + * @return VariableManager object + */ + VariableManagement::VariableManager variableManager_; +}; + +/*! factory class to build a Constraint */ +class ConstraintFactory +{ +public: + ConstraintFactory() = delete; + + explicit ConstraintFactory(ConstraintBuilder& builder): + builder(builder) + { + } + + ConstraintBuilder& builder; +}; + +// Helper functions +inline void ExportPaliers(const PALIERS_THERMIQUES& PaliersThermiquesDuPays, + ConstraintBuilder& newConstraintBuilder) +{ + for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) + { + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + newConstraintBuilder.DispatchableProduction(palier, -1.0); + } +} + +class BindingConstraintData +{ +public: + const char& TypeDeContrainteCouplante; + const int& NombreDInterconnexionsDansLaContrainteCouplante; + const std::vector& NumeroDeLInterconnexion; + const std::vector& PoidsDeLInterconnexion; + const std::vector& OffsetTemporelSurLInterco; + const int& NombreDePaliersDispatchDansLaContrainteCouplante; + const std::vector& PaysDuPalierDispatch; + const std::vector& NumeroDuPalierDispatch; + const std::vector& PoidsDuPalierDispatch; + const std::vector& OffsetTemporelSurLePalierDispatch; + const char& SensDeLaContrainteCouplante; + const char* const& NomDeLaContrainteCouplante; + const std::vector& PaliersThermiquesDuPays; +}; + +struct StartUpCostsData +{ + const std::vector& PaliersThermiquesDuPays; + bool Simulation; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConstraintGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConstraintGroup.h new file mode 100644 index 0000000000..5b2087767a --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ConstraintGroup.h @@ -0,0 +1,42 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "constraint_builder_utils.h" + +class ConstraintGroup +{ +public: + explicit ConstraintGroup(PROBLEME_HEBDO* problemeHebdo, ConstraintBuilder& builder): + problemeHebdo_(problemeHebdo), + builder_(builder) + { + } + + virtual ~ConstraintGroup() = default; + virtual void BuildConstraints() = 0; + PROBLEME_HEBDO* problemeHebdo_; + ConstraintBuilder& builder_; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ExchangeBalance.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ExchangeBalance.h new file mode 100644 index 0000000000..890a735ff5 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ExchangeBalance.h @@ -0,0 +1,49 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct ExchangeBalanceData +{ + const std::vector& IndexDebutIntercoOrigine; + const std::vector& IndexSuivantIntercoOrigine; + const std::vector& IndexDebutIntercoExtremite; + const std::vector& IndexSuivantIntercoExtremite; + std::vector& NumeroDeContrainteDeSoldeDEchange; +}; + +class ExchangeBalance: private ConstraintFactory +{ +public: + ExchangeBalance(ConstraintBuilder& builder, ExchangeBalanceData& data): + ConstraintFactory(builder), + data(data) + { + } + + // TODO transform data to ref + void add(uint32_t pays); + +private: + ExchangeBalanceData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ExchangeBalanceGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ExchangeBalanceGroup.h new file mode 100644 index 0000000000..ebf73076c6 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ExchangeBalanceGroup.h @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" +#include "ExchangeBalance.h" + +class ExchangeBalanceGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + ExchangeBalanceData GetExchangeBalanceDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/FictitiousLoad.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FictitiousLoad.h new file mode 100644 index 0000000000..573f234c67 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FictitiousLoad.h @@ -0,0 +1,54 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct FictitiousLoadData +{ + std::vector& CorrespondanceCntNativesCntOptim; + const std::vector& PaliersThermiquesDuPays; + const std::vector& DefaillanceNegativeUtiliserHydro; +}; + +/*! + * represent 'Fictitious Load' constraint type + */ +class FictitiousLoad: private ConstraintFactory +{ +public: + FictitiousLoad(ConstraintBuilder& builder, FictitiousLoadData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param pays : area + */ + void add(int pdt, int pays); + +private: + FictitiousLoadData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockEquivalent.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockEquivalent.h new file mode 100644 index 0000000000..48a530e618 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockEquivalent.h @@ -0,0 +1,51 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct FinalStockEquivalentData +{ + const std::vector CaracteristiquesHydrauliques; + std::vector& NumeroDeContrainteEquivalenceStockFinal; +}; + +/*! + * represent 'Final Stock Equivalent' constraint type + */ +class FinalStockEquivalent: private ConstraintFactory +{ +public: + FinalStockEquivalent(ConstraintBuilder& builder, FinalStockEquivalentData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays); + +private: + FinalStockEquivalentData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockExpression.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockExpression.h new file mode 100644 index 0000000000..c87a710fec --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockExpression.h @@ -0,0 +1,52 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "ConstraintBuilder.h" + +struct FinalStockExpressionData +{ + const std::vector CaracteristiquesHydrauliques; + std::vector& NumeroDeContrainteExpressionStockFinal; +}; + +/*! + * represent 'Final Stock Expression' constraint type + */ +class FinalStockExpression: private ConstraintFactory +{ +public: + FinalStockExpression(ConstraintBuilder& builder, FinalStockExpressionData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays); + +private: + FinalStockExpressionData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockGroup.h new file mode 100644 index 0000000000..b023ec3c65 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FinalStockGroup.h @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" +#include "FinalStockEquivalent.h" +#include "FinalStockExpression.h" + +class FinalStockGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + FinalStockEquivalentData GetFinalStockEquivalentData(); + FinalStockExpressionData GetFinalStockExpressionData(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/FlowDissociation.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FlowDissociation.h new file mode 100644 index 0000000000..81218c1d9f --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/FlowDissociation.h @@ -0,0 +1,55 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct FlowDissociationData +{ + std::vector& CorrespondanceCntNativesCntOptim; + const std::vector& CoutDeTransport; + const std::vector& PaysOrigineDeLInterconnexion; + const std::vector& PaysExtremiteDeLInterconnexion; +}; + +/*! + * represent 'Flow Dissociation' constraint type + */ + +class FlowDissociation: private ConstraintFactory +{ +public: + FlowDissociation(ConstraintBuilder& builder, FlowDissociationData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param interco : interconnection number + */ + void add(int pdt, int interco); + +private: + FlowDissociationData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/Group1.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/Group1.h new file mode 100644 index 0000000000..2428ccaa44 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/Group1.h @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AreaBalance.h" +#include "BindingConstraintHour.h" +#include "ConstraintGroup.h" +#include "FictitiousLoad.h" +#include "FlowDissociation.h" +#include "ShortTermStorageLevel.h" + +class Group1: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + AreaBalanceData GetAreaBalanceData(); + FictitiousLoadData GetFictitiousLoadData(); + ShortTermStorageLevelData GetShortTermStorageLevelData(); + FlowDissociationData GetFlowDissociationData(); + BindingConstraintHourData GetBindingConstraintHourData(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydraulicSmoothingGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydraulicSmoothingGroup.h new file mode 100644 index 0000000000..821360961c --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydraulicSmoothingGroup.h @@ -0,0 +1,33 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" + +class HydraulicSmoothingGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPower.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPower.h new file mode 100644 index 0000000000..29f248f7bb --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPower.h @@ -0,0 +1,53 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct HydroPowerData +{ + const std::vector& CaracteristiquesHydrauliques; + const int& NombreDePasDeTempsPourUneOptimisation; + std::vector& NumeroDeContrainteEnergieHydraulique; +}; + +/*! + * represent 'Hydraulic Power' constraint type + */ + +class HydroPower: private ConstraintFactory +{ +public: + HydroPower(ConstraintBuilder& builder, HydroPowerData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays); + +public: + HydroPowerData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerGroup.h new file mode 100644 index 0000000000..b89eadf2ac --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerGroup.h @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" +#include "HydroPower.h" + +class HydroPowerGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + HydroPowerData GetHydroPowerDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h new file mode 100644 index 0000000000..0249e40254 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxDown.h @@ -0,0 +1,39 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +/*! + * represent 'Hydraulic Power Smoothing Using Variation Max Down' constraint type + */ + +class HydroPowerSmoothingUsingVariationMaxDown: private ConstraintFactory +{ +public: + using ConstraintFactory::ConstraintFactory; + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param pays : area + */ + void add(int pays, int pdt); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h new file mode 100644 index 0000000000..13dfc386bb --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationMaxUp.h @@ -0,0 +1,39 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +/*! + * represent 'Hydraulic Power Smoothing Using Variation Max Up' constraint type + */ +class HydroPowerSmoothingUsingVariationMaxUp: private ConstraintFactory +{ +public: + using ConstraintFactory::ConstraintFactory; + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pdt : timestep + * @param pays : area + */ + void add(int pays, int pdt); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h new file mode 100644 index 0000000000..4104627df5 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/HydroPowerSmoothingUsingVariationSum.h @@ -0,0 +1,39 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +/*! + * represent 'Hydraulic Power Smoothing Using Variation Sum' constraint type + */ + +class HydroPowerSmoothingUsingVariationSum: private ConstraintFactory +{ +public: + using ConstraintFactory::ConstraintFactory; + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays, const int nombreDePasDeTempsPourUneOptimisation); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxHydroPower.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxHydroPower.h new file mode 100644 index 0000000000..8f31968836 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxHydroPower.h @@ -0,0 +1,52 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct MaxHydroPowerData +{ + const std::vector CaracteristiquesHydrauliques; + const int& NombreDePasDeTempsPourUneOptimisation; + std::vector& NumeroDeContrainteMaxEnergieHydraulique; +}; + +/*! + * represent 'Max Hydraulic Power' constraint type + */ +class MaxHydroPower: private ConstraintFactory +{ +public: + MaxHydroPower(ConstraintBuilder& builder, MaxHydroPowerData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays); + +private: + MaxHydroPowerData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxPumping.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxPumping.h new file mode 100644 index 0000000000..624129a6fd --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxPumping.h @@ -0,0 +1,52 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct MaxPumpingData +{ + const std::vector CaracteristiquesHydrauliques; + std::vector& NumeroDeContrainteMaxPompage; +}; + +/*! + * represent 'Max Pumping' constraint type + */ + +class MaxPumping: private ConstraintFactory +{ +public: + MaxPumping(ConstraintBuilder& builder, MaxPumpingData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays); + +private: + MaxPumpingData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxPumpingGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxPumpingGroup.h new file mode 100644 index 0000000000..0273d5080b --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MaxPumpingGroup.h @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" +#include "MaxPumping.h" + +class MaxPumpingGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + MaxPumpingData GetMaxPumpingData(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinDownTime.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinDownTime.h new file mode 100644 index 0000000000..3a6c3a4155 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinDownTime.h @@ -0,0 +1,55 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct MinDownTimeData +{ + const std::vector& PaliersThermiquesDuPays; + bool Simulation; + std::vector& CorrespondanceCntNativesCntOptim; +}; + +/*! + * represent 'MinDownTime' Constraint type + */ +class MinDownTime: private ConstraintFactory +{ +public: + MinDownTime(ConstraintBuilder& builder, MinDownTimeData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + * @param cluster : global index of the cluster + * @param pdt : timestep + * @param Simulation : --- + */ + void add(int pays, int index, int pdt); + +private: + MinDownTimeData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinDownTimeGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinDownTimeGroup.h new file mode 100644 index 0000000000..7084f23eef --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinDownTimeGroup.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AbstractStartUpCostsGroup.h" +#include "ConstraintGroup.h" +#include "MinDownTime.h" + +/** + * @brief Group of MinDownTime constraints + * + */ + +class MinDownTimeGroup: public AbstractStartUpCostsGroup +{ +public: + using AbstractStartUpCostsGroup::AbstractStartUpCostsGroup; + + void BuildConstraints() override; + +private: + MinDownTimeData GetMinDownTimeDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinHydroPower.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinHydroPower.h new file mode 100644 index 0000000000..4fd75a981e --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinHydroPower.h @@ -0,0 +1,53 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct MinHydroPowerData +{ + const std::vector CaracteristiquesHydrauliques; + const int& NombreDePasDeTempsPourUneOptimisation; + std::vector& NumeroDeContrainteMinEnergieHydraulique; +}; + +/*! + * represent 'Min Hydraulic Power' constraint type + */ + +class MinHydroPower: private ConstraintFactory +{ +public: + MinHydroPower(ConstraintBuilder& builder, MinHydroPowerData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + */ + void add(int pays); + +private: + MinHydroPowerData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinMaxHydroPowerGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinMaxHydroPowerGroup.h new file mode 100644 index 0000000000..30a9190472 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/MinMaxHydroPowerGroup.h @@ -0,0 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintGroup.h" +#include "MaxHydroPower.h" +#include "MinHydroPower.h" + +class MinMaxHydroPowerGroup: public ConstraintGroup +{ +public: + using ConstraintGroup::ConstraintGroup; + + void BuildConstraints() override; + +private: + MinHydroPowerData GetMinHydroPowerData(); + MaxHydroPowerData GetMaxHydroPowerData(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h new file mode 100644 index 0000000000..bcaf06df71 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTime.h @@ -0,0 +1,55 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "ConstraintBuilder.h" + +struct NbDispUnitsMinBoundSinceMinUpTimeData +{ + const std::vector& PaliersThermiquesDuPays; + bool Simulation; + std::vector& CorrespondanceCntNativesCntOptim; +}; + +/*! + * represent 'Number of Dispatchable Units Min Bound Since Min Up Time' type + */ +class NbDispUnitsMinBoundSinceMinUpTime: private ConstraintFactory +{ +public: + NbDispUnitsMinBoundSinceMinUpTime(ConstraintBuilder& builder, + NbDispUnitsMinBoundSinceMinUpTimeData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + * @param cluster : global index of the cluster + * @param pdt : timestep + * @param Simulation : --- + */ + void add(int pays, int index, int pdt); + +private: + NbDispUnitsMinBoundSinceMinUpTimeData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.h new file mode 100644 index 0000000000..cd7ea3a6dc --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbDispUnitsMinBoundSinceMinUpTimeGroup.h @@ -0,0 +1,42 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AbstractStartUpCostsGroup.h" +#include "ConstraintGroup.h" +#include "NbDispUnitsMinBoundSinceMinUpTime.h" + +/** + * @brief Group of NbDispUnitsMinBoundSinceMinUpTime constraints + * + */ + +class NbDispUnitsMinBoundSinceMinUpTimeGroup: public AbstractStartUpCostsGroup +{ +public: + using AbstractStartUpCostsGroup::AbstractStartUpCostsGroup; + + void BuildConstraints() override; + +private: + NbDispUnitsMinBoundSinceMinUpTimeData + GetNbDispUnitsMinBoundSinceMinUpTimeDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h new file mode 100644 index 0000000000..a3b7b0e2e3 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStop.h @@ -0,0 +1,55 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include "ConstraintBuilder.h" + +struct NbUnitsOutageLessThanNbUnitsStopData +{ + const std::vector& PaliersThermiquesDuPays; + bool Simulation; + std::vector& CorrespondanceCntNativesCntOptim; +}; + +/*! + * represent 'NbUnitsOutageLessThanNbUnitsStop' type + */ +class NbUnitsOutageLessThanNbUnitsStop: private ConstraintFactory +{ +public: + NbUnitsOutageLessThanNbUnitsStop(ConstraintBuilder& builder, + NbUnitsOutageLessThanNbUnitsStopData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + * @param cluster : global index of the cluster + * @param pdt : timestep + * @param Simulation : --- + */ + void add(int pays, int index, int pdt); + +private: + NbUnitsOutageLessThanNbUnitsStopData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.h new file mode 100644 index 0000000000..ff5ce2b43e --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/NbUnitsOutageLessThanNbUnitsStopGroup.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AbstractStartUpCostsGroup.h" +#include "ConstraintGroup.h" +#include "NbUnitsOutageLessThanNbUnitsStop.h" + +/** + * @brief Group of NbUnitsOutageLessThanNbUnitsStop constraints + * + */ + +class NbUnitsOutageLessThanNbUnitsStopGroup: public AbstractStartUpCostsGroup +{ +public: + using AbstractStartUpCostsGroup::AbstractStartUpCostsGroup; + + void BuildConstraints() override; + +private: + NbUnitsOutageLessThanNbUnitsStopData GetNbUnitsOutageLessThanNbUnitsStopDataFromProblemHebdo(); +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMaxDispatchableGeneration.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMaxDispatchableGeneration.h new file mode 100644 index 0000000000..0e40b4c6db --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMaxDispatchableGeneration.h @@ -0,0 +1,48 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +/*! + * represent 'PMaxDispatchableGeneration' Constraint type + */ +class PMaxDispatchableGeneration: private ConstraintFactory +{ +public: + PMaxDispatchableGeneration(ConstraintBuilder& builder, StartUpCostsData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + * @param cluster : global index of the cluster + * @param pdt : timestep + * @param Simulation : --- + */ + void add(int pays, int index, int pdt); + +private: + StartUpCostsData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMinDispatchableGeneration.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMinDispatchableGeneration.h new file mode 100644 index 0000000000..4bc9383d2d --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMinDispatchableGeneration.h @@ -0,0 +1,48 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +/*! + * represent 'PMinDispatchableGeneration' Constraint type + */ +class PMinDispatchableGeneration: private ConstraintFactory +{ +public: + PMinDispatchableGeneration(ConstraintBuilder& builder, StartUpCostsData& data): + ConstraintFactory(builder), + data(data) + { + } + + /*! + * @brief Add variables to the constraint and update constraints Matrix + * @param pays : area + * @param cluster : global index of the cluster + * @param pdt : timestep + * @param Simulation : --- + */ + void add(int pays, int index, int pdt); + +private: + StartUpCostsData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.h new file mode 100644 index 0000000000..43d8430fa7 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/PMinMaxDispatchableGenerationGroup.h @@ -0,0 +1,38 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "AbstractStartUpCostsGroup.h" +#include "ConstraintGroup.h" +#include "PMaxDispatchableGeneration.h" +#include "PMinDispatchableGeneration.h" + +/** + * @brief Group of Pmin/PmaxDispatchableGenerationGroup constraints + * + */ +class PMinMaxDispatchableGenerationGroup: public AbstractStartUpCostsGroup +{ +public: + using AbstractStartUpCostsGroup::AbstractStartUpCostsGroup; + + void BuildConstraints() override; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/ShortTermStorageLevel.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ShortTermStorageLevel.h new file mode 100644 index 0000000000..5571e4636c --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/ShortTermStorageLevel.h @@ -0,0 +1,45 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "ConstraintBuilder.h" + +struct ShortTermStorageLevelData +{ + std::vector& CorrespondanceCntNativesCntOptim; + + const std::vector<::ShortTermStorage::AREA_INPUT>& ShortTermStorage; +}; + +class ShortTermStorageLevel: private ConstraintFactory +{ +public: + ShortTermStorageLevel(ConstraintBuilder& builder, ShortTermStorageLevelData& data): + ConstraintFactory(builder), + data(data) + { + } + + void add(int pdt, int pays); + +private: + ShortTermStorageLevelData& data; +}; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/constraints/constraint_builder_utils.h b/src/solver/optimisation/include/antares/solver/optimisation/constraints/constraint_builder_utils.h new file mode 100644 index 0000000000..9e940aa200 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/constraints/constraint_builder_utils.h @@ -0,0 +1,36 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include + +#include "ConstraintBuilder.h" +struct PROBLEME_HEBDO; + +ConstraintBuilderData NewGetConstraintBuilderFromProblemHebdoAndProblemAResoudre( + PROBLEME_HEBDO* problemeHebdo, + PROBLEME_ANTARES_A_RESOUDRE& ProblemeAResoudre); + +inline ConstraintBuilderData NewGetConstraintBuilderFromProblemHebdo(PROBLEME_HEBDO* problemeHebdo) +{ + auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; + return NewGetConstraintBuilderFromProblemHebdoAndProblemAResoudre(problemeHebdo, + *ProblemeAResoudre); +} diff --git a/src/solver/optimisation/include/antares/solver/optimisation/opt_constants.h b/src/solver/optimisation/include/antares/solver/optimisation/opt_constants.h new file mode 100644 index 0000000000..1e0be3e653 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/opt_constants.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/simulation/sim_constants.h" + +constexpr char PREMIERE_OPTIMISATION = 1; +constexpr char DEUXIEME_OPTIMISATION = 2; + +constexpr char CONTRAINTE_HORAIRE = 1; +constexpr char CONTRAINTE_JOURNALIERE = 2; +constexpr char CONTRAINTE_HEBDOMADAIRE = 3; + +constexpr char PAS_DE_LISSAGE_HYDRAULIQUE = 0; +constexpr char LISSAGE_HYDRAULIQUE_SUR_SOMME_DES_VARIATIONS = 1; +constexpr char LISSAGE_HYDRAULIQUE_SUR_VARIATION_MAX = 2; + +constexpr char ALTRUISTE = 1; +constexpr char EGOISTE = 2; + +constexpr char ANTARES_SIMPLEXE = 1; +constexpr char ANTARES_PNE = 2; diff --git a/src/solver/optimisation/include/antares/solver/optimisation/opt_export_structure.h b/src/solver/optimisation/include/antares/solver/optimisation/opt_export_structure.h new file mode 100644 index 0000000000..47aa3838e1 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/opt_export_structure.h @@ -0,0 +1,32 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include + +#include "antares/antares/Enum.hpp" +#include "antares/writer/i_writer.h" +struct PROBLEME_HEBDO; + +void OPT_ExportInterco(Antares::Solver::IResultWriter& writer, PROBLEME_HEBDO* problemeHebdo); +void OPT_ExportAreaName(Antares::Solver::IResultWriter& writer, + const std::vector& areaNames); +void OPT_ExportStructures(PROBLEME_HEBDO* problemeHebdo, Antares::Solver::IResultWriter& writer); diff --git a/src/solver/optimisation/include/antares/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/include/antares/solver/optimisation/opt_fonctions.h new file mode 100644 index 0000000000..4be6b8e1d7 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/opt_fonctions.h @@ -0,0 +1,123 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_OPTIMISATION_FUNCTIONS_H__ +#define __SOLVER_OPTIMISATION_FUNCTIONS_H__ + +#include +#include +#include +#include "antares/config/config.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/study/parameters/adq-patch-params.h" + +#include "adequacy_patch_csr/hourly_csr_problem.h" + +using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; +using OptimizationOptions = Antares::Solver::Optimization::OptimizationOptions; + +void OPT_OptimisationHebdomadaire(const OptimizationOptions& options, + PROBLEME_HEBDO* pProblemeHebdo, + const AdqPatchParams& adqPatchParams, + Solver::IResultWriter& writer, + Solver::Simulation::ISimulationObserver& simulationObserver); +void OPT_NumeroDeJourDuPasDeTemps(PROBLEME_HEBDO*); +void OPT_NumeroDIntervalleOptimiseDuPasDeTemps(PROBLEME_HEBDO*); +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBDO*); +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_HEBDO*); +void OPT_InitialiserLesPminHebdo(PROBLEME_HEBDO*); +void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise(PROBLEME_HEBDO*); +void OPT_MaxDesPmaxHydrauliques(PROBLEME_HEBDO*); +void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO*, + const AdqPatchParams&, + const int, + const int, + const int); +void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO*, int); +void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO*, int, int, int, const int); +void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO*, int); +void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO*, const int, const int); +void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO*, int); +void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); +bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); + +using namespace Antares::Data::AdequacyPatch; +bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE&, + HourlyCSRProblem&, + const AdqPatchParams&, + uint week, + int year); + +bool OPT_PilotageOptimisationLineaire(const OptimizationOptions& options, + PROBLEME_HEBDO* problemeHebdo, + const AdqPatchParams& adqPatchParams, + Solver::IResultWriter& writer, + Solver::Simulation::ISimulationObserver& simulationObserver); +void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); +bool OPT_PilotageOptimisationQuadratique(PROBLEME_HEBDO*); + +/*! +** \brief Appel du solver +** +** \return True si l'operation s'est bien deroulee, false si le probleme n'a pas de solution +*/ +bool OPT_AppelDuSimplexe(const OptimizationOptions& options, + PROBLEME_HEBDO*, + int, + const int, + const OptPeriodStringGenerator&, + Antares::Solver::IResultWriter& writer); +void OPT_LiberationProblemesSimplexe(const OptimizationOptions& options, const PROBLEME_HEBDO*); + +bool OPT_OptimisationLineaire(const OptimizationOptions& options, + PROBLEME_HEBDO* problemeHebdo, + const AdqPatchParams& adqPatchParams, + Solver::IResultWriter& writer, + Solver::Simulation::ISimulationObserver& simulationObserver); +void OPT_RestaurerLesDonnees(PROBLEME_HEBDO*); +/*------------------------------*/ + +void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO*); +double OPT_CalculerAireMaxPminJour(int, int, int, int, std::vector&, std::vector&); + +void OPT_ChainagesDesIntercoPartantDUnNoeud(PROBLEME_HEBDO*); + +void OPT_AllocateFromNumberOfVariableConstraints(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + int); +void OPT_AllocDuProblemeAOptimiser(PROBLEME_HEBDO*); +int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO*); +void OPT_AugmenterLaTailleDeLaMatriceDesContraintes(PROBLEME_ANTARES_A_RESOUDRE*); + +/*------------------------------*/ + +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, + bool); +void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, + const int, + const int); +void OPT_InitialiserLesCoutsLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, const int, const int); +void OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, int, int); +void OPT_DecompteDesVariablesEtDesContraintesCoutsDeDemarrage(PROBLEME_HEBDO*); +void OPT_InitialiserNombreMinEtMaxDeGroupesCoutsDeDemarrage(PROBLEME_HEBDO*); +void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO*); +double OPT_SommeDesPminThermiques(const PROBLEME_HEBDO*, int, uint); + +#endif /* __SOLVER_OPTIMISATION_FUNCTIONS_H__ */ diff --git a/src/solver/optimisation/opt_rename_problem.h b/src/solver/optimisation/include/antares/solver/optimisation/opt_rename_problem.h similarity index 79% rename from src/solver/optimisation/opt_rename_problem.h rename to src/solver/optimisation/include/antares/solver/optimisation/opt_rename_problem.h index 50c0ac8778..fafb4f2e45 100644 --- a/src/solver/optimisation/opt_rename_problem.h +++ b/src/solver/optimisation/include/antares/solver/optimisation/opt_rename_problem.h @@ -1,5 +1,26 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once -#include "opt_structure_probleme_a_resoudre.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" + #include "opt_export_structure.h" const std::string SEPARATOR = "::"; @@ -8,7 +29,8 @@ const std::string AREA_SEP = "$$"; class TargetVectorUpdater { public: - explicit TargetVectorUpdater(std::vector& target) : target_(target) + explicit TargetVectorUpdater(std::vector& target): + target_(target) { } @@ -24,7 +46,8 @@ class TargetVectorUpdater class Namer { public: - explicit Namer(std::vector& target) : targetUpdater_(target) + explicit Namer(std::vector& target): + targetUpdater_(target) { } @@ -37,6 +60,7 @@ class Namer { area_ = area; } + void SetLinkElementName(unsigned int variable, const std::string& variableType); void SetAreaElementNameHour(unsigned int variable, const std::string& variableType); void SetAreaElementNameWeek(unsigned int variable, const std::string& variableType); @@ -54,7 +78,7 @@ class Namer TargetVectorUpdater targetUpdater_; }; -class VariableNamer : public Namer +class VariableNamer: public Namer { public: using Namer::Namer; @@ -96,7 +120,7 @@ class VariableNamer : public Namer const std::string& shortTermStorageName); }; -class ConstraintNamer : public Namer +class ConstraintNamer: public Namer { public: using Namer::Namer; @@ -104,6 +128,7 @@ class ConstraintNamer : public Namer void FlowDissociation(unsigned int constraint, const std::string& origin, const std::string& destination); + void AreaBalance(unsigned int constraint); void FictiveLoads(unsigned int constraint); void HydroPower(unsigned int constraint); @@ -126,6 +151,12 @@ class ConstraintNamer : public Namer void BindingConstraintHour(unsigned int constraint, const std::string& name); void BindingConstraintDay(unsigned int constraint, const std::string& name); void BindingConstraintWeek(unsigned int constraint, const std::string& name); + void CsrFlowDissociation(unsigned int constraint, + const std::string& origin, + const std::string& destination); + + void CsrAreaBalance(unsigned int constraint); + void CsrBindingConstraintHour(unsigned int constraint, const std::string& name); private: void nameWithTimeGranularity(unsigned int constraint, diff --git a/src/solver/optimisation/include/antares/solver/optimisation/opt_structure_probleme_a_resoudre.h b/src/solver/optimisation/include/antares/solver/optimisation/opt_structure_probleme_a_resoudre.h new file mode 100644 index 0000000000..7641c23d4e --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/opt_structure_probleme_a_resoudre.h @@ -0,0 +1,114 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_OPTIMISATION_STRUCTURE_PROBLEME_A_RESOUDRE_H__ +#define __SOLVER_OPTIMISATION_STRUCTURE_PROBLEME_A_RESOUDRE_H__ + +#include +#include +#include + +#include + +#include "opt_constants.h" + +/*--------------------------------------------------------------------------------------*/ + +/* Le probleme a resoudre */ +struct PROBLEME_ANTARES_A_RESOUDRE +{ + /* La matrice des contraintes */ + int NombreDeVariables; + int NombreDeContraintes; /* Il est egal a : + ( NombreDePays contraintes de bilan + + NombreDePays contraintes de reserve + + NombreDeContraintesCouplantes + )* NombreDePasDeTempsDUneJournee + + NombreDePays contraintes de turbine */ + std::string Sens; + std::vector IndicesDebutDeLigne; + std::vector NombreDeTermesDesLignes; + std::vector CoefficientsDeLaMatriceDesContraintes; + std::vector IndicesColonnes; + int NombreDeTermesAllouesDansLaMatriceDesContraintes; + int IncrementDAllocationMatriceDesContraintes; + int NombreDeTermesDansLaMatriceDesContraintes; + /* Donnees variables de la matrice des contraintes */ + std::vector CoutQuadratique; + std::vector CoutLineaire; + std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les + suivantes (voir le fichier spx_constantes_externes.h mais ne jamais + utiliser les valeurs explicites des constantes): VARIABLE_FIXE , + VARIABLE_BORNEE_DES_DEUX_COTES , + VARIABLE_BORNEE_INFERIEUREMENT , + VARIABLE_BORNEE_SUPERIEUREMENT , + VARIABLE_NON_BORNEE + */ + std::vector Xmin; + std::vector Xmax; + std::vector SecondMembre; + /* Tableau de pointeur a des doubles. Ce tableau est parallele a X, il permet + de renseigner directement les structures de description du reseau avec les + resultats contenus dans X */ + std::vector AdresseOuPlacerLaValeurDesVariablesOptimisees; + /* Resultat */ + std::vector X; + /* Tableau de pointeur a des doubles. Ce tableau est parallele a CoutsMarginauxDesContraintes, + il permet de renseigner directement les structures de description du reseau avec les + resultats sur les couts marginaux */ + std::vector AdresseOuPlacerLaValeurDesCoutsMarginaux; + std::vector CoutsMarginauxDesContraintes; + /* Tableau de pointeur a des doubles. Ce tableau est parallele a CoutsMarginauxDesContraintes, + il permet de renseigner directement les structures de description du reseau avec les + resultats sur les couts reduits */ + std::vector AdresseOuPlacerLaValeurDesCoutsReduits; + std::vector CoutsReduits; + /* En Entree ou en Sortie */ + int ExistenceDUneSolution; /* En sortie, vaut : + OUI_SPX s'il y a une solution, + NON_SPX s'il n'y a pas de solution admissible + SPX_ERREUR_INTERNE si probleme a l'execution (saturation memoire + par exemple), et dans ce cas il n'y a pas de solution + SPX_MATRICE_DE_BASE_SINGULIERE si on n'a pas pu construire de + matrice de base reguliere, et dans ce cas il n'y a pas de solution + */ + + std::vector ProblemesSpx; + + std::vector + PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + std::vector + ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ + + /* Vecteurs de travail pour contruire la matrice des contraintes lineaires */ + std::vector Pi; + std::vector Colonne; + + /* Nommage des variables & contraintes */ + std::vector NomDesVariables; + std::vector NomDesContraintes; + + std::vector VariablesEntieres; // true = int, false = continuous + + // PIMPL is used to break dependency to OR-Tools' linear_solver.h (big header) + Antares::Optimization::BasisStatus basisStatus; +}; + +#endif /* __SOLVER_OPTIMISATION_STRUCTURE_PROBLEME_A_RESOUDRE_H__ */ diff --git a/src/solver/optimisation/include/antares/solver/optimisation/optim_post_process_list.h b/src/solver/optimisation/include/antares/solver/optimisation/optim_post_process_list.h new file mode 100644 index 0000000000..eecd9edfba --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/optim_post_process_list.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/simulation/base_post_process.h" + +namespace Antares::Solver::Simulation +{ +class OptPostProcessList: public interfacePostProcessList +{ +public: + OptPostProcessList(PROBLEME_HEBDO* problemeHebdo, + uint thread_number, + AreaList& areas, + SheddingPolicy sheddingPolicy, + SimplexOptimization splxOptimization, + Calendar& calendar); + + virtual ~OptPostProcessList() = default; +}; + +} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/include/antares/solver/optimisation/post_process_commands.h b/src/solver/optimisation/include/antares/solver/optimisation/post_process_commands.h new file mode 100644 index 0000000000..652ab48132 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/post_process_commands.h @@ -0,0 +1,138 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/solver/simulation/base_post_process.h" + +namespace Antares::Solver::Simulation +{ +class DispatchableMarginPostProcessCmd: public basePostProcessCommand +{ +public: + DispatchableMarginPostProcessCmd(PROBLEME_HEBDO* problemeHebdo, + unsigned int thread_number, + AreaList& areas); + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + unsigned int thread_number_ = 0; + const AreaList& area_list_; +}; + +class HydroLevelsUpdatePostProcessCmd: public basePostProcessCommand +{ +public: + HydroLevelsUpdatePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + bool remixWasRun, + bool computeAnyway); + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + const AreaList& area_list_; + bool remixWasRun_ = false; + bool computeAnyway_ = false; +}; + +class RemixHydroPostProcessCmd: public basePostProcessCommand +{ +public: + RemixHydroPostProcessCmd(PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + SheddingPolicy sheddingPolicy, + SimplexOptimization simplexOptimization, + unsigned int thread_number); + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + const AreaList& area_list_; + unsigned int thread_number_ = 0; + SheddingPolicy shedding_policy_; + SimplexOptimization splx_optimization_; +}; + +class DTGmarginForAdqPatchPostProcessCmd: public basePostProcessCommand +{ + using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; + +public: + DTGmarginForAdqPatchPostProcessCmd(const AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + unsigned int thread_number); + + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + const AdqPatchParams& adqPatchParams_; + const AreaList& area_list_; + unsigned int thread_number_ = 0; +}; + +class InterpolateWaterValuePostProcessCmd: public basePostProcessCommand +{ +public: + InterpolateWaterValuePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + const Date::Calendar& calendar); + + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + const AreaList& area_list_; + const Date::Calendar& calendar_; +}; + +class HydroLevelsFinalUpdatePostProcessCmd: public basePostProcessCommand +{ +public: + HydroLevelsFinalUpdatePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, AreaList& areas); + + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + const AreaList& area_list_; +}; + +class CurtailmentSharingPostProcessCmd: public basePostProcessCommand +{ + using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; + +public: + CurtailmentSharingPostProcessCmd(const AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + unsigned int thread_number); + + void execute(const optRuntimeData& opt_runtime_data) override; + +private: + double calculateDensNewAndTotalLmrViolation(); + std::vector calculateENSoverAllAreasForEachHour() const; + std::set identifyHoursForCurtailmentSharing(const std::vector& sumENS) const; + std::set getHoursRequiringCurtailmentSharing() const; + + const AreaList& area_list_; + const AdqPatchParams& adqPatchParams_; + unsigned int thread_number_ = 0; +}; + +} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/include/antares/solver/optimisation/weekly_optimization.h b/src/solver/optimisation/include/antares/solver/optimisation/weekly_optimization.h new file mode 100644 index 0000000000..2206d35a25 --- /dev/null +++ b/src/solver/optimisation/include/antares/solver/optimisation/weekly_optimization.h @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "base_weekly_optimization.h" + +namespace Antares::Solver::Optimization +{ +class DefaultWeeklyOptimization: public WeeklyOptimization +{ +public: + explicit DefaultWeeklyOptimization(const OptimizationOptions& options, + PROBLEME_HEBDO* problemeHebdo, + Antares::Data::AdequacyPatch::AdqPatchParams&, + uint numSpace, + IResultWriter& writer, + Simulation::ISimulationObserver& simulationObserver); + ~DefaultWeeklyOptimization() override = default; + void solve() override; +}; +} // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/opt_alloc_probleme_a_optimiser.cpp b/src/solver/optimisation/opt_alloc_probleme_a_optimiser.cpp index 4e9457c5a9..d7e812e32d 100644 --- a/src/solver/optimisation/opt_alloc_probleme_a_optimiser.cpp +++ b/src/solver/optimisation/opt_alloc_probleme_a_optimiser.cpp @@ -1,40 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" - -#include "opt_fonctions.h" -#include - #include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" using namespace Antares; @@ -82,21 +70,26 @@ void OPT_AllocateFromNumberOfVariableConstraints(PROBLEME_ANTARES_A_RESOUDRE* Pr ProblemeAResoudre->Pi.assign(nbVariables, 0.); ProblemeAResoudre->Colonne.assign(nbVariables, 0); + // Names ProblemeAResoudre->NomDesVariables.resize(nbVariables); ProblemeAResoudre->NomDesContraintes.resize(nbConstraints); + // Integer variables ? (MILP) + ProblemeAResoudre->VariablesEntieres.resize(nbVariables); } static void optimisationAllocateProblem(PROBLEME_HEBDO* problemeHebdo, const int mxPaliers) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; int Sparsity = mxPaliers * problemeHebdo->NombreDePays; Sparsity += problemeHebdo->NombreDInterconnexions; if (Sparsity > 100) + { Sparsity = 100; + } int NbTermes = 0; NbTermes += ProblemeAResoudre->NombreDeContraintes; diff --git a/src/solver/optimisation/opt_appel_solveur_lineaire.cpp b/src/solver/optimisation/opt_appel_solveur_lineaire.cpp index 5e9f8f45f8..2dd81809da 100644 --- a/src/solver/optimisation/opt_appel_solveur_lineaire.cpp +++ b/src/solver/optimisation/opt_appel_solveur_lineaire.cpp @@ -1,56 +1,47 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #include -#include "opt_structure_probleme_a_resoudre.h" -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/solver/simulation/simulation.h" +#include "antares/solver/utils/basis_status.h" extern "C" { #include "spx_definition_arguments.h" #include "spx_fonctions.h" - #include "srs_api.h" } -#include -#include - -#include "../utils/mps_utils.h" -#include "../utils/filename.h" - -#include "../infeasible-problem-analysis/problem.h" -#include "../infeasible-problem-analysis/exceptions.h" - #include +#include +#include +#include "antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h" +#include "antares/solver/utils/filename.h" +#include "antares/solver/utils/mps_utils.h" + using namespace operations_research; using namespace Antares; @@ -74,7 +65,7 @@ class TimeMeasurement end_ = clock::now(); } - long long duration_ms() const + long duration_ms() const { return std::chrono::duration_cast(end_ - start_).count(); } @@ -92,30 +83,27 @@ class TimeMeasurement struct SimplexResult { bool success = false; - long long solveTime = 0; + TIME_MEASURE timeMeasure; mpsWriterFactory mps_writer_factory; }; -static SimplexResult OPT_TryToCallSimplex( - const OptimizationOptions& options, - PROBLEME_HEBDO* problemeHebdo, - Optimization::PROBLEME_SIMPLEXE_NOMME& Probleme, - const int NumIntervalle, - const int optimizationNumber, - const OptPeriodStringGenerator& optPeriodStringGenerator, - bool PremierPassage, - IResultWriter& writer - ) +static SimplexResult OPT_TryToCallSimplex(const OptimizationOptions& options, + PROBLEME_HEBDO* problemeHebdo, + Optimization::PROBLEME_SIMPLEXE_NOMME& Probleme, + const int NumIntervalle, + const int optimizationNumber, + const OptPeriodStringGenerator& optPeriodStringGenerator, + bool PremierPassage, + IResultWriter& writer) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - auto ProbSpx - = (PROBLEME_SPX*)(ProblemeAResoudre->ProblemesSpx[(int)NumIntervalle]); + auto ProbSpx = (PROBLEME_SPX*)(ProblemeAResoudre->ProblemesSpx[(int)NumIntervalle]); auto solver = (MPSolver*)(ProblemeAResoudre->ProblemesSpx[(int)NumIntervalle]); const int opt = optimizationNumber - 1; assert(opt >= 0 && opt < 2); OptimizationStatistics& optimizationStatistics = problemeHebdo->optimizationStatistics[opt]; - + TIME_MEASURE timeMeasure; if (!PremierPassage) { ProbSpx = nullptr; @@ -131,7 +119,7 @@ static SimplexResult OPT_TryToCallSimplex( { if (problemeHebdo->ReinitOptimisation) { - if (options.useOrtools && solver != nullptr) + if (options.ortoolsUsed && solver) { ORTOOLS_LibererProbleme(solver); } @@ -151,11 +139,12 @@ static SimplexResult OPT_TryToCallSimplex( Probleme.Contexte = BRANCH_AND_BOUND_OU_CUT_NOEUD; Probleme.BaseDeDepartFournie = UTILISER_LA_BASE_DU_PROBLEME_SPX; - TimeMeasurement measure; - if (options.useOrtools) + TimeMeasurement updateMeasure; + if (options.ortoolsUsed) { - ORTOOLS_ModifierLeVecteurCouts( - solver, ProblemeAResoudre->CoutLineaire.data(), ProblemeAResoudre->NombreDeVariables); + ORTOOLS_ModifierLeVecteurCouts(solver, + ProblemeAResoudre->CoutLineaire.data(), + ProblemeAResoudre->NombreDeVariables); ORTOOLS_ModifierLeVecteurSecondMembre(solver, ProblemeAResoudre->SecondMembre.data(), ProblemeAResoudre->Sens.data(), @@ -168,15 +157,17 @@ static SimplexResult OPT_TryToCallSimplex( } else { - SPX_ModifierLeVecteurCouts( - ProbSpx, ProblemeAResoudre->CoutLineaire.data(), ProblemeAResoudre->NombreDeVariables); + SPX_ModifierLeVecteurCouts(ProbSpx, + ProblemeAResoudre->CoutLineaire.data(), + ProblemeAResoudre->NombreDeVariables); SPX_ModifierLeVecteurSecondMembre(ProbSpx, ProblemeAResoudre->SecondMembre.data(), ProblemeAResoudre->Sens.data(), ProblemeAResoudre->NombreDeContraintes); } - measure.tick(); - optimizationStatistics.addUpdateTime(measure.duration_ms()); + updateMeasure.tick(); + timeMeasure.updateTime = updateMeasure.duration_ms(); + optimizationStatistics.addUpdateTime(timeMeasure.updateTime); } } @@ -194,8 +185,9 @@ static SimplexResult OPT_TryToCallSimplex( Probleme.IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne.data(); Probleme.NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes.data(); Probleme.IndicesColonnes = ProblemeAResoudre->IndicesColonnes.data(); - Probleme.CoefficientsDeLaMatriceDesContraintes - = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes.data(); + Probleme.CoefficientsDeLaMatriceDesContraintes = ProblemeAResoudre + ->CoefficientsDeLaMatriceDesContraintes + .data(); Probleme.Sens = ProblemeAResoudre->Sens.data(); Probleme.SecondMembre = ProblemeAResoudre->SecondMembre.data(); @@ -203,7 +195,7 @@ static SimplexResult OPT_TryToCallSimplex( Probleme.TypeDePricing = PRICING_STEEPEST_EDGE; - Probleme.FaireDuScaling = ( PremierPassage ? OUI_SPX : NON_SPX ); + Probleme.FaireDuScaling = (PremierPassage ? OUI_SPX : NON_SPX); Probleme.StrategieAntiDegenerescence = AGRESSIF; @@ -219,17 +211,11 @@ static SimplexResult OPT_TryToCallSimplex( Probleme.CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes.data(); Probleme.CoutsReduits = ProblemeAResoudre->CoutsReduits.data(); -#ifndef NDEBUG - Probleme.AffichageDesTraces = ( PremierPassage ? OUI_SPX : NON_SPX ); -#else - Probleme.AffichageDesTraces = NON_SPX; -#endif - Probleme.NombreDeContraintesCoupes = 0; - if (options.useOrtools) + if (options.ortoolsUsed) { - solver = ORTOOLS_ConvertIfNeeded(options.solverName, &Probleme, solver); + solver = ORTOOLS_ConvertIfNeeded(options.ortoolsSolver, &Probleme, solver); } const std::string filename = createMPSfilename(optPeriodStringGenerator, optimizationNumber); @@ -237,17 +223,17 @@ static SimplexResult OPT_TryToCallSimplex( problemeHebdo->exportMPSOnError, optimizationNumber, &Probleme, - options.useOrtools, + options.ortoolsUsed, solver); auto mps_writer = mps_writer_factory.create(); mps_writer->runIfNeeded(writer, filename); TimeMeasurement measure; - if (options.useOrtools) + if (options.ortoolsUsed) { const bool keepBasis = (optimizationNumber == PREMIERE_OPTIMISATION); - solver = ORTOOLS_Simplexe(&Probleme, solver, keepBasis); + solver = ORTOOLS_Simplexe(&Probleme, solver, keepBasis, options); if (solver != nullptr) { ProblemeAResoudre->ProblemesSpx[NumIntervalle] = (void*)solver; @@ -262,15 +248,15 @@ static SimplexResult OPT_TryToCallSimplex( } } measure.tick(); - long long solveTime = measure.duration_ms(); - optimizationStatistics.addSolveTime(solveTime); + timeMeasure.solveTime = measure.duration_ms(); + optimizationStatistics.addSolveTime(timeMeasure.solveTime); ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; if (ProblemeAResoudre->ExistenceDUneSolution != OUI_SPX && PremierPassage) { if (ProblemeAResoudre->ExistenceDUneSolution != SPX_ERREUR_INTERNE) { - if (options.useOrtools && solver != nullptr) + if (options.ortoolsUsed && solver) { ORTOOLS_LibererProbleme(solver); } @@ -286,7 +272,9 @@ static SimplexResult OPT_TryToCallSimplex( { logs.info() << " solver: resetting"; } - return {.success=false, .solveTime=solveTime, .mps_writer_factory=mps_writer_factory}; + return {.success = false, + .timeMeasure = timeMeasure, + .mps_writer_factory = mps_writer_factory}; } else @@ -294,7 +282,7 @@ static SimplexResult OPT_TryToCallSimplex( throw FatalError("Internal error: insufficient memory"); } } - return {.success=true, .solveTime=solveTime, .mps_writer_factory=mps_writer_factory}; + return {.success = true, .timeMeasure = timeMeasure, .mps_writer_factory = mps_writer_factory}; } bool OPT_AppelDuSimplexe(const OptimizationOptions& options, @@ -307,25 +295,35 @@ bool OPT_AppelDuSimplexe(const OptimizationOptions& options, const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; Optimization::PROBLEME_SIMPLEXE_NOMME Probleme(ProblemeAResoudre->NomDesVariables, ProblemeAResoudre->NomDesContraintes, - ProblemeAResoudre->StatutDesVariables, - ProblemeAResoudre->StatutDesContraintes, - problemeHebdo->NamedProblems); + ProblemeAResoudre->VariablesEntieres, + ProblemeAResoudre->basisStatus, + problemeHebdo->NamedProblems, + options.solverLogs); bool PremierPassage = true; - struct SimplexResult simplexResult = - OPT_TryToCallSimplex(options, problemeHebdo, Probleme, NumIntervalle, optimizationNumber, - optPeriodStringGenerator, PremierPassage, writer); + SimplexResult simplexResult = OPT_TryToCallSimplex(options, + problemeHebdo, + Probleme, + NumIntervalle, + optimizationNumber, + optPeriodStringGenerator, + PremierPassage, + writer); if (!simplexResult.success) { PremierPassage = false; - simplexResult = OPT_TryToCallSimplex(options, problemeHebdo, Probleme, NumIntervalle, optimizationNumber, - optPeriodStringGenerator, PremierPassage, writer); + simplexResult = OPT_TryToCallSimplex(options, + problemeHebdo, + Probleme, + NumIntervalle, + optimizationNumber, + optPeriodStringGenerator, + PremierPassage, + writer); } - long long solveTime = simplexResult.solveTime; - if (ProblemeAResoudre->ExistenceDUneSolution == OUI_SPX) { if (!PremierPassage) @@ -342,28 +340,39 @@ bool OPT_AppelDuSimplexe(const OptimizationOptions& options, pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[i]; if (pt != nullptr) + { *pt = ProblemeAResoudre->X[i]; + } pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[i]; if (pt != nullptr) + { *pt = ProblemeAResoudre->CoutsReduits[i]; + } } + { + const int opt = optimizationNumber - 1; + assert(opt >= 0 && opt < 2); + problemeHebdo->timeMeasure[opt] = simplexResult.timeMeasure; + } + + // TODO remove this if..else if (optimizationNumber == PREMIERE_OPTIMISATION) { problemeHebdo->coutOptimalSolution1[NumIntervalle] = CoutOpt; - problemeHebdo->tempsResolution1[NumIntervalle] = solveTime; } else { problemeHebdo->coutOptimalSolution2[NumIntervalle] = CoutOpt; - problemeHebdo->tempsResolution2[NumIntervalle] = solveTime; } for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) { pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsMarginaux[Cnt]; if (pt != nullptr) + { *pt = ProblemeAResoudre->CoutsMarginauxDesContraintes[Cnt]; + } } } @@ -375,24 +384,17 @@ bool OPT_AppelDuSimplexe(const OptimizationOptions& options, } Probleme.SetUseNamedProblems(true); - Optimization::InfeasibleProblemAnalysis analysis(options.solverName, &Probleme); - logs.notice() << " Solver: Starting infeasibility analysis..."; - try - { - Optimization::InfeasibleProblemReport report = analysis.produceReport(); - report.prettyPrint(); - } - catch (const Optimization::SlackVariablesEmpty& ex) - { - logs.error() << ex.what(); - } - catch (const Optimization::ProblemResolutionFailed& ex) - { - logs.error() << ex.what(); - } + + auto MPproblem = std::shared_ptr( + ProblemSimplexeNommeConverter(options.ortoolsSolver, &Probleme).Convert()); + + auto analyzer = makeUnfeasiblePbAnalyzer(); + analyzer->run(MPproblem.get()); + analyzer->printReport(); auto mps_writer_on_error = simplexResult.mps_writer_factory.createOnOptimizationError(); - const std::string filename = createMPSfilename(optPeriodStringGenerator, optimizationNumber); + const std::string filename = createMPSfilename(optPeriodStringGenerator, + optimizationNumber); mps_writer_on_error->runIfNeeded(writer, filename); return false; diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index d0a7e2a52c..a491294a06 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -1,35 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "opt_structure_probleme_a_resoudre.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" /* pi_define.h doesn't include this header, yet it uses struct jmp_buf. @@ -78,8 +71,9 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr Probleme.IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne.data(); Probleme.NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes.data(); Probleme.IndicesColonnes = ProblemeAResoudre->IndicesColonnes.data(); - Probleme.CoefficientsDeLaMatriceDesContraintes - = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes.data(); + Probleme.CoefficientsDeLaMatriceDesContraintes = ProblemeAResoudre + ->CoefficientsDeLaMatriceDesContraintes + .data(); Probleme.Sens = ProblemeAResoudre->Sens.data(); Probleme.SecondMembre = ProblemeAResoudre->SecondMembre.data(); @@ -110,7 +104,9 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr { double* pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[i]; if (pt) + { *pt = ProblemeAResoudre->X[i]; + } } return true; @@ -123,7 +119,9 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr { double* pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[i]; if (pt) + { *pt = std::numeric_limits::quiet_NaN(); + } } #ifndef NDEBUG diff --git a/src/solver/optimisation/opt_calcul_des_pmin_MUT_MDT.cpp b/src/solver/optimisation/opt_calcul_des_pmin_MUT_MDT.cpp index 60acd5a8e7..16212e0bfd 100644 --- a/src/solver/optimisation/opt_calcul_des_pmin_MUT_MDT.cpp +++ b/src/solver/optimisation/opt_calcul_des_pmin_MUT_MDT.cpp @@ -1,38 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" constexpr double ZERO_PMIN = 1.e-2; @@ -49,13 +42,17 @@ double OPT_CalculerAireMaxPminJour(int PremierPdt, for (int hour = 0; hour < PremierPdt; hour++) { if (NbGrpCourbeGuide[hour] > NbMx) + { NbMx = NbGrpCourbeGuide[hour]; + } } for (int hour = DernierPdt; hour < NombreDePasDeTemps; hour++) { if (NbGrpCourbeGuide[hour] > NbMx) + { NbMx = NbGrpCourbeGuide[hour]; + } } for (int hour = 0; hour < PremierPdt; hour++) @@ -78,7 +75,9 @@ double OPT_CalculerAireMaxPminJour(int PremierPdt, for (countMUT = 0; countMUT < MUTetMDT && hour < DernierPdt; countMUT++, hour++) { if (NbGrpCourbeGuide[hour] > NbMx) + { NbMx = NbGrpCourbeGuide[hour]; + } } hour -= countMUT; @@ -101,8 +100,7 @@ void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO* problemeH for (uint32_t Pays = 0; Pays < problemeHebdo->NombreDePays; ++Pays) { const RESULTATS_HORAIRES& ResultatsHoraires = problemeHebdo->ResultatsHoraires[Pays]; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[Pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo->PaliersThermiquesDuPays[Pays]; const std::vector& PminDuPalierThermiquePendantUneHeure = PaliersThermiquesDuPays.PminDuPalierThermiquePendantUneHeure; const std::vector& TailleUnitaireDUnGroupeDuPalierThermique @@ -114,15 +112,18 @@ void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO* problemeH for (int Palier = 0; Palier < PaliersThermiquesDuPays.NombreDePaliersThermiques; Palier++) { - PDISP_ET_COUTS_HORAIRES_PAR_PALIER& PuissanceDispoEtCout - = PaliersThermiquesDuPays.PuissanceDisponibleEtCout[Palier]; - std::vector& PuissanceMinDuPalierThermique - = PuissanceDispoEtCout.PuissanceMinDuPalierThermique; + PDISP_ET_COUTS_HORAIRES_PAR_PALIER& PuissanceDispoEtCout = PaliersThermiquesDuPays + .PuissanceDisponibleEtCout + [Palier]; + std::vector& PuissanceMinDuPalierThermique = PuissanceDispoEtCout + .PuissanceMinDuPalierThermique; const std::vector& PuissanceDisponibleDuPalierThermique = PuissanceDispoEtCout.PuissanceDisponibleDuPalierThermique; if (fabs(PminDuPalierThermiquePendantUneHeure[Palier]) < ZERO_PMIN) + { continue; + } for (int Pdt = 0; Pdt < NombreDePasDeTemps; Pdt++) { @@ -130,13 +131,19 @@ void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO* problemeH NbGrpCourbeGuide[Pdt] = 0; if (fabs(P) < ZERO_PMIN) + { continue; + } if (TailleUnitaireDUnGroupeDuPalierThermique[Palier] > ZERO_PMIN) - NbGrpCourbeGuide[Pdt] - = (int)ceil(P / TailleUnitaireDUnGroupeDuPalierThermique[Palier]); + { + NbGrpCourbeGuide[Pdt] = (int)ceil( + P / TailleUnitaireDUnGroupeDuPalierThermique[Palier]); + } else + { NbGrpCourbeGuide[Pdt] = (int)ceil(P); + } } double EcartOpt = LINFINI_ANTARES; @@ -146,17 +153,25 @@ void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO* problemeH int IntervalleDAjustement = MUTetMDT; if (NombreDePasDeTemps - MUTetMDT < IntervalleDAjustement) + { IntervalleDAjustement = NombreDePasDeTemps - MUTetMDT; + } if (IntervalleDAjustement < 0) + { IntervalleDAjustement = 0; + } for (int hour = 0; hour <= IntervalleDAjustement; hour++) { int PremierPdt = hour; int DernierPdt = NombreDePasDeTemps - IntervalleDAjustement + hour; - double Ecart = OPT_CalculerAireMaxPminJour( - PremierPdt, DernierPdt, MUTetMDT, NombreDePasDeTemps, NbGrpCourbeGuide, NbGrpOpt); + double Ecart = OPT_CalculerAireMaxPminJour(PremierPdt, + DernierPdt, + MUTetMDT, + NombreDePasDeTemps, + NbGrpCourbeGuide, + NbGrpOpt); if (Ecart < EcartOpt) { EcartOpt = Ecart; @@ -165,23 +180,34 @@ void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO* problemeH } if (iOpt < 0) + { continue; + } int PremierPdt = iOpt; int DernierPdt = NombreDePasDeTemps - IntervalleDAjustement + iOpt; - OPT_CalculerAireMaxPminJour( - PremierPdt, DernierPdt, MUTetMDT, NombreDePasDeTemps, NbGrpCourbeGuide, NbGrpOpt); + OPT_CalculerAireMaxPminJour(PremierPdt, + DernierPdt, + MUTetMDT, + NombreDePasDeTemps, + NbGrpCourbeGuide, + NbGrpOpt); for (int Pdt = 0; Pdt < NombreDePasDeTemps; Pdt++) { if (PminDuPalierThermiquePendantUneHeure[Palier] * NbGrpOpt[Pdt] > PuissanceMinDuPalierThermique[Pdt]) - PuissanceMinDuPalierThermique[Pdt] - = PminDuPalierThermiquePendantUneHeure[Palier] * NbGrpOpt[Pdt]; + { + PuissanceMinDuPalierThermique[Pdt] = PminDuPalierThermiquePendantUneHeure + [Palier] + * NbGrpOpt[Pdt]; + } if (PuissanceMinDuPalierThermique[Pdt] > PuissanceDisponibleDuPalierThermique[Pdt]) + { PuissanceMinDuPalierThermique[Pdt] = PuissanceDisponibleDuPalierThermique[Pdt]; + } } } } diff --git a/src/solver/optimisation/opt_chainage_intercos.cpp b/src/solver/optimisation/opt_chainage_intercos.cpp index b791caaa9f..8d1f362ffd 100644 --- a/src/solver/optimisation/opt_chainage_intercos.cpp +++ b/src/solver/optimisation/opt_chainage_intercos.cpp @@ -1,34 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" void OPT_ChainagesDesIntercoPartantDUnNoeud(PROBLEME_HEBDO* problemeHebdo) { diff --git a/src/solver/optimisation/opt_constants.h b/src/solver/optimisation/opt_constants.h deleted file mode 100644 index 922805abcd..0000000000 --- a/src/solver/optimisation/opt_constants.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "../simulation/sim_constants.h" - -constexpr char PREMIERE_OPTIMISATION = 1; -constexpr char DEUXIEME_OPTIMISATION = 2; - -constexpr char CONTRAINTE_HORAIRE = 1; -constexpr char CONTRAINTE_JOURNALIERE = 2; -constexpr char CONTRAINTE_HEBDOMADAIRE = 3; - -constexpr char PAS_DE_LISSAGE_HYDRAULIQUE = 0; -constexpr char LISSAGE_HYDRAULIQUE_SUR_SOMME_DES_VARIATIONS = 1; -constexpr char LISSAGE_HYDRAULIQUE_SUR_VARIATION_MAX = 2; - -constexpr char ALTRUISTE = 1; -constexpr char EGOISTE = 2; - -constexpr char ANTARES_SIMPLEXE = 1; -constexpr char ANTARES_PNE = 2; diff --git a/src/solver/optimisation/opt_construction_contraintes_couts_demarrage.cpp b/src/solver/optimisation/opt_construction_contraintes_couts_demarrage.cpp deleted file mode 100644 index 2c0c6f66b6..0000000000 --- a/src/solver/optimisation/opt_construction_contraintes_couts_demarrage.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" - -#include "opt_fonctions.h" -#include "opt_rename_problem.h" -#include "constraints/PMaxDispatchableGeneration.h" -#include "constraints/PMinDispatchableGeneration.h" -#include "constraints/ConsistenceNumberOfDispatchableUnits.h" -#include "constraints/NbUnitsOutageLessThanNbUnitsStop.h" -#include "constraints/NbDispUnitsMinBoundSinceMinUpTime.h" -#include "constraints/MinDownTime.h" - -using namespace Antares::Data; - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaireCoutsDeDemarrage( - PROBLEME_HEBDO* problemeHebdo, - bool Simulation) -{ - const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - - int nombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; - - ConstraintNamer constraintNamer(ProblemeAResoudre->NomDesContraintes); - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - constraintNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) - { - PMaxDispatchableGeneration pMaxDispatchableGeneration(problemeHebdo); - PMinDispatchableGeneration pMinDispatchableGeneration(problemeHebdo); - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - pMaxDispatchableGeneration.add(pays, palier, index, pdt, Simulation); - pMinDispatchableGeneration.add(pays, palier, index, pdt, Simulation); - } - } - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - constraintNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) - { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - ConsistenceNumberOfDispatchableUnits consistenceNumberOfDispatchableUnits( - problemeHebdo); - consistenceNumberOfDispatchableUnits.add(pays, palier, index, pdt, Simulation); - } - } - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - NbUnitsOutageLessThanNbUnitsStop nbUnitsOutageLessThanNbUnitsStop(problemeHebdo); - - constraintNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) - { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - nbUnitsOutageLessThanNbUnitsStop.add(pays, palier, index, pdt, Simulation); - } - } - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - NbDispUnitsMinBoundSinceMinUpTime nbDispUnitsMinBoundSinceMinUpTime(problemeHebdo); - constraintNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) - { - if (PaliersThermiquesDuPays.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[index] <= 0) - continue; - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - nbDispUnitsMinBoundSinceMinUpTime.add(pays, palier, index, pdt, Simulation); - } - } - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; - MinDownTime minDownTime(problemeHebdo); - for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) - { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - minDownTime.add(pays, palier, index, pdt, Simulation); - } - } - } - - return; -} diff --git a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_lineaire.cpp b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_lineaire.cpp deleted file mode 100644 index 3dd43259a4..0000000000 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_lineaire.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#include "opt_structure_probleme_a_resoudre.h" -#include "opt_export_structure.h" -#include "../utils/filename.h" -#include "opt_fonctions.h" -#include "opt_rename_problem.h" -#include "sim_structure_probleme_economique.h" -#include "constraints/AreaBalance.h" -#include "constraints/FictitiousLoad.h" -#include "constraints/ShortTermStorageLevel.h" -#include "constraints/FlowDissociation.h" -#include "constraints/BindingConstraintHour.h" -#include "constraints/BindingConstraintDay.h" -#include "constraints/BindingConstraintWeek.h" -#include "constraints/HydroPower.h" -#include "constraints/HydroPowerSmoothingUsingVariationSum.h" -#include "constraints/HydroPowerSmoothingUsingVariationMaxDown.h" -#include "constraints/HydroPowerSmoothingUsingVariationMaxUp.h" -#include "constraints/MinHydroPower.h" -#include "constraints/MaxHydroPower.h" -#include "constraints/MaxPumping.h" -#include "constraints/AreaHydroLevel.h" -#include "constraints/FinalStockEquivalent.h" -#include "constraints/FinalStockExpression.h" - -#include - -using namespace Antares::Data; - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaire(PROBLEME_HEBDO* problemeHebdo, Solver::IResultWriter& writer) -{ - const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - - int nombreDePasDeTempsDUneJournee = problemeHebdo->NombreDePasDeTempsDUneJournee; - int nombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; - - ProblemeAResoudre->NombreDeContraintes = 0; - ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - ConstraintNamer constraintNamer(ProblemeAResoudre->NomDesContraintes); - - AreaBalance areaBalance(problemeHebdo); - FictitiousLoad fictitiousLoad(problemeHebdo); - ShortTermStorageLevel shortTermStorageLevel(problemeHebdo); - FlowDissociation flowDissociation(problemeHebdo); - BindingConstraintHour bindingConstraintHour(problemeHebdo); - BindingConstraintDay bindingConstraintDay(problemeHebdo); - BindingConstraintWeek bindingConstraintWeek(problemeHebdo); - HydroPower hydroPower(problemeHebdo); - HydroPowerSmoothingUsingVariationSum hydroPowerSmoothingUsingVariationSum(problemeHebdo); - HydroPowerSmoothingUsingVariationMaxDown hydroPowerSmoothingUsingVariationMaxDown( - problemeHebdo); - HydroPowerSmoothingUsingVariationMaxUp hydroPowerSmoothingUsingVariationMaxUp(problemeHebdo); - - MinHydroPower minHydroPower(problemeHebdo); - MaxHydroPower maxHydroPower(problemeHebdo); - - MaxPumping maxPumping(problemeHebdo); - - AreaHydroLevel areaHydroLevel(problemeHebdo); - - FinalStockEquivalent finalStockEquivalent(problemeHebdo); - FinalStockExpression finalStockExpression(problemeHebdo); - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - int timeStepInYear = problemeHebdo->weekInTheYear * 168 + pdt; - constraintNamer.UpdateTimeStep(timeStepInYear); - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - areaBalance.add(pdt, pays); - - fictitiousLoad.add(pdt, pays); - - shortTermStorageLevel.add(pdt, pays); - } - - for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) - { - flowDissociation.add(pdt, interco); - } - for (uint32_t cntCouplante = 0; cntCouplante < problemeHebdo->NombreDeContraintesCouplantes; - cntCouplante++) - { - bindingConstraintHour.add(pdt, cntCouplante); - } - } - - for (uint32_t cntCouplante = 0; cntCouplante < problemeHebdo->NombreDeContraintesCouplantes; - cntCouplante++) - { - bindingConstraintDay.add(cntCouplante); - } - - if (nombreDePasDeTempsPourUneOptimisation > nombreDePasDeTempsDUneJournee) - { - for (uint32_t cntCouplante = 0; cntCouplante < problemeHebdo->NombreDeContraintesCouplantes; - cntCouplante++) - { - bindingConstraintWeek.add(cntCouplante); - } - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - hydroPower.add(pays); - } - - if (problemeHebdo->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_SOMME_DES_VARIATIONS) - { - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) - continue; - - hydroPowerSmoothingUsingVariationSum.add(pays); - } - } - else if (problemeHebdo->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_VARIATION_MAX) - { - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) - continue; - - constraintNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - hydroPowerSmoothingUsingVariationMaxDown.add(pays, pdt); - hydroPowerSmoothingUsingVariationMaxUp.add(pays, pdt); - } - } - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - minHydroPower.add(pays); - - maxHydroPower.add(pays); - } - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - maxPumping.add(pays); - } - - for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) - { - int timeStepInYear = problemeHebdo->weekInTheYear * 168 + pdt; - constraintNamer.UpdateTimeStep(timeStepInYear); - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - areaHydroLevel.add(pays, pdt); - } - } - - /* For each area with ad hoc properties, two possible sets of two additional constraints */ - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) - { - finalStockEquivalent.add(pays); - - finalStockExpression.add(pays); - } - - if (problemeHebdo->OptimisationAvecCoutsDeDemarrage) - { - OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaireCoutsDeDemarrage(problemeHebdo, - false); - } - - // Export structure - if (problemeHebdo->ExportStructure && problemeHebdo->firstWeekOfSimulation) - { - OPT_ExportInterco(writer, problemeHebdo); - OPT_ExportAreaName(writer, problemeHebdo->NomsDesPays); - } - - return; -} diff --git a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp deleted file mode 100644 index b3d7399045..0000000000 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" -#include "opt_fonctions.h" - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* problemeHebdo) -{ - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = problemeHebdo->ProblemeAResoudre.get(); - - std::vector Pi(ProblemeAResoudre->NombreDeVariables, 0.); - std::vector Colonne(ProblemeAResoudre->NombreDeVariables, 0); - - ProblemeAResoudre->NombreDeContraintes = 0; - ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - const CORRESPONDANCES_DES_VARIABLES& correspondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[0]; - - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays - 1; pays++) - { - int nombreDeTermes = 0; - - int interco = problemeHebdo->IndexDebutIntercoOrigine[pays]; - while (interco >= 0) - { - if (int var - = correspondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco]; - var >= 0) - { - Pi[nombreDeTermes] = 1.0; - Colonne[nombreDeTermes] = var; - nombreDeTermes++; - } - interco = problemeHebdo->IndexSuivantIntercoOrigine[interco]; - } - interco = problemeHebdo->IndexDebutIntercoExtremite[pays]; - while (interco >= 0) - { - if (int var - = correspondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco]; - var >= 0) - { - Pi[nombreDeTermes] = -1.0; - Colonne[nombreDeTermes] = var; - nombreDeTermes++; - } - interco = problemeHebdo->IndexSuivantIntercoExtremite[interco]; - } - - problemeHebdo->NumeroDeContrainteDeSoldeDEchange[pays] - = ProblemeAResoudre->NombreDeContraintes; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, nombreDeTermes, '='); - } -} diff --git a/src/solver/optimisation/opt_construction_matrice_des_contraintes_outils.cpp b/src/solver/optimisation/opt_construction_matrice_des_contraintes_outils.cpp deleted file mode 100644 index ecbb26cdf5..0000000000 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_outils.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/sim_structure_donnees.h" - -#include "opt_fonctions.h" - -void OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - std::vector& Pi, - std::vector& Colonne, - int NombreDeTermesDeLaContrainte, - char SensContrainte) -{ - int& nombreDeTermes = ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes; - int& nombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; - - ProblemeAResoudre->IndicesDebutDeLigne[nombreDeContraintes] = nombreDeTermes; - for (int i = 0; i < NombreDeTermesDeLaContrainte; i++) - { - ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[nombreDeTermes] = Pi[i]; - ProblemeAResoudre->IndicesColonnes[nombreDeTermes] = Colonne[i]; - nombreDeTermes++; - if (nombreDeTermes == ProblemeAResoudre->NombreDeTermesAllouesDansLaMatriceDesContraintes) - { - OPT_AugmenterLaTailleDeLaMatriceDesContraintes(ProblemeAResoudre); - } - } - ProblemeAResoudre->NombreDeTermesDesLignes[nombreDeContraintes] = NombreDeTermesDeLaContrainte; - - ProblemeAResoudre->Sens[nombreDeContraintes] = SensContrainte; - nombreDeContraintes++; - - return; -} diff --git a/src/solver/optimisation/opt_construction_variables_couts_demarrages.cpp b/src/solver/optimisation/opt_construction_variables_couts_demarrages.cpp index b7b1658fec..98a259540d 100644 --- a/src/solver/optimisation/opt_construction_variables_couts_demarrages.cpp +++ b/src/solver/optimisation/opt_construction_variables_couts_demarrages.cpp @@ -1,38 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" -#include "opt_rename_problem.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_rename_problem.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" #include "spx_constantes_externes.h" +#include "variables/VariableManagerUtils.h" void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaireCoutsDeDemarrage( PROBLEME_HEBDO* problemeHebdo, @@ -40,20 +33,23 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaireCoutsDeDemarra { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - int nombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int nombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; int nombreDeVariables = ProblemeAResoudre->NombreDeVariables; VariableNamer variableNamer(ProblemeAResoudre->NomDesVariables); + const bool intVariables = problemeHebdo->OptimisationAvecVariablesEntieres; for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { variableNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); - const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; const auto& clusterName = PaliersThermiquesDuPays.NomsDesPaliersThermiques[index]; + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int pdt = 0; pdt < nombreDePasDeTempsPourUneOptimisation; pdt++) { @@ -63,46 +59,40 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaireCoutsDeDemarra nombreDeVariables += 4; continue; } - CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdt]; - CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesEnMarcheDuPalierThermique[palier] - = nombreDeVariables; + variableManager.NumberOfDispatchableUnits(palier, pdt) = nombreDeVariables; ProblemeAResoudre->TypeDeVariable[nombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + + ProblemeAResoudre->VariablesEntieres[nombreDeVariables] = intVariables; variableNamer.NODU(nombreDeVariables, clusterName); nombreDeVariables++; - CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiDemarrentDuPalierThermique[palier] - = nombreDeVariables; + variableManager.NumberStartingDispatchableUnits(palier, pdt) = nombreDeVariables; ProblemeAResoudre->TypeDeVariable[nombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->VariablesEntieres[nombreDeVariables] = intVariables; variableNamer.NumberStartingDispatchableUnits(nombreDeVariables, clusterName); nombreDeVariables++; - CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiSArretentDuPalierThermique[palier] - = nombreDeVariables; + variableManager.NumberStoppingDispatchableUnits(palier, pdt) = nombreDeVariables; ProblemeAResoudre->TypeDeVariable[nombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->VariablesEntieres[nombreDeVariables] = intVariables; variableNamer.NumberStoppingDispatchableUnits(nombreDeVariables, clusterName); nombreDeVariables++; - CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiTombentEnPanneDuPalierThermique[palier] + variableManager.NumberBreakingDownDispatchableUnits(palier, pdt) = nombreDeVariables; ProblemeAResoudre->TypeDeVariable[nombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + + ProblemeAResoudre->VariablesEntieres[nombreDeVariables] = intVariables; variableNamer.NumberBreakingDownDispatchableUnits(nombreDeVariables, clusterName); nombreDeVariables++; } } } - ProblemeAResoudre->NombreDeVariables = nombreDeVariables; - - return; } diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_lineaire.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_lineaire.cpp index c33a5300b8..40736b5428 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_lineaire.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_lineaire.cpp @@ -1,76 +1,66 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#include "opt_structure_probleme_a_resoudre.h" -#include "../simulation/sim_extern_variables_globales.h" -#include "opt_fonctions.h" -#include "opt_rename_problem.h" - -#include "spx_constantes_externes.h" + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#include + +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_rename_problem.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" + +#include "variables/VariableManagerUtils.h" void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBDO* problemeHebdo) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; int NombreDeVariables = 0; VariableNamer variableNamer(ProblemeAResoudre->NomDesVariables); + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int pdt = 0; pdt < NombreDePasDeTempsPourUneOptimisation; pdt++) { variableNamer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 + pdt); - auto& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdt]; for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { - CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco] - = NombreDeVariables; + variableManager.NTCDirect(interco, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - const auto origin - = problemeHebdo->NomsDesPays[problemeHebdo->PaysOrigineDeLInterconnexion[interco]]; - const auto destination - = problemeHebdo->NomsDesPays[problemeHebdo->PaysExtremiteDeLInterconnexion[interco]]; + const auto origin = problemeHebdo->NomsDesPays + [problemeHebdo->PaysOrigineDeLInterconnexion[interco]]; + const auto destination = problemeHebdo->NomsDesPays + [problemeHebdo->PaysExtremiteDeLInterconnexion[interco]]; variableNamer.NTCDirect(NombreDeVariables, origin, destination); NombreDeVariables++; if (problemeHebdo->CoutDeTransport[interco].IntercoGereeAvecDesCouts) { - CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[interco] - = NombreDeVariables; + variableManager.IntercoDirectCost(interco, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.IntercoDirectCost(NombreDeVariables, origin, destination); NombreDeVariables++; - CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[interco] - = NombreDeVariables; + variableManager.IntercoIndirectCost(interco, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.IntercoIndirectCost(NombreDeVariables, origin, destination); @@ -80,57 +70,53 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; variableNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; const auto& clusterName = PaliersThermiquesDuPays.NomsDesPaliersThermiques[index]; - CorrespondanceVarNativesVarOptim.NumeroDeVariableDuPalierThermique[palier] - = NombreDeVariables; + variableManager.DispatchableProduction(palier, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.DispatchableProduction(NombreDeVariables, clusterName); NombreDeVariables++; } - for (const auto& storage : problemeHebdo->ShortTermStorage[pays]) + for (const auto& storage: problemeHebdo->ShortTermStorage[pays]) { const int clusterGlobalIndex = storage.clusterGlobalIndex; // 1. Injection - CorrespondanceVarNativesVarOptim.SIM_ShortTermStorage.InjectionVariable[clusterGlobalIndex] + variableManager.ShortTermStorageInjection(clusterGlobalIndex, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.ShortTermStorageInjection(NombreDeVariables, storage.name); NombreDeVariables++; // 2. Withdrawal - CorrespondanceVarNativesVarOptim.SIM_ShortTermStorage.WithdrawalVariable[clusterGlobalIndex] + variableManager.ShortTermStorageWithdrawal(clusterGlobalIndex, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.ShortTermStorageWithdrawal(NombreDeVariables, storage.name); NombreDeVariables++; // 3. Level - CorrespondanceVarNativesVarOptim.SIM_ShortTermStorage.LevelVariable[clusterGlobalIndex] - = NombreDeVariables; + variableManager.ShortTermStorageLevel(clusterGlobalIndex, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.ShortTermStorageLevel(NombreDeVariables, storage.name); NombreDeVariables++; } - CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[pays] - = NombreDeVariables; + variableManager.PositiveUnsuppliedEnergy(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.PositiveUnsuppliedEnergy(NombreDeVariables); NombreDeVariables++; - CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillanceNegative[pays] - = NombreDeVariables; + variableManager.NegativeUnsuppliedEnergy(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; variableNamer.NegativeUnsuppliedEnergy(NombreDeVariables); @@ -142,31 +128,29 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD variableNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); if (problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) { - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeLaProdHyd[pays] - = NombreDeVariables; + variableManager.HydProd(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.HydProd(NombreDeVariables); NombreDeVariables++; } else - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeLaProdHyd[pays] = -1; - - CorrespondanceVarNativesVarOptim.NumeroDeVariablesVariationHydALaBaisse[pays] = -1; - CorrespondanceVarNativesVarOptim.NumeroDeVariablesVariationHydALaHausse[pays] = -1; + { + variableManager.HydProd(pays, pdt) = -1; + } + variableManager.HydProdDown(pays, pdt) = -1; + variableManager.HydProdUp(pays, pdt) = -1; if (problemeHebdo->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_SOMME_DES_VARIATIONS) { if (problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) { - CorrespondanceVarNativesVarOptim.NumeroDeVariablesVariationHydALaBaisse[pays] - = NombreDeVariables; + variableManager.HydProdDown(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; variableNamer.HydProdDown(NombreDeVariables); NombreDeVariables++; - CorrespondanceVarNativesVarOptim.NumeroDeVariablesVariationHydALaHausse[pays] - = NombreDeVariables; + variableManager.HydProdUp(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; variableNamer.HydProdUp(NombreDeVariables); @@ -179,15 +163,13 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD .PresenceDHydrauliqueModulable && pdt == 0) { - CorrespondanceVarNativesVarOptim.NumeroDeVariablesVariationHydALaBaisse[pays] - = NombreDeVariables; + variableManager.HydProdDown(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.HydProdDown(NombreDeVariables); NombreDeVariables++; - CorrespondanceVarNativesVarOptim.NumeroDeVariablesVariationHydALaHausse[pays] - = NombreDeVariables; + variableManager.HydProdUp(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; @@ -197,26 +179,25 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD if (problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable) { - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDePompage[pays] - = NombreDeVariables; + variableManager.Pumping(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.Pumping(NombreDeVariables); NombreDeVariables++; } else - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDePompage[pays] = -1; + { + variableManager.Pumping(pays, pdt) = -1; + } if (problemeHebdo->CaracteristiquesHydrauliques[pays].SuiviNiveauHoraire) { - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeNiveau[pays] - = NombreDeVariables; + variableManager.HydroLevel(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.HydroLevel(NombreDeVariables); NombreDeVariables++; - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeDebordement[pays] - = NombreDeVariables; + variableManager.Overflow(pays, pdt) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.Overflow(NombreDeVariables); @@ -224,8 +205,8 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD } else { - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeNiveau[pays] = -1; - CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeDebordement[pays] = -1; + variableManager.HydroLevel(pays, pdt) = -1; + variableManager.Overflow(pays, pdt) = -1; } } } @@ -233,18 +214,18 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { variableNamer.UpdateTimeStep(problemeHebdo->weekInTheYear * 168 - + NombreDePasDeTempsPourUneOptimisation - 1); + + NombreDePasDeTempsPourUneOptimisation - 1); variableNamer.UpdateArea(problemeHebdo->NomsDesPays[pays]); if (problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) { - problemeHebdo->NumeroDeVariableStockFinal[pays] = NombreDeVariables; + variableManager.FinalStorage(pays) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_NON_BORNEE; variableNamer.FinalStorage(NombreDeVariables); NombreDeVariables++; for (uint nblayer = 0; nblayer < 100; nblayer++) { - problemeHebdo->NumeroDeVariableDeTrancheDeStock[pays][nblayer] = NombreDeVariables; + variableManager.LayerStorage(pays, nblayer) = NombreDeVariables; ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; variableNamer.LayerStorage(NombreDeVariables, nblayer); @@ -253,10 +234,10 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBD } else { - problemeHebdo->NumeroDeVariableStockFinal[pays] = -1; + variableManager.FinalStorage(pays) = -1; for (uint nblayer = 0; nblayer < 100; nblayer++) { - problemeHebdo->NumeroDeVariableDeTrancheDeStock[pays][nblayer] = -1; + variableManager.LayerStorage(pays, nblayer) = -1; } } } diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 793a871db6..10018bf29d 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -1,54 +1,44 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" #include "pi_constantes_externes.h" +#include "variables/VariableManagerUtils.h" void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_HEBDO* problemeHebdo) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); + assert(ProblemeAResoudre); int nombreDeVariables = 0; - - CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[0]; + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { - CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco] - = nombreDeVariables; + variableManager.NTCDirect(interco, 0) = nombreDeVariables; ProblemeAResoudre->TypeDeVariable[nombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; nombreDeVariables++; } diff --git a/src/solver/optimisation/opt_decompte_variables_et_contraintes.cpp b/src/solver/optimisation/opt_decompte_variables_et_contraintes.cpp index 17738e7b1d..1f773bb9ea 100644 --- a/src/solver/optimisation/opt_decompte_variables_et_contraintes.cpp +++ b/src/solver/optimisation/opt_decompte_variables_et_contraintes.cpp @@ -1,47 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" - + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include #include -#include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" using namespace Antares; int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* problemeHebdo) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - int nombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int nombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; int mxPaliers = 0; ProblemeAResoudre->NombreDeVariables = problemeHebdo->NombreDInterconnexions; @@ -50,8 +41,8 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - ProblemeAResoudre->NombreDeVariables - += problemeHebdo->PaliersThermiquesDuPays[pays].NombreDePaliersThermiques; + ProblemeAResoudre->NombreDeVariables += problemeHebdo->PaliersThermiquesDuPays[pays] + .NombreDePaliersThermiques; mxPaliers += problemeHebdo->PaliersThermiquesDuPays[pays].NombreDePaliersThermiques; @@ -104,11 +95,13 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* int nombreDeJoursDansUnIntervalleOptimise; if (nombreDePasDeTempsPourUneOptimisation > problemeHebdo->NombreDePasDeTempsDUneJournee) { - nombreDeJoursDansUnIntervalleOptimise - = problemeHebdo->NombreDePasDeTemps / problemeHebdo->NombreDePasDeTempsDUneJournee; + nombreDeJoursDansUnIntervalleOptimise = problemeHebdo->NombreDePasDeTemps + / problemeHebdo->NombreDePasDeTempsDUneJournee; } else + { nombreDeJoursDansUnIntervalleOptimise = 1; + } for (uint32_t cntCouplante = 0; cntCouplante < problemeHebdo->NombreDeContraintesCouplantes; cntCouplante++) @@ -137,10 +130,10 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { char Pump = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable; - char TurbEntreBornes - = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; - char MonitorHourlyLev - = problemeHebdo->CaracteristiquesHydrauliques[pays].SuiviNiveauHoraire; + char TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays] + .TurbinageEntreBornes; + char MonitorHourlyLev = problemeHebdo->CaracteristiquesHydrauliques[pays] + .SuiviNiveauHoraire; if (!Pump && !TurbEntreBornes && !MonitorHourlyLev && problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) @@ -150,9 +143,9 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* if (Pump && !TurbEntreBornes && !MonitorHourlyLev) { - ProblemeAResoudre->NombreDeContraintes - += 2; /* 2 constraints bounding the overall energy generated over the period (10a in - the reference document) */ + ProblemeAResoudre->NombreDeContraintes += 2; /* 2 constraints bounding the overall + energy generated over the period (10a in + the reference document) */ ProblemeAResoudre ->NombreDeContraintes++; /* 1 constraint setting the level variation over the period (10b in the reference document) */ @@ -198,9 +191,9 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* } if (Pump && !TurbEntreBornes && MonitorHourlyLev) { - ProblemeAResoudre->NombreDeContraintes - += 2; /* 2 constraints bounding the overall energy generated over the period (10a in - the reference document) */ + ProblemeAResoudre->NombreDeContraintes += 2; /* 2 constraints bounding the overall + energy generated over the period (10a in + the reference document) */ ProblemeAResoudre ->NombreDeContraintes++; /* 1 constraint setting the level variation over the period (10b in the reference document) */ @@ -215,7 +208,8 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* if (!Pump && !TurbEntreBornes && MonitorHourlyLev) { const std::string areaName(problemeHebdo->NomsDesPays[pays]); - throw FatalError("Level explicit modeling requires flexible generation in area " + areaName); + throw FatalError("Level explicit modeling requires flexible generation in area " + + areaName); } } @@ -252,8 +246,8 @@ int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO* { if (problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) { - ProblemeAResoudre->NombreDeContraintes - += 2; /* Final Stock Level : (1 equivalence cnt + 1 expression cnt )*/ + ProblemeAResoudre->NombreDeContraintes += 2; /* Final Stock Level : (1 equivalence cnt + + 1 expression cnt )*/ } } diff --git a/src/solver/optimisation/opt_decompte_variables_et_contraintes_couts_demarrage.cpp b/src/solver/optimisation/opt_decompte_variables_et_contraintes_couts_demarrage.cpp index d7cae91d60..ed4216b8a3 100644 --- a/src/solver/optimisation/opt_decompte_variables_et_contraintes_couts_demarrage.cpp +++ b/src/solver/optimisation/opt_decompte_variables_et_contraintes_couts_demarrage.cpp @@ -1,41 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/LinearProblemMatrixStartUpCosts.h" +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" void OPT_DecompteDesVariablesEtDesContraintesCoutsDeDemarrage(PROBLEME_HEBDO* problemeHebdo) { if (!problemeHebdo->OptimisationAvecCoutsDeDemarrage) + { return; + } - OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaireCoutsDeDemarrage(problemeHebdo, true); + auto builder_data = NewGetConstraintBuilderFromProblemHebdo(problemeHebdo); + ConstraintBuilder builder(builder_data); + LinearProblemMatrixStartUpCosts(problemeHebdo, true, builder).Run(); OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaireCoutsDeDemarrage(problemeHebdo, true); diff --git a/src/solver/optimisation/opt_export_structure.cpp b/src/solver/optimisation/opt_export_structure.cpp index 807ce209f6..78f39cca47 100644 --- a/src/solver/optimisation/opt_export_structure.cpp +++ b/src/solver/optimisation/opt_export_structure.cpp @@ -1,41 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/optimisation/opt_export_structure.h" + #include -#include "../simulation/sim_structure_probleme_economique.h" -#include "opt_export_structure.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" //////////////////////////////////////////////////////////////////// // Export de la structure des LPs //////////////////////////////////////////////////////////////////// -void OPT_ExportInterco(Antares::Solver::IResultWriter& writer, - PROBLEME_HEBDO* problemeHebdo) +void OPT_ExportInterco(Antares::Solver::IResultWriter& writer, PROBLEME_HEBDO* problemeHebdo) { Yuni::Clob Flot; for (uint32_t i(0); i < problemeHebdo->NombreDInterconnexions; ++i) @@ -62,3 +56,9 @@ void OPT_ExportAreaName(Antares::Solver::IResultWriter& writer, } writer.addEntryFromBuffer(filename, Flot); } + +void OPT_ExportStructures(PROBLEME_HEBDO* problemeHebdo, Antares::Solver::IResultWriter& writer) +{ + OPT_ExportInterco(writer, problemeHebdo); + OPT_ExportAreaName(writer, problemeHebdo->NomsDesPays); +} diff --git a/src/solver/optimisation/opt_export_structure.h b/src/solver/optimisation/opt_export_structure.h deleted file mode 100644 index ef5fbca36b..0000000000 --- a/src/solver/optimisation/opt_export_structure.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __EXPORT_STRUCTURE__ -#define __EXPORT_STRUCTURE__ - -#include -#include -#include - -#include - -#include -#include "antares/writer/i_writer.h" -#include - -namespace Antares -{ -namespace Data -{ - -class Study; -} // namespace Data -} // namespace Antares - -struct PROBLEME_HEBDO; - -void OPT_ExportInterco(Antares::Solver::IResultWriter& writer, - PROBLEME_HEBDO* problemeHebdo); -void OPT_ExportAreaName(Antares::Solver::IResultWriter& writer, - const std::vector& areaNames); - -#endif diff --git a/src/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/opt_fonctions.h deleted file mode 100644 index e2807f0c8d..0000000000 --- a/src/solver/optimisation/opt_fonctions.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_OPTIMISATION_FUNCTIONS_H__ -#define __SOLVER_OPTIMISATION_FUNCTIONS_H__ - -#include "../config.h" -#include "opt_structure_probleme_a_resoudre.h" -#include "adequacy_patch_csr/hourly_csr_problem.h" -#include "opt_period_string_generator_base.h" -#include "antares/study/parameters/adq-patch-params.h" -#include "opt_structure_probleme_a_resoudre.h" -#include - -using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; -using OptimizationOptions = Antares::Solver::Optimization::OptimizationOptions; - -void OPT_OptimisationHebdomadaire(const OptimizationOptions& options, - PROBLEME_HEBDO*, - const AdqPatchParams&, - Antares::Solver::IResultWriter& writer); -void OPT_NumeroDeJourDuPasDeTemps(PROBLEME_HEBDO*); -void OPT_NumeroDIntervalleOptimiseDuPasDeTemps(PROBLEME_HEBDO*); -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBDO*); -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_HEBDO*); -void OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaire(PROBLEME_HEBDO*, - Antares::Solver::IResultWriter& writer); -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO*); -void OPT_InitialiserLesPminHebdo(PROBLEME_HEBDO*); -void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise(PROBLEME_HEBDO*); -void OPT_MaxDesPmaxHydrauliques(PROBLEME_HEBDO*); -void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO*, - const AdqPatchParams&, - const int, - const int, - const int); -void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO*, int); -void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO*, int, int, int, const int); -void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO*, int); -void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO*, const int, const int); -void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO*, int); -void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); -bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); - -using namespace Antares::Data::AdequacyPatch; -bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE&, - HourlyCSRProblem&, - const AdqPatchParams&, - uint week, - int year); - -bool OPT_PilotageOptimisationLineaire(const OptimizationOptions& options, - PROBLEME_HEBDO*, - const AdqPatchParams&, - Antares::Solver::IResultWriter& writer); -void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); -bool OPT_PilotageOptimisationQuadratique(PROBLEME_HEBDO*); - -/*! -** \brief Appel du solver -** -** \return True si l'operation s'est bien deroulee, false si le probleme n'a pas de solution -*/ -bool OPT_AppelDuSimplexe(const OptimizationOptions& options, - PROBLEME_HEBDO*, - int, - const int, - const OptPeriodStringGenerator&, - Antares::Solver::IResultWriter& writer); -void OPT_LiberationProblemesSimplexe(const OptimizationOptions& options, const PROBLEME_HEBDO*); - -bool OPT_OptimisationLineaire(const OptimizationOptions& options, - PROBLEME_HEBDO*, - const AdqPatchParams&, - Antares::Solver::IResultWriter& writer); -void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO*); -/*------------------------------*/ - -void OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(PROBLEME_HEBDO*); -double OPT_CalculerAireMaxPminJour(int, int, int, int, std::vector&, std::vector&); - -void OPT_ChargerLaContrainteDansLaMatriceDesContraintes(PROBLEME_ANTARES_A_RESOUDRE*, - std::vector&, - std::vector&, - int, - char); -void OPT_ChainagesDesIntercoPartantDUnNoeud(PROBLEME_HEBDO*); - -void OPT_AllocateFromNumberOfVariableConstraints(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - int); -void OPT_FreeOptimizationData(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre); -void OPT_AllocDuProblemeAOptimiser(PROBLEME_HEBDO*); -int OPT_DecompteDesVariablesEtDesContraintesDuProblemeAOptimiser(PROBLEME_HEBDO*); -void OPT_AugmenterLaTailleDeLaMatriceDesContraintes(PROBLEME_ANTARES_A_RESOUDRE*); - -/*------------------------------*/ - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, bool); -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, - bool); -void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, - const int, - const int); -void OPT_InitialiserLesCoutsLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, const int, const int); -void OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HEBDO*, int, int); -void OPT_DecompteDesVariablesEtDesContraintesCoutsDeDemarrage(PROBLEME_HEBDO*); -void OPT_InitialiserNombreMinEtMaxDeGroupesCoutsDeDemarrage(PROBLEME_HEBDO*); -void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO*); -double OPT_SommeDesPminThermiques(const PROBLEME_HEBDO*, int, uint); - -#endif /* __SOLVER_OPTIMISATION_FUNCTIONS_H__ */ diff --git a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp index b45190106c..398af7b814 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -1,41 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" +#include -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include "../simulation/adequacy_patch_runtime_data.h" - -#include "opt_fonctions.h" -#include "adequacy_patch_local_matching/adq_patch_local_matching.h" -#include +#include "antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" #include "spx_constantes_externes.h" +#include "variables/VariableManagement.h" +#include "variables/VariableManagerUtils.h" using namespace Antares; using namespace Antares::Data; @@ -48,14 +42,18 @@ void OPT_MaxDesPmaxHydrauliques(PROBLEME_HEBDO* problemeHebdo) { problemeHebdo->CaracteristiquesHydrauliques[pays].MaxDesPmaxHydrauliques = 0.0; if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) + { continue; + } const std::vector& ContrainteDePmaxHydrauliqueHoraire = problemeHebdo->CaracteristiquesHydrauliques[pays].ContrainteDePmaxHydrauliqueHoraire; double pmaxHyd = -1; for (uint pdtHebdo = 0; pdtHebdo < problemeHebdo->NombreDePasDeTemps; pdtHebdo++) { if (ContrainteDePmaxHydrauliqueHoraire[pdtHebdo] > pmaxHyd) + { pmaxHyd = ContrainteDePmaxHydrauliqueHoraire[pdtHebdo]; + } } problemeHebdo->CaracteristiquesHydrauliques[pays].MaxDesPmaxHydrauliques = pmaxHyd; @@ -67,15 +65,15 @@ void OPT_MaxDesPmaxHydrauliques(PROBLEME_HEBDO* problemeHebdo) double OPT_SommeDesPminThermiques(const PROBLEME_HEBDO* problemeHebdo, int Pays, uint pdtHebdo) { double sommeDesPminThermiques = 0.0; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[Pays]; - std::vector& PuissanceDisponibleEtCout + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[Pays]; + const std::vector& PuissanceDisponibleEtCout = PaliersThermiquesDuPays.PuissanceDisponibleEtCout; for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) { - sommeDesPminThermiques - += PuissanceDisponibleEtCout[index].PuissanceMinDuPalierThermique[pdtHebdo]; + sommeDesPminThermiques += PuissanceDisponibleEtCout[index] + .PuissanceMinDuPalierThermique[pdtHebdo]; } return sommeDesPminThermiques; @@ -95,16 +93,15 @@ void setBoundsForUnsuppliedEnergy(PROBLEME_HEBDO* problemeHebdo, const bool reserveJm1 = (problemeHebdo->YaDeLaReserveJmoins1); const bool opt1 = (optimizationNumber == PREMIERE_OPTIMISATION); + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int pdtHebdo = PremierPdtDeLIntervalle, pdtJour = 0; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++, pdtJour++) { - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdtJour]; - const ALL_MUST_RUN_GENERATION& AllMustRunGeneration - = problemeHebdo->AllMustRunGeneration[pdtHebdo]; - const CONSOMMATIONS_ABATTUES& ConsommationsAbattues - = problemeHebdo->ConsommationsAbattues[pdtHebdo]; + const ALL_MUST_RUN_GENERATION& AllMustRunGeneration = problemeHebdo + ->AllMustRunGeneration[pdtHebdo]; + const CONSOMMATIONS_ABATTUES& ConsommationsAbattues = problemeHebdo + ->ConsommationsAbattues[pdtHebdo]; for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { @@ -112,38 +109,47 @@ void setBoundsForUnsuppliedEnergy(PROBLEME_HEBDO* problemeHebdo, if (reserveJm1 && opt1) { - ResidualLoadInArea - += problemeHebdo->ReserveJMoins1[pays].ReserveHoraireJMoins1[pdtHebdo]; + ResidualLoadInArea += problemeHebdo->ReserveJMoins1[pays] + .ReserveHoraireJMoins1[pdtHebdo]; } - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[pays]; + int var = variableManager.PositiveUnsuppliedEnergy(pays, pdtJour); Xmin[var] = 0.0; double MaxAllMustRunGenerationOfArea = 0.; if (AllMustRunGeneration.AllMustRunGenerationOfArea[pays] > 0.) - MaxAllMustRunGenerationOfArea - = AllMustRunGeneration.AllMustRunGenerationOfArea[pays]; + { + MaxAllMustRunGenerationOfArea = AllMustRunGeneration + .AllMustRunGenerationOfArea[pays]; + } ResidualLoadInArea += MaxAllMustRunGenerationOfArea; if (ResidualLoadInArea >= 0.) + { Xmax[var] = ResidualLoadInArea + 1e-5; + } else + { Xmax[var] = 0.; + } // adq patch: update ENS <= DENS in 2nd run if (adqPatchParams.enabled && adqPatchParams.localMatching.enabled && !problemeHebdo->adequacyPatchRuntimeData->AdequacyFirstStep && problemeHebdo->adequacyPatchRuntimeData->areaMode[pays] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { Xmax[var] = std::min( - Xmax[var], problemeHebdo->ResultatsHoraires[pays].ValeursHorairesDENS[pdtHebdo]); + Xmax[var], + problemeHebdo->ResultatsHoraires[pays].ValeursHorairesDENS[pdtHebdo]); + } problemeHebdo->ResultatsHoraires[pays].ValeursHorairesDeDefaillancePositive[pdtHebdo] = 0.0; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] - = &(problemeHebdo->ResultatsHoraires[pays] - .ValeursHorairesDeDefaillancePositive[pdtHebdo]); + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = &( + problemeHebdo->ResultatsHoraires[pays] + .ValeursHorairesDeDefaillancePositive[pdtHebdo]); } } } @@ -154,53 +160,53 @@ static void setBoundsForShortTermStorage(PROBLEME_HEBDO* problemeHebdo, { std::vector& Xmin = problemeHebdo->ProblemeAResoudre->Xmin; std::vector& Xmax = problemeHebdo->ProblemeAResoudre->Xmax; - std::vector& AddressForVars - = problemeHebdo->ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees; + std::vector& AddressForVars = problemeHebdo->ProblemeAResoudre + ->AdresseOuPlacerLaValeurDesVariablesOptimisees; int weekFirstHour = problemeHebdo->weekInTheYear * 168; + + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); + for (int pdtHebdo = PremierPdtDeLIntervalle, pdtJour = 0; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++, pdtJour++) { int hourInTheYear = weekFirstHour + pdtHebdo; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdtJour]; for (uint32_t areaIndex = 0; areaIndex < problemeHebdo->NombreDePays; areaIndex++) { int storageIndex = 0; - for (const auto& storage : problemeHebdo->ShortTermStorage[areaIndex]) + for (const auto& storage: problemeHebdo->ShortTermStorage[areaIndex]) { const int clusterGlobalIndex = storage.clusterGlobalIndex; - auto& STSResult - = problemeHebdo->ResultatsHoraires[areaIndex].ShortTermStorage[pdtHebdo]; + auto& STSResult = problemeHebdo->ResultatsHoraires[areaIndex] + .ShortTermStorage[pdtHebdo]; // 1. Injection - int varInjection = CorrespondanceVarNativesVarOptim.SIM_ShortTermStorage - .InjectionVariable[clusterGlobalIndex]; + int varInjection = variableManager.ShortTermStorageInjection(clusterGlobalIndex, + pdtJour); Xmin[varInjection] = 0.; Xmax[varInjection] = storage.injectionNominalCapacity * storage.series->maxInjectionModulation[hourInTheYear]; AddressForVars[varInjection] = &STSResult.injection[storageIndex]; // 2. Withdrwal - int varWithdrawal = CorrespondanceVarNativesVarOptim.SIM_ShortTermStorage - .WithdrawalVariable[clusterGlobalIndex]; + int varWithdrawal = variableManager.ShortTermStorageWithdrawal(clusterGlobalIndex, + pdtJour); Xmin[varWithdrawal] = 0.; Xmax[varWithdrawal] = storage.withdrawalNominalCapacity * storage.series->maxWithdrawalModulation[hourInTheYear]; AddressForVars[varWithdrawal] = &STSResult.withdrawal[storageIndex]; // 3. Levels - int varLevel = CorrespondanceVarNativesVarOptim.SIM_ShortTermStorage - .LevelVariable[clusterGlobalIndex]; + int varLevel = variableManager.ShortTermStorageLevel(clusterGlobalIndex, pdtJour); if (pdtHebdo == DernierPdtDeLIntervalle - 1 && !storage.initialLevelOptim) { - Xmin[varLevel] = Xmax[varLevel] - = storage.reservoirCapacity * storage.initialLevel; + Xmin[varLevel] = Xmax[varLevel] = storage.reservoirCapacity + * storage.initialLevel; } else { - Xmin[varLevel] - = storage.reservoirCapacity * storage.series->lowerRuleCurve[hourInTheYear]; - Xmax[varLevel] - = storage.reservoirCapacity * storage.series->upperRuleCurve[hourInTheYear]; + Xmin[varLevel] = storage.reservoirCapacity + * storage.series->lowerRuleCurve[hourInTheYear]; + Xmax[varLevel] = storage.reservoirCapacity + * storage.series->upperRuleCurve[hourInTheYear]; } AddressForVars[varLevel] = &STSResult.level[storageIndex]; @@ -232,39 +238,50 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob AdresseOuPlacerLaValeurDesCoutsReduits[i] = nullptr; } + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int pdtHebdo = PremierPdtDeLIntervalle, pdtJour = 0; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++, pdtJour++) { VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeNTC = problemeHebdo->ValeursDeNTC[pdtHebdo]; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdtJour]; for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco]; + int var = variableManager.NTCDirect(interco, pdtJour); const COUTS_DE_TRANSPORT& CoutDeTransport = problemeHebdo->CoutDeTransport[interco]; - AdequacyPatch::setNTCbounds( - Xmax[var], Xmin[var], ValeursDeNTC, interco, problemeHebdo, adqPatchParams); + AdequacyPatch::setNTCbounds(Xmax[var], + Xmin[var], + ValeursDeNTC, + interco, + problemeHebdo, + adqPatchParams); - if (Math::Infinite(Xmax[var]) == 1) + if (std::isinf(Xmax[var]) && Xmax[var] > 0) { - if (Math::Infinite(Xmin[var]) == -1) + if (std::isinf(Xmin[var]) && Xmin[var] < 0) + { TypeDeVariable[var] = VARIABLE_NON_BORNEE; + } else + { TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; + } } else { - if (Math::Infinite(Xmin[var]) == -1) + if (std::isinf(Xmin[var]) && Xmin[var] < 0) + { TypeDeVariable[var] = VARIABLE_BORNEE_SUPERIEUREMENT; + } else + { TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } } - double* adresseDuResultat - = &(problemeHebdo->VariablesDualesDesContraintesDeNTC[pdtHebdo] - .VariableDualeParInterconnexion[interco]); + double* adresseDuResultat = &( + problemeHebdo->VariablesDualesDesContraintesDeNTC[pdtHebdo] + .VariableDualeParInterconnexion[interco]); AdresseOuPlacerLaValeurDesCoutsReduits[var] = adresseDuResultat; adresseDuResultat = &(ValeursDeNTC.ValeurDuFlux[interco]); @@ -272,64 +289,69 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob if (CoutDeTransport.IntercoGereeAvecDesCouts) { - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[interco]; + var = variableManager.IntercoDirectCost(interco, pdtJour); if (CoutDeTransport.IntercoGereeAvecLoopFlow) + { Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[interco] - ValeursDeNTC.ValeurDeLoopFlowOrigineVersExtremite[interco]; + } else + { Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[interco]; + } Xmax[var] += 0.01; TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[var]) == 1) + if (std::isinf(Xmax[var]) && Xmax[var] > 0) { TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; } Xmin[var] = 0.0; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[interco]; + var = variableManager.IntercoIndirectCost(interco, pdtJour); if (CoutDeTransport.IntercoGereeAvecLoopFlow) + { Xmax[var] = ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[interco] + ValeursDeNTC.ValeurDeLoopFlowOrigineVersExtremite[interco]; + } else + { Xmax[var] = ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[interco]; + } Xmax[var] += 0.01; TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[var]) == 1) + if (std::isinf(Xmax[var]) && Xmax[var] > 0) { TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; } Xmin[var] = 0.0; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; } } for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; int maxThermalPlant = PaliersThermiquesDuPays.NombreDePaliersThermiques; for (int index = 0; index < maxThermalPlant; index++) { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - int var - = CorrespondanceVarNativesVarOptim.NumeroDeVariableDuPalierThermique[palier]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + int var = variableManager.DispatchableProduction(palier, pdtJour); const PDISP_ET_COUTS_HORAIRES_PAR_PALIER& PuissanceDisponibleEtCout = PaliersThermiquesDuPays.PuissanceDisponibleEtCout[index]; Xmin[var] = PuissanceDisponibleEtCout.PuissanceMinDuPalierThermique[pdtHebdo]; - Xmax[var] - = PuissanceDisponibleEtCout.PuissanceDisponibleDuPalierThermique[pdtHebdo]; + Xmax[var] = PuissanceDisponibleEtCout + .PuissanceDisponibleDuPalierThermique[pdtHebdo]; double* adresseDuResultat = &(problemeHebdo->ResultatsHoraires[pays] .ProductionThermique[pdtHebdo] @@ -337,16 +359,16 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; } - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeLaProdHyd[pays]; + int var = variableManager.HydProd(pays, pdtJour); problemeHebdo->ResultatsHoraires[pays].TurbinageHoraire[pdtHebdo] = 0.0; if (var >= 0) { - Xmin[var] - = problemeHebdo->CaracteristiquesHydrauliques[pays].MingenHoraire[pdtHebdo]; + Xmin[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] + .MingenHoraire[pdtHebdo]; Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] .ContrainteDePmaxHydrauliqueHoraire[pdtHebdo]; - double* adresseDuResultat - = &(problemeHebdo->ResultatsHoraires[pays].TurbinageHoraire[pdtHebdo]); + double* adresseDuResultat = &( + problemeHebdo->ResultatsHoraires[pays].TurbinageHoraire[pdtHebdo]); AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; } @@ -355,66 +377,62 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob if (problemeHebdo->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_SOMME_DES_VARIATIONS) { - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaBaisse[pays]; + var = variableManager.HydProdDown(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { Xmin[var] = 0.0; Xmax[var] = LINFINI_ANTARES; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaHausse[pays]; + var = variableManager.HydProdUp(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { Xmin[var] = 0.0; Xmax[var] = LINFINI_ANTARES; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; } } else if (problemeHebdo->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_VARIATION_MAX && pdtJour == 0) { - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaBaisse[pays]; + var = variableManager.HydProdDown(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { Xmin[var] = 0.0; Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] .MaxDesPmaxHydrauliques; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaHausse[pays]; + var = variableManager.HydProdUp(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { Xmin[var] = 0.0; Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] .MaxDesPmaxHydrauliques; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; } } } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDePompage[pays]; + var = variableManager.Pumping(pays, pdtJour); problemeHebdo->ResultatsHoraires[pays].PompageHoraire[pdtHebdo] = 0.0; if (var >= 0) { Xmin[var] = 0.0; Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] .ContrainteDePmaxPompageHoraire[pdtHebdo]; - double* adresseDuResultat - = &(problemeHebdo->ResultatsHoraires[pays].PompageHoraire[pdtHebdo]); + double* adresseDuResultat = &( + problemeHebdo->ResultatsHoraires[pays].PompageHoraire[pdtHebdo]); AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeDebordement[pays]; + var = variableManager.Overflow(pays, pdtJour); problemeHebdo->ResultatsHoraires[pays].debordementsHoraires[pdtHebdo] = 0.; if (var >= 0) @@ -422,25 +440,25 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob Xmin[var] = 0.0; Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] .ApportNaturelHoraire[pdtHebdo]; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeNiveau[pays]; + var = variableManager.HydroLevel(pays, pdtJour); if (var >= 0) { - Xmin[var] - = problemeHebdo->CaracteristiquesHydrauliques[pays].NiveauHoraireInf[pdtHebdo]; - Xmax[var] - = problemeHebdo->CaracteristiquesHydrauliques[pays].NiveauHoraireSup[pdtHebdo]; - double* adresseDuResultat - = &(problemeHebdo->ResultatsHoraires[pays].niveauxHoraires[pdtHebdo]); - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; + Xmin[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] + .NiveauHoraireInf[pdtHebdo]; + Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays] + .NiveauHoraireSup[pdtHebdo]; + double* adresseDuResultat = &( + problemeHebdo->ResultatsHoraires[pays].niveauxHoraires[pdtHebdo]); + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; } { - var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillanceNegative[pays]; + var = variableManager.NegativeUnsuppliedEnergy(pays, pdtJour); Xmin[var] = 0.0; @@ -453,9 +471,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob .ValeursHorairesDeDefaillanceNegative[pdtHebdo]); AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; } - - problemeHebdo->ResultatsHoraires[pays].ValeursHorairesDeDefaillanceEnReserve[pdtHebdo] - = 0.0; } } @@ -471,32 +486,32 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob { if (problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) { - int var = problemeHebdo->NumeroDeVariableStockFinal[pays]; + int var = variableManager.FinalStorage(pays); if (var >= 0) { Xmin[var] = -(LINFINI_ANTARES); Xmax[var] = LINFINI_ANTARES; - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; // Note: if there were a single optimization run instead of two; the following // could be used: adresseDuResultat = //&(problemeHebdo->CaracteristiquesHydrauliques[pays].LevelForTimeInterval); // AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; } for (uint nblayer = 0; nblayer < 100; nblayer++) { - var = problemeHebdo->NumeroDeVariableDeTrancheDeStock[pays][nblayer]; + var = variableManager.LayerStorage(pays, nblayer); if (var >= 0) { Xmin[var] = 0; Xmax[var] = problemeHebdo->CaracteristiquesHydrauliques[pays].TailleReservoir / double(100); - AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = NULL; - AdresseOuPlacerLaValeurDesCoutsReduits[var] = NULL; + AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = nullptr; + AdresseOuPlacerLaValeurDesCoutsReduits[var] = nullptr; } } } @@ -505,7 +520,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* prob if (problemeHebdo->OptimisationAvecCoutsDeDemarrage) { OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage( - problemeHebdo, PremierPdtDeLIntervalle, DernierPdtDeLIntervalle); + problemeHebdo, + PremierPdtDeLIntervalle, + DernierPdtDeLIntervalle); } return; diff --git a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp index 51ccbfac21..e48672d22a 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -1,40 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" +#include -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" #include "pi_constantes_externes.h" - -#include +#include "variables/VariableManagerUtils.h" #define ZERO_POUR_LES_VARIABLES_FIXES 1.e-6 @@ -44,42 +37,54 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* p int PdtHebdo) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int i = 0; i < ProblemeAResoudre->NombreDeVariables; i++) + { ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[i] = nullptr; + } VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeNTC = problemeHebdo->ValeursDeNTC[PdtHebdo]; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[0]; for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco]; + int var = variableManager.NTCDirect(interco, 0); ProblemeAResoudre->Xmax[var] = ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[interco]; ProblemeAResoudre->Xmin[var] = -(ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[interco]); if (ProblemeAResoudre->Xmax[var] - ProblemeAResoudre->Xmin[var] < ZERO_POUR_LES_VARIABLES_FIXES) { - ProblemeAResoudre->X[var] - = 0.5 * (ProblemeAResoudre->Xmax[var] - ProblemeAResoudre->Xmin[var]); + ProblemeAResoudre->X[var] = 0.5 + * (ProblemeAResoudre->Xmax[var] + - ProblemeAResoudre->Xmin[var]); ProblemeAResoudre->TypeDeVariable[var] = VARIABLE_FIXE; } else { - if (Math::Infinite(ProblemeAResoudre->Xmax[var]) == 1) + const double Xmin = ProblemeAResoudre->Xmin[var]; + const double Xmax = ProblemeAResoudre->Xmax[var]; + if (std::isinf(Xmax) && Xmax > 0) { - if (Math::Infinite(ProblemeAResoudre->Xmin[var]) == -1) + if (std::isinf(Xmin) && Xmin < 0) + { ProblemeAResoudre->TypeDeVariable[var] = VARIABLE_NON_BORNEE; + } else + { ProblemeAResoudre->TypeDeVariable[var] = VARIABLE_BORNEE_INFERIEUREMENT; + } } else { - if (Math::Infinite(ProblemeAResoudre->Xmin[var]) == -1) + if (std::isinf(Xmin) && Xmin < 0) + { ProblemeAResoudre->TypeDeVariable[var] = VARIABLE_BORNEE_SUPERIEUREMENT; + } else + { ProblemeAResoudre->TypeDeVariable[var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } } } double* adresseDuResultat = &(ValeursDeNTC.ValeurDuFlux[interco]); diff --git a/src/solver/optimisation/opt_gestion_des_bornes_couts_demarrage.cpp b/src/solver/optimisation/opt_gestion_des_bornes_couts_demarrage.cpp index bf7d7ae914..e73cb62779 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_couts_demarrage.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_couts_demarrage.cpp @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/solver/simulation/simulation.h" -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include "opt_fonctions.h" +#include "variables/VariableManagement.h" +#include "variables/VariableManagerUtils.h" using namespace Yuni; @@ -40,38 +36,36 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage( const int DernierPdtDeLIntervalle) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; std::vector& AdresseOuPlacerLaValeurDesVariablesOptimisees = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees; std::vector& Xmin = ProblemeAResoudre->Xmin; std::vector& Xmax = ProblemeAResoudre->Xmax; + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int pdtHebdo = PremierPdtDeLIntervalle, pdtJour = 0; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++, pdtJour++) { - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdtJour]; - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) { const PDISP_ET_COUTS_HORAIRES_PAR_PALIER& PuissanceDisponibleEtCout = PaliersThermiquesDuPays.PuissanceDisponibleEtCout[index]; - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; const std::vector& NombreMaxDeGroupesEnMarcheDuPalierThermique = PuissanceDisponibleEtCout.NombreMaxDeGroupesEnMarcheDuPalierThermique; const std::vector& NombreMinDeGroupesEnMarcheDuPalierThermique = PuissanceDisponibleEtCout.NombreMinDeGroupesEnMarcheDuPalierThermique; - int var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesEnMarcheDuPalierThermique[palier]; + int var = variableManager.NumberOfDispatchableUnits(palier, pdtJour); + Xmax[var] = NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo]; Xmin[var] = NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo]; @@ -80,8 +74,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage( .NombreDeGroupesEnMarcheDuPalier[index]); AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiDemarrentDuPalierThermique[palier]; + var = variableManager.NumberStartingDispatchableUnits(palier, pdtJour); Xmax[var] = LINFINI_ANTARES; Xmin[var] = 0; adresseDuResultat = &(problemeHebdo->ResultatsHoraires[pays] @@ -89,8 +82,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage( .NombreDeGroupesQuiDemarrentDuPalier[index]); AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiSArretentDuPalierThermique[palier]; + var = variableManager.NumberStoppingDispatchableUnits(palier, pdtJour); Xmax[var] = LINFINI_ANTARES; Xmin[var] = 0; adresseDuResultat = &(problemeHebdo->ResultatsHoraires[pays] @@ -98,14 +90,15 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaireCoutsDeDemarrage( .NombreDeGroupesQuiSArretentDuPalier[index]); AdresseOuPlacerLaValeurDesVariablesOptimisees[var] = adresseDuResultat; - var - = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiTombentEnPanneDuPalierThermique[palier]; + // var + var = variableManager.NumberBreakingDownDispatchableUnits(palier, pdtJour); Xmin[var] = 0; int t1 = pdtHebdo; int t1moins1 = t1 - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTempsPourUneOptimisation + t1moins1; + } Xmax[var] = 0; if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] diff --git a/src/solver/optimisation/opt_gestion_des_couts_cas_lineaire.cpp b/src/solver/optimisation/opt_gestion_des_couts_cas_lineaire.cpp index 189a27662a..c2d1859106 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_lineaire.cpp @@ -1,77 +1,72 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include -#include "opt_structure_probleme_a_resoudre.h" -#include "../simulation/sim_spread_generator.h" -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_spread_generator.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" -#include "opt_fonctions.h" +#include "variables/VariableManagerUtils.h" static void shortTermStorageCost( int PremierPdtDeLIntervalle, int DernierPdtDeLIntervalle, int NombreDePays, const std::vector<::ShortTermStorage::AREA_INPUT>& shortTermStorageInput, - std::vector& CorrespondanceVarNativesVarOptim, + VariableManagement::VariableManager& variableManager, std::vector& linearCost) { SIM::SpreadGenerator spreadGenerator; for (int pays = 0; pays < NombreDePays; ++pays) { - for (const auto& storage : shortTermStorageInput[pays]) + for (const auto& storage: shortTermStorageInput[pays]) { for (int pdtHebdo = PremierPdtDeLIntervalle, pdtJour = 0; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++, pdtJour++) { - const auto& VarCurrent = CorrespondanceVarNativesVarOptim[pdtJour]; const int clusterGlobalIndex = storage.clusterGlobalIndex; - if (const int varLevel - = VarCurrent.SIM_ShortTermStorage.LevelVariable[clusterGlobalIndex]; + if (const int varLevel = variableManager.ShortTermStorageLevel(clusterGlobalIndex, + pdtJour); varLevel >= 0) { linearCost[varLevel] = 0; } const double cost = spreadGenerator.generate(); - if (const int varInjection - = VarCurrent.SIM_ShortTermStorage.InjectionVariable[clusterGlobalIndex]; + if (const int varInjection = variableManager.ShortTermStorageInjection( + clusterGlobalIndex, + pdtJour); varInjection >= 0) { linearCost[varInjection] = cost; } - if (const int varWithdrawal - = VarCurrent.SIM_ShortTermStorage.WithdrawalVariable[clusterGlobalIndex]; + if (const int varWithdrawal = variableManager.ShortTermStorageWithdrawal( + clusterGlobalIndex, + pdtJour); varWithdrawal >= 0) { linearCost[varWithdrawal] = storage.efficiency * cost; @@ -90,24 +85,22 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, int pdtJour = 0; ProblemeAResoudre->CoutQuadratique.assign(ProblemeAResoudre->NombreDeVariables, 0.); + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); shortTermStorageCost(PremierPdtDeLIntervalle, DernierPdtDeLIntervalle, problemeHebdo->NombreDePays, problemeHebdo->ShortTermStorage, - problemeHebdo->CorrespondanceVarNativesVarOptim, + variableManager, ProblemeAResoudre->CoutLineaire); for (int pdtHebdo = PremierPdtDeLIntervalle; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++) { - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdtJour]; - for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { const COUTS_DE_TRANSPORT& CoutDeTransport = problemeHebdo->CoutDeTransport[interco]; - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco]; + int var = variableManager.NTCDirect(interco, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { ProblemeAResoudre->CoutLineaire[var] = 0.0; @@ -115,34 +108,34 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, if (CoutDeTransport.IntercoGereeAvecDesCouts) { - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[interco]; + var = variableManager.IntercoDirectCost(interco, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[var] - = CoutDeTransport.CoutDeTransportOrigineVersExtremite[pdtHebdo]; + ProblemeAResoudre->CoutLineaire[var] = CoutDeTransport + .CoutDeTransportOrigineVersExtremite + [pdtHebdo]; } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[interco]; + var = variableManager.IntercoIndirectCost(interco, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[var] - = CoutDeTransport.CoutDeTransportExtremiteVersOrigine[pdtHebdo]; + ProblemeAResoudre->CoutLineaire[var] = CoutDeTransport + .CoutDeTransportExtremiteVersOrigine + [pdtHebdo]; } } } for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; ++pays) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; int var; for (int Index = 0; Index < PaliersThermiquesDuPays.NombreDePaliersThermiques; Index++) { - int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[Index]; - var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDuPalierThermique[palier]; + int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[Index]; + var = variableManager.DispatchableProduction(palier, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { ProblemeAResoudre->CoutLineaire[var] @@ -151,20 +144,24 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, } } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeLaProdHyd[pays]; + var = variableManager.HydProd(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) + { ProblemeAResoudre->CoutLineaire[var] = 0.0; + } if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[var] - = problemeHebdo - ->BruitSurCoutHydraulique[pays][problemeHebdo->HeureDansLAnnee + pdtHebdo]; + ProblemeAResoudre->CoutLineaire[var] = problemeHebdo->BruitSurCoutHydraulique + [pays][problemeHebdo->HeureDansLAnnee + + pdtHebdo]; if (!problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) - ProblemeAResoudre->CoutLineaire[var] - += problemeHebdo->CaracteristiquesHydrauliques[pays] - .WeeklyWaterValueStateRegular; + { + ProblemeAResoudre->CoutLineaire[var] += problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .WeeklyWaterValueStateRegular; + } } if (problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable) @@ -176,14 +173,16 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, P = problemeHebdo->CaracteristiquesHydrauliques[pays] .PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaBaisse[pays]; + var = variableManager.HydProdDown(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) + { ProblemeAResoudre->CoutLineaire[var] = P; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaHausse[pays]; + } + var = variableManager.HydProdUp(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) + { ProblemeAResoudre->CoutLineaire[var] = P; + } } else if (problemeHebdo->TypeDeLissageHydraulique == LISSAGE_HYDRAULIQUE_SUR_VARIATION_MAX @@ -191,18 +190,21 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, { P = problemeHebdo->CaracteristiquesHydrauliques[pays] .PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaBaisse[pays]; + var = variableManager.HydProdDown(pays, pdtJour); + if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) + { ProblemeAResoudre->CoutLineaire[var] = P; - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariablesVariationHydALaHausse[pays]; + } + var = variableManager.HydProdUp(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) + { ProblemeAResoudre->CoutLineaire[var] = -P; + } } } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDePompage[pays]; + var = variableManager.Pumping(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { /* Sets the cost of the pumping variable when such a variable is actually defined @@ -229,31 +231,33 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, if (!problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) { - ProblemeAResoudre->CoutLineaire[var] - = problemeHebdo->CaracteristiquesHydrauliques[pays] - .WeeklyWaterValueStateRegular; + ProblemeAResoudre->CoutLineaire[var] = problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .WeeklyWaterValueStateRegular; - ProblemeAResoudre->CoutLineaire[var] - *= problemeHebdo->CaracteristiquesHydrauliques[pays].PumpingRatio; + ProblemeAResoudre->CoutLineaire[var] *= problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .PumpingRatio; ProblemeAResoudre->CoutLineaire[var] *= -1.; - ProblemeAResoudre->CoutLineaire[var] - += 2. - * fabs(problemeHebdo - ->BruitSurCoutHydraulique[pays][problemeHebdo->HeureDansLAnnee - + pdtHebdo]); + ProblemeAResoudre->CoutLineaire[var] += 2. + * fabs( + problemeHebdo->BruitSurCoutHydraulique + [pays] + [problemeHebdo->HeureDansLAnnee + + pdtHebdo]); } else { - ProblemeAResoudre->CoutLineaire[var] - = 2. - * fabs(problemeHebdo - ->BruitSurCoutHydraulique[pays][problemeHebdo->HeureDansLAnnee - + pdtHebdo]); + ProblemeAResoudre->CoutLineaire[var] = 2. + * fabs( + problemeHebdo->BruitSurCoutHydraulique + [pays][problemeHebdo->HeureDansLAnnee + + pdtHebdo]); } } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeDebordement[pays]; + var = variableManager.Overflow(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { /* Sets the cost of the overflow variable when such a variable is actually defined @@ -276,38 +280,38 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, if (!problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) { - ProblemeAResoudre->CoutLineaire[var] - = problemeHebdo->CoutDeDefaillanceNegative[pays]; + ProblemeAResoudre->CoutLineaire[var] = problemeHebdo + ->CoutDeDefaillanceNegative[pays]; - ProblemeAResoudre->CoutLineaire[var] - += problemeHebdo->CaracteristiquesHydrauliques[pays] - .WeeklyWaterValueStateRegular; + ProblemeAResoudre->CoutLineaire[var] += problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .WeeklyWaterValueStateRegular; } else { - ProblemeAResoudre->CoutLineaire[var] - = problemeHebdo->CoutDeDefaillanceNegative[pays]; + ProblemeAResoudre->CoutLineaire[var] = problemeHebdo + ->CoutDeDefaillanceNegative[pays]; } } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariablesDeNiveau[pays]; + var = variableManager.HydroLevel(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { ProblemeAResoudre->CoutLineaire[var] = 0; } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillancePositive[pays]; + var = variableManager.PositiveUnsuppliedEnergy(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[var] - = problemeHebdo->CoutDeDefaillancePositive[pays]; + ProblemeAResoudre->CoutLineaire[var] = problemeHebdo + ->CoutDeDefaillancePositive[pays]; } - var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDefaillanceNegative[pays]; + var = variableManager.NegativeUnsuppliedEnergy(pays, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[var] - = problemeHebdo->CoutDeDefaillanceNegative[pays]; + ProblemeAResoudre->CoutLineaire[var] = problemeHebdo + ->CoutDeDefaillanceNegative[pays]; } } @@ -318,7 +322,7 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, { if (problemeHebdo->CaracteristiquesHydrauliques[pays].AccurateWaterValue) { - int var = problemeHebdo->NumeroDeVariableStockFinal[pays]; + int var = variableManager.FinalStorage(pays); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { ProblemeAResoudre->CoutLineaire[var] = 0; @@ -326,12 +330,12 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, for (int layerindex = 0; layerindex < 100; layerindex++) { - var = problemeHebdo->NumeroDeVariableDeTrancheDeStock[pays][layerindex]; + var = variableManager.LayerStorage(pays, layerindex); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[var] - = -problemeHebdo->CaracteristiquesHydrauliques[pays] - .WaterLayerValues[layerindex]; + ProblemeAResoudre->CoutLineaire[var] = -problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .WaterLayerValues[layerindex]; } } } @@ -339,8 +343,9 @@ void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO* problemeHebdo, if (problemeHebdo->OptimisationAvecCoutsDeDemarrage) { - OPT_InitialiserLesCoutsLineaireCoutsDeDemarrage( - problemeHebdo, PremierPdtDeLIntervalle, DernierPdtDeLIntervalle); + OPT_InitialiserLesCoutsLineaireCoutsDeDemarrage(problemeHebdo, + PremierPdtDeLIntervalle, + DernierPdtDeLIntervalle); } return; diff --git a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp index 5aa0efee81..4e3c137cf7 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -1,53 +1,48 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" -#include "opt_fonctions.h" +#include "variables/VariableManagerUtils.h" void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* problemeHebdo, int PdtHebdo) { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; ProblemeAResoudre->CoutLineaire.assign(ProblemeAResoudre->NombreDeVariables, 0.); + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); - const VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeResistances - = problemeHebdo->ValeursDeNTC[PdtHebdo]; - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[0]; + const VALEURS_DE_NTC_ET_RESISTANCES& ValeursDeResistances = problemeHebdo + ->ValeursDeNTC[PdtHebdo]; for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { - int var = CorrespondanceVarNativesVarOptim.NumeroDeVariableDeLInterconnexion[interco]; + int var = variableManager.NTCDirect(interco, 0); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) - ProblemeAResoudre->CoutQuadratique[var] - = ValeursDeResistances.ResistanceApparente[interco]; + { + ProblemeAResoudre->CoutQuadratique[var] = ValeursDeResistances + .ResistanceApparente[interco]; + } } } diff --git a/src/solver/optimisation/opt_gestion_des_couts_couts_demarrage.cpp b/src/solver/optimisation/opt_gestion_des_couts_couts_demarrage.cpp index 2d508e10a6..3112f70e68 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_couts_demarrage.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_couts_demarrage.cpp @@ -1,38 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" -#include "opt_fonctions.h" +#include "variables/VariableManagerUtils.h" void OPT_InitialiserLesCoutsLineaireCoutsDeDemarrage(PROBLEME_HEBDO* problemeHebdo, const int PremierPdtDeLIntervalle, @@ -40,51 +33,46 @@ void OPT_InitialiserLesCoutsLineaireCoutsDeDemarrage(PROBLEME_HEBDO* problemeHeb { const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; std::vector& CoutLineaire = ProblemeAResoudre->CoutLineaire; + auto variableManager = VariableManagerFromProblemHebdo(problemeHebdo); for (int pdtHebdo = PremierPdtDeLIntervalle, pdtJour = 0; pdtHebdo < DernierPdtDeLIntervalle; pdtHebdo++, pdtJour++) { - const CORRESPONDANCES_DES_VARIABLES& CorrespondanceVarNativesVarOptim - = problemeHebdo->CorrespondanceVarNativesVarOptim[pdtJour]; - for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) { - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; - int var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesEnMarcheDuPalierThermique[palier]; + int var = variableManager.NumberOfDispatchableUnits(palier, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - CoutLineaire[var] - = PaliersThermiquesDuPays.CoutFixeDeMarcheDUnGroupeDuPalierThermique[index]; + CoutLineaire[var] = PaliersThermiquesDuPays + .CoutFixeDeMarcheDUnGroupeDuPalierThermique[index]; } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiSArretentDuPalierThermique[palier]; + var = variableManager.NumberStoppingDispatchableUnits(palier, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - CoutLineaire[var] - = PaliersThermiquesDuPays.CoutDArretDUnGroupeDuPalierThermique[index]; + CoutLineaire[var] = PaliersThermiquesDuPays + .CoutDArretDUnGroupeDuPalierThermique[index]; } - var - = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiTombentEnPanneDuPalierThermique[palier]; + var = variableManager.NumberBreakingDownDispatchableUnits(palier, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) + { CoutLineaire[var] = 0; + } - var = CorrespondanceVarNativesVarOptim - .NumeroDeVariableDuNombreDeGroupesQuiDemarrentDuPalierThermique[palier]; + var = variableManager.NumberStartingDispatchableUnits(palier, pdtJour); if (var >= 0 && var < ProblemeAResoudre->NombreDeVariables) { - CoutLineaire[var] - = PaliersThermiquesDuPays.CoutDeDemarrageDUnGroupeDuPalierThermique[index]; + CoutLineaire[var] = PaliersThermiquesDuPays + .CoutDeDemarrageDUnGroupeDuPalierThermique[index]; } } } diff --git a/src/solver/optimisation/opt_gestion_des_pmin.cpp b/src/solver/optimisation/opt_gestion_des_pmin.cpp index b3bf43a60a..921371b0e3 100644 --- a/src/solver/optimisation/opt_gestion_des_pmin.cpp +++ b/src/solver/optimisation/opt_gestion_des_pmin.cpp @@ -1,34 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" #define ZERO 1.e-2 @@ -38,8 +31,7 @@ void OPT_InitialiserLesPminHebdo(PROBLEME_HEBDO* problemeHebdo) for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo->PaliersThermiquesDuPays[pays]; std::vector& PuissanceDisponibleEtCout = PaliersThermiquesDuPays.PuissanceDisponibleEtCout; for (int palier = 0; palier < PaliersThermiquesDuPays.NombreDePaliersThermiques; palier++) diff --git a/src/solver/optimisation/opt_gestion_second_membre_cas_lineaire.cpp b/src/solver/optimisation/opt_gestion_second_membre_cas_lineaire.cpp index 73506a61c1..3818f73e38 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_lineaire.cpp @@ -1,56 +1,46 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" -#include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" using namespace Antares; using namespace Antares::Data; using namespace Yuni; static void shortTermStorageLevelsRHS( - const std::vector<::ShortTermStorage::AREA_INPUT>& shortTermStorageInput, - int numberOfAreas, - std::vector& SecondMembre, - const CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim, - int hourInTheYear) + const std::vector<::ShortTermStorage::AREA_INPUT>& shortTermStorageInput, + int numberOfAreas, + std::vector& SecondMembre, + const CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim, + int hourInTheYear) { for (int areaIndex = 0; areaIndex < numberOfAreas; areaIndex++) { - for (auto& storage : shortTermStorageInput[areaIndex]) + for (auto& storage: shortTermStorageInput[areaIndex]) { const int clusterGlobalIndex = storage.clusterGlobalIndex; - const int cnt - = CorrespondanceCntNativesCntOptim.ShortTermStorageLevelConstraint[clusterGlobalIndex]; + const int cnt = CorrespondanceCntNativesCntOptim + .ShortTermStorageLevelConstraint[clusterGlobalIndex]; SecondMembre[cnt] = storage.series->inflows[hourInTheYear]; } } @@ -80,8 +70,8 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb = problemeHebdo->NumeroDeContrainteMinEnergieHydraulique; const std::vector& NumeroDeContrainteMaxEnergieHydraulique = problemeHebdo->NumeroDeContrainteMaxEnergieHydraulique; - const std::vector& NumeroDeContrainteMaxPompage - = problemeHebdo->NumeroDeContrainteMaxPompage; + const std::vector& NumeroDeContrainteMaxPompage = problemeHebdo + ->NumeroDeContrainteMaxPompage; const std::vector& DefaillanceNegativeUtiliserConsoAbattue = problemeHebdo->DefaillanceNegativeUtiliserConsoAbattue; @@ -91,7 +81,6 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb for (int i = 0; i < ProblemeAResoudre->NombreDeContraintes; i++) { AdresseOuPlacerLaValeurDesCoutsMarginaux[i] = nullptr; - SecondMembre[i] = 0.0; } @@ -101,10 +90,10 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb const CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim = problemeHebdo->CorrespondanceCntNativesCntOptim[pdtJour]; - const CONSOMMATIONS_ABATTUES& ConsommationsAbattues - = problemeHebdo->ConsommationsAbattues[pdtHebdo]; - const ALL_MUST_RUN_GENERATION& AllMustRunGeneration - = problemeHebdo->AllMustRunGeneration[pdtHebdo]; + const CONSOMMATIONS_ABATTUES& ConsommationsAbattues = problemeHebdo + ->ConsommationsAbattues[pdtHebdo]; + const ALL_MUST_RUN_GENERATION& AllMustRunGeneration = problemeHebdo + ->AllMustRunGeneration[pdtHebdo]; for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { int cnt = CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesBilansPays[pays]; @@ -114,12 +103,12 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb bool opt1 = (optimizationNumber == PREMIERE_OPTIMISATION); if (reserveJm1 && opt1) { - SecondMembre[cnt] - -= problemeHebdo->ReserveJMoins1[pays].ReserveHoraireJMoins1[pdtHebdo]; + SecondMembre[cnt] -= problemeHebdo->ReserveJMoins1[pays] + .ReserveHoraireJMoins1[pdtHebdo]; } - double* adresseDuResultat - = &(problemeHebdo->ResultatsHoraires[pays].CoutsMarginauxHoraires[pdtHebdo]); + double* adresseDuResultat = &( + problemeHebdo->ResultatsHoraires[pays].CoutsMarginauxHoraires[pdtHebdo]); AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] = adresseDuResultat; cnt = CorrespondanceCntNativesCntOptim @@ -128,15 +117,19 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb double MaxAllMustRunGeneration = 0.0; if (AllMustRunGeneration.AllMustRunGenerationOfArea[pays] > 0.0) + { MaxAllMustRunGeneration = AllMustRunGeneration.AllMustRunGenerationOfArea[pays]; + } double MaxMoinsConsommationBrute = 0.0; if (-(ConsommationsAbattues.ConsommationAbattueDuPays[pays] + AllMustRunGeneration.AllMustRunGenerationOfArea[pays]) > 0.0) - MaxMoinsConsommationBrute - = -(ConsommationsAbattues.ConsommationAbattueDuPays[pays] - + AllMustRunGeneration.AllMustRunGenerationOfArea[pays]); + { + MaxMoinsConsommationBrute = -( + ConsommationsAbattues.ConsommationAbattueDuPays[pays] + + AllMustRunGeneration.AllMustRunGenerationOfArea[pays]); + } SecondMembre[cnt] = DefaillanceNegativeUtiliserConsoAbattue[pays] * (MaxAllMustRunGeneration + MaxMoinsConsommationBrute); @@ -159,15 +152,19 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { if (const COUTS_DE_TRANSPORT& CoutDeTransport = problemeHebdo->CoutDeTransport[interco]; - CoutDeTransport.IntercoGereeAvecDesCouts) + CoutDeTransport.IntercoGereeAvecDesCouts) { int cnt = CorrespondanceCntNativesCntOptim .NumeroDeContrainteDeDissociationDeFlux[interco]; if (CoutDeTransport.IntercoGereeAvecLoopFlow) + { SecondMembre[cnt] = problemeHebdo->ValeursDeNTC[pdtHebdo] .ValeurDeLoopFlowOrigineVersExtremite[interco]; + } else + { SecondMembre[cnt] = 0.; + } AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] = nullptr; } } @@ -178,17 +175,22 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes = problemeHebdo->MatriceDesContraintesCouplantes[cntCouplante]; if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante != CONTRAINTE_HORAIRE) + { continue; + } int cnt = CorrespondanceCntNativesCntOptim .NumeroDeContrainteDesContraintesCouplantes[cntCouplante]; if (cnt >= 0) { - SecondMembre[cnt] - = MatriceDesContraintesCouplantes.SecondMembreDeLaContrainteCouplante[pdtHebdo]; - AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] - = problemeHebdo->ResultatsContraintesCouplantes[cntCouplante].variablesDuales.data() - + pdtHebdo; + SecondMembre[cnt] = MatriceDesContraintesCouplantes + .SecondMembreDeLaContrainteCouplante[pdtHebdo]; + AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] = problemeHebdo + ->ResultatsContraintesCouplantes + [MatriceDesContraintesCouplantes + .bindingConstraint] + .data() + + pdtHebdo; } } } @@ -199,24 +201,26 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb int indexCorrespondanceCnt = (!problemeHebdo->OptimisationAuPasHebdomadaire) ? 0 : jour; CORRESPONDANCES_DES_CONTRAINTES_JOURNALIERES& CorrespondanceCntNativesCntOptimJournalieres - = problemeHebdo->CorrespondanceCntNativesCntOptimJournalieres[indexCorrespondanceCnt]; + = problemeHebdo->CorrespondanceCntNativesCntOptimJournalieres[indexCorrespondanceCnt]; for (uint32_t cntCouplante = 0; cntCouplante < problemeHebdo->NombreDeContraintesCouplantes; cntCouplante++) { const CONTRAINTES_COUPLANTES& MatriceDesContraintesCouplantes = problemeHebdo->MatriceDesContraintesCouplantes[cntCouplante]; - if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante - == CONTRAINTE_JOURNALIERE) + if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante == CONTRAINTE_JOURNALIERE) { int cnt = CorrespondanceCntNativesCntOptimJournalieres .NumeroDeContrainteDesContraintesCouplantes[cntCouplante]; if (cnt >= 0) { - SecondMembre[cnt] - = MatriceDesContraintesCouplantes.SecondMembreDeLaContrainteCouplante[jour]; + SecondMembre[cnt] = MatriceDesContraintesCouplantes + .SecondMembreDeLaContrainteCouplante[jour]; AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] - = problemeHebdo->ResultatsContraintesCouplantes[cntCouplante].variablesDuales.data() + = problemeHebdo + ->ResultatsContraintesCouplantes[MatriceDesContraintesCouplantes + .bindingConstraint] + .data() + jour; } } @@ -239,16 +243,21 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb if (MatriceDesContraintesCouplantes.TypeDeContrainteCouplante != CONTRAINTE_HEBDOMADAIRE) + { continue; + } int cnt = CorrespondanceCntNativesCntOptimHebdomadaires .NumeroDeContrainteDesContraintesCouplantes[cntCouplante]; if (cnt >= 0) { - SecondMembre[cnt] - = MatriceDesContraintesCouplantes.SecondMembreDeLaContrainteCouplante[0]; - AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] - = problemeHebdo->ResultatsContraintesCouplantes[cntCouplante].variablesDuales.data(); + SecondMembre[cnt] = MatriceDesContraintesCouplantes + .SecondMembreDeLaContrainteCouplante[0]; + AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] = problemeHebdo + ->ResultatsContraintesCouplantes + [MatriceDesContraintesCouplantes + .bindingConstraint] + .data(); } } } @@ -266,11 +275,12 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - bool presenceHydro - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable; - bool TurbEntreBornes - = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; - if (presenceHydro && (TurbEntreBornes + bool presenceHydro = problemeHebdo->CaracteristiquesHydrauliques[pays] + .PresenceDHydrauliqueModulable; + bool TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays] + .TurbinageEntreBornes; + if (presenceHydro + && (TurbEntreBornes || problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) { int cnt = NumeroDeContrainteMinEnergieHydraulique[pays]; @@ -285,11 +295,12 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - bool presenceHydro - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable; - bool TurbEntreBornes - = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; - if (presenceHydro && (TurbEntreBornes + bool presenceHydro = problemeHebdo->CaracteristiquesHydrauliques[pays] + .PresenceDHydrauliqueModulable; + bool TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays] + .TurbinageEntreBornes; + if (presenceHydro + && (TurbEntreBornes || problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) { int cnt = NumeroDeContrainteMaxEnergieHydraulique[pays]; @@ -325,7 +336,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { if (!problemeHebdo->CaracteristiquesHydrauliques[pays].SuiviNiveauHoraire) + { continue; + } int cnt = CorrespondanceCntNativesCntOptim.NumeroDeContrainteDesNiveauxPays[pays]; if (cnt >= 0) @@ -334,8 +347,8 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb .ApportNaturelHoraire[pdtHebdo]; if (pdtHebdo == 0) { - SecondMembre[cnt] - += problemeHebdo->CaracteristiquesHydrauliques[pays].NiveauInitialReservoir; + SecondMembre[cnt] += problemeHebdo->CaracteristiquesHydrauliques[pays] + .NiveauInitialReservoir; } AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] = nullptr; } @@ -369,8 +382,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO* problemeHeb if (problemeHebdo->OptimisationAvecCoutsDeDemarrage) { - OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage( - problemeHebdo, PremierPdtDeLIntervalle, DernierPdtDeLIntervalle); + OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(problemeHebdo, + PremierPdtDeLIntervalle, + DernierPdtDeLIntervalle); } return; diff --git a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp index 588d1f51b7..44d6486041 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -1,36 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* problemeHebdo, int PdtHebdo) { @@ -39,7 +31,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* probleme for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays - 1; pays++) { int cnt = problemeHebdo->NumeroDeContrainteDeSoldeDEchange[pays]; - ProblemeAResoudre->SecondMembre[cnt] - = problemeHebdo->SoldeMoyenHoraire[PdtHebdo].SoldeMoyenDuPays[pays]; + ProblemeAResoudre->SecondMembre[cnt] = problemeHebdo->SoldeMoyenHoraire[PdtHebdo] + .SoldeMoyenDuPays[pays]; } } diff --git a/src/solver/optimisation/opt_gestion_second_membre_couts_demarrage.cpp b/src/solver/optimisation/opt_gestion_second_membre_couts_demarrage.cpp index 50a7d22d56..215532e83e 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_couts_demarrage.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_couts_demarrage.cpp @@ -1,38 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" - #include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" using namespace Antares; using namespace Antares::Data; @@ -48,13 +39,13 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HE std::vector& AdresseOuPlacerLaValeurDesCoutsMarginaux = ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsMarginaux; - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + int NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + const PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; for (int index = 0; index < PaliersThermiquesDuPays.NombreDePaliersThermiques; index++) { @@ -63,8 +54,8 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HE .NombreMaxDeGroupesEnMarcheDuPalierThermique; const int DureeMinimaleDArretDUnGroupeDuPalierThermique = PaliersThermiquesDuPays.DureeMinimaleDArretDUnGroupeDuPalierThermique[index]; - const int palier - = PaliersThermiquesDuPays.NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; + const int palier = PaliersThermiquesDuPays + .NumeroDuPalierDansLEnsembleDesPaliersThermiques[index]; for (int pdtJour = 0, pdtHebdo = PremierPdtDeLIntervalle; pdtHebdo < DernierPdtDeLIntervalle; @@ -73,12 +64,14 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HE const CORRESPONDANCES_DES_CONTRAINTES& CorrespondanceCntNativesCntOptim = problemeHebdo->CorrespondanceCntNativesCntOptim[pdtJour]; int cnt = CorrespondanceCntNativesCntOptim - .NumeroDeContrainteDesContraintesDeDureeMinDArret[palier]; + .NumeroDeContrainteDesContraintesDeDureeMinDArret[palier]; if (cnt >= 0) { int t1 = pdtHebdo - DureeMinimaleDArretDUnGroupeDuPalierThermique; if (t1 < 0) + { t1 = NombreDePasDeTempsPourUneOptimisation + t1; + } SecondMembre[cnt] = NombreMaxDeGroupesEnMarcheDuPalierThermique[t1]; for (int k = pdtHebdo - DureeMinimaleDArretDUnGroupeDuPalierThermique + 1; k <= pdtHebdo; @@ -87,20 +80,24 @@ void OPT_InitialiserLeSecondMembreDuProblemeLineaireCoutsDeDemarrage(PROBLEME_HE t1 = k; if (t1 < 0) + { t1 = NombreDePasDeTempsPourUneOptimisation + t1; + } int t1moins1 = t1 - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTempsPourUneOptimisation + t1moins1; + } if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] > 0) { - SecondMembre[cnt] - += NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1]; + SecondMembre[cnt] += NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] + - NombreMaxDeGroupesEnMarcheDuPalierThermique + [t1moins1]; } } AdresseOuPlacerLaValeurDesCoutsMarginaux[cnt] = nullptr; diff --git a/src/solver/optimisation/opt_init_contraintes_hydrauliques.cpp b/src/solver/optimisation/opt_init_contraintes_hydrauliques.cpp index 49a005f584..c9f25e418f 100644 --- a/src/solver/optimisation/opt_init_contraintes_hydrauliques.cpp +++ b/src/solver/optimisation/opt_init_contraintes_hydrauliques.cpp @@ -1,54 +1,50 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise( PROBLEME_HEBDO* problemeHebdo) { - int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; - int NbIntervallesOptimises - = problemeHebdo->NombreDePasDeTemps / NombreDePasDeTempsPourUneOptimisation; - int NombreDeJoursParIntervalle - = NombreDePasDeTempsPourUneOptimisation / problemeHebdo->NombreDePasDeTempsDUneJournee; + int NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; + int NbIntervallesOptimises = problemeHebdo->NombreDePasDeTemps + / NombreDePasDeTempsPourUneOptimisation; + int NombreDeJoursParIntervalle = NombreDePasDeTempsPourUneOptimisation + / problemeHebdo->NombreDePasDeTempsDUneJournee; for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { if (!problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable || problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes) + { continue; + } - std::vector& CntEnergieH2OParJour - = problemeHebdo->CaracteristiquesHydrauliques[pays].CntEnergieH2OParJour; + std::vector& CntEnergieH2OParJour = problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .CntEnergieH2OParJour; std::vector& CntEnergieH2OParIntervalleOptimise = problemeHebdo->CaracteristiquesHydrauliques[pays].CntEnergieH2OParIntervalleOptimise; @@ -69,17 +65,18 @@ void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise( for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - bool presenceHydro - = problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDHydrauliqueModulable; - bool TurbEntreBornes - = problemeHebdo->CaracteristiquesHydrauliques[pays].TurbinageEntreBornes; + bool presenceHydro = problemeHebdo->CaracteristiquesHydrauliques[pays] + .PresenceDHydrauliqueModulable; + bool TurbEntreBornes = problemeHebdo->CaracteristiquesHydrauliques[pays] + .TurbinageEntreBornes; if (presenceHydro && (TurbEntreBornes || problemeHebdo->CaracteristiquesHydrauliques[pays].PresenceDePompageModulable)) { - std::vector& CntEnergieH2OParJour - = problemeHebdo->CaracteristiquesHydrauliques[pays].CntEnergieH2OParJour; + std::vector& CntEnergieH2OParJour = problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .CntEnergieH2OParJour; std::vector& MinEnergieHydrauParIntervalleOptimise = problemeHebdo->CaracteristiquesHydrauliques[pays] .MinEnergieHydrauParIntervalleOptimise; @@ -126,8 +123,9 @@ void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise( for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - std::vector& InflowForTimeInterval - = problemeHebdo->CaracteristiquesHydrauliques[pays].InflowForTimeInterval; + std::vector& InflowForTimeInterval = problemeHebdo + ->CaracteristiquesHydrauliques[pays] + .InflowForTimeInterval; for (int intervalle = 0; intervalle < NbIntervallesOptimises; intervalle++) { diff --git a/src/solver/optimisation/opt_init_minmax_groupes_couts_demarrage.cpp b/src/solver/optimisation/opt_init_minmax_groupes_couts_demarrage.cpp index ed8b0509ba..1ca75d33d2 100644 --- a/src/solver/optimisation/opt_init_minmax_groupes_couts_demarrage.cpp +++ b/src/solver/optimisation/opt_init_minmax_groupes_couts_demarrage.cpp @@ -1,45 +1,39 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" void OPT_InitialiserNombreMinEtMaxDeGroupesCoutsDeDemarrage(PROBLEME_HEBDO* problemeHebdo) { if (!problemeHebdo->OptimisationAvecCoutsDeDemarrage) + { return; + } for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo->PaliersThermiquesDuPays[pays]; std::vector& PuissanceDisponibleEtCout = PaliersThermiquesDuPays.PuissanceDisponibleEtCout; @@ -61,13 +55,13 @@ void OPT_InitialiserNombreMinEtMaxDeGroupesCoutsDeDemarrage(PROBLEME_HEBDO* prob { if (TailleUnitaireDUnGroupeDuPalierThermique != 0) { - NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] - = (int)ceil(PuissanceDisponibleDuPalierThermiqueRef[pdtHebdo] - / TailleUnitaireDUnGroupeDuPalierThermique); + NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] = (int)ceil( + PuissanceDisponibleDuPalierThermiqueRef[pdtHebdo] + / TailleUnitaireDUnGroupeDuPalierThermique); - NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo] - = (int)ceil(PuissanceMinDuPalierThermiqueRef[pdtHebdo] - / TailleUnitaireDUnGroupeDuPalierThermique); + NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo] = (int)ceil( + PuissanceMinDuPalierThermiqueRef[pdtHebdo] + / TailleUnitaireDUnGroupeDuPalierThermique); } else { diff --git a/src/solver/optimisation/opt_liberation_problemes_simplexe.cpp b/src/solver/optimisation/opt_liberation_problemes_simplexe.cpp index 05b84ec32b..df0a9b4e37 100644 --- a/src/solver/optimisation/opt_liberation_problemes_simplexe.cpp +++ b/src/solver/optimisation/opt_liberation_problemes_simplexe.cpp @@ -1,39 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" - -#include "../utils/ortools_utils.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" +#include "antares/solver/utils/ortools_utils.h" extern "C" { @@ -42,37 +33,43 @@ extern "C" using namespace Antares; -void OPT_LiberationProblemesSimplexe(const OptimizationOptions& options, const PROBLEME_HEBDO* problemeHebdo) +void OPT_LiberationProblemesSimplexe(const OptimizationOptions& options, + const PROBLEME_HEBDO* problemeHebdo) { int NombreDePasDeTempsPourUneOptimisation; if (!problemeHebdo->OptimisationAuPasHebdomadaire) + { NombreDePasDeTempsPourUneOptimisation = problemeHebdo->NombreDePasDeTempsDUneJournee; + } else + { NombreDePasDeTempsPourUneOptimisation = problemeHebdo->NombreDePasDeTemps; + } int nbIntervalles = problemeHebdo->NombreDePasDeTemps / NombreDePasDeTempsPourUneOptimisation; const auto& ProblemeAResoudre = problemeHebdo->ProblemeAResoudre; if (!ProblemeAResoudre) + { return; + } if (!problemeHebdo->LeProblemeADejaEteInstancie) { for (int numIntervalle = 0; numIntervalle < nbIntervalles; numIntervalle++) { - auto ProbSpx - = (PROBLEME_SPX*)(ProblemeAResoudre->ProblemesSpx[numIntervalle]); + auto ProbSpx = (PROBLEME_SPX*)(ProblemeAResoudre->ProblemesSpx[numIntervalle]); auto solver = (MPSolver*)(ProblemeAResoudre->ProblemesSpx[numIntervalle]); - if (options.useOrtools && solver != NULL) + if (options.ortoolsUsed && solver) { ORTOOLS_LibererProbleme(solver); - solver = NULL; + solver = nullptr; } - else if (ProbSpx != NULL) + else if (ProbSpx) { SPX_LibererProbleme(ProbSpx); - ProbSpx = NULL; + ProbSpx = nullptr; } } } diff --git a/src/solver/optimisation/opt_nombre_min_groupes_demarres_couts_demarrage.cpp b/src/solver/optimisation/opt_nombre_min_groupes_demarres_couts_demarrage.cpp index eb050f39d6..705fd63290 100644 --- a/src/solver/optimisation/opt_nombre_min_groupes_demarres_couts_demarrage.cpp +++ b/src/solver/optimisation/opt_nombre_min_groupes_demarres_couts_demarrage.cpp @@ -1,37 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" extern "C" { @@ -57,7 +49,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBL void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO* problemeHebdo) { if (!problemeHebdo->OptimisationAvecCoutsDeDemarrage) + { return; + } int NombreDePasDeTempsProblemeHebdo = problemeHebdo->NombreDePasDeTemps; double Eps = 1.e-3; @@ -68,10 +62,9 @@ void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO* pro { const RESULTATS_HORAIRES& ResultatsHoraires = problemeHebdo->ResultatsHoraires[pays]; const std::vector& ProductionThermique - = ResultatsHoraires.ProductionThermique; + = ResultatsHoraires.ProductionThermique; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo->PaliersThermiquesDuPays[pays]; std::vector& PuissanceDisponibleEtCout = PaliersThermiquesDuPays.PuissanceDisponibleEtCout; @@ -88,26 +81,33 @@ void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO* pro for (int pdtHebdo = 0; pdtHebdo < NombreDePasDeTempsProblemeHebdo; pdtHebdo++) { - double ProductionThermiqueDuPalier - = ProductionThermique[pdtHebdo].ProductionThermiqueDuPalier[index]; + double ProductionThermiqueDuPalier = ProductionThermique[pdtHebdo] + .ProductionThermiqueDuPalier[index]; if (ProductionThermiqueDuPalier - eps_prodTherm > PuissanceMinDuPalierThermique[pdtHebdo]) - PuissanceMinDuPalierThermique[pdtHebdo] - = ProductionThermiqueDuPalier - eps_prodTherm; + { + PuissanceMinDuPalierThermique[pdtHebdo] = ProductionThermiqueDuPalier + - eps_prodTherm; + } if (ProductionThermiqueDuPalier + eps_prodTherm < PuissanceDisponibleDuPalierThermique[pdtHebdo]) - PuissanceDisponibleDuPalierThermique[pdtHebdo] - = ProductionThermiqueDuPalier + eps_prodTherm; + { + PuissanceDisponibleDuPalierThermique[pdtHebdo] = ProductionThermiqueDuPalier + + eps_prodTherm; + } - double NombreDeGroupesEnMarcheDuPalier - = ProductionThermique[pdtHebdo].NombreDeGroupesEnMarcheDuPalier[index]; + double NombreDeGroupesEnMarcheDuPalier = ProductionThermique[pdtHebdo] + .NombreDeGroupesEnMarcheDuPalier + [index]; if (NombreDeGroupesEnMarcheDuPalier - eps_nbGroupes > NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo]) - NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo] - = (int)ceil(NombreDeGroupesEnMarcheDuPalier - eps_nbGroupes); + { + NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo] = (int)ceil( + NombreDeGroupesEnMarcheDuPalier - eps_nbGroupes); + } } } else @@ -118,15 +118,14 @@ void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO* pro = PuissanceDisponibleEtCout[index].NombreMaxDeGroupesEnMarcheDuPalierThermique; std::vector& PuissanceDisponibleDuPalierThermique = PuissanceDisponibleEtCout[index].PuissanceDisponibleDuPalierThermique; - double pminDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.pminDUnGroupeDuPalierThermique[index]; - double PmaxDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.PmaxDUnGroupeDuPalierThermique[index]; + double pminDUnGroupeDuPalierThermique = PaliersThermiquesDuPays + .pminDUnGroupeDuPalierThermique[index]; + double PmaxDUnGroupeDuPalierThermique = PaliersThermiquesDuPays + .PmaxDUnGroupeDuPalierThermique[index]; for (int pdtHebdo = 0; pdtHebdo < NombreDePasDeTempsProblemeHebdo; pdtHebdo++) { - double X - = ProductionThermique[pdtHebdo].NombreDeGroupesEnMarcheDuPalier[index]; + double X = ProductionThermique[pdtHebdo].NombreDeGroupesEnMarcheDuPalier[index]; if (X > NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] + Eps) { printf( @@ -176,51 +175,67 @@ void OPT_AjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage(PROBLEME_HEBDO* pro NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo] = (int)ceil(X); } - OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( - problemeHebdo, NombreMinDeGroupesEnMarcheDuPalierThermique, pays, index); + if (!problemeHebdo->OptimisationAvecVariablesEntieres) + { + OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( + problemeHebdo, + NombreMinDeGroupesEnMarcheDuPalierThermique, + pays, + index); - for (int pdtHebdo = 0; pdtHebdo < NombreDePasDeTempsProblemeHebdo; pdtHebdo++) + for (int pdtHebdo = 0; pdtHebdo < NombreDePasDeTempsProblemeHebdo; pdtHebdo++) + { + if (NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] + < NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo]) + { + NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] + = NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo]; + } + + if (pminDUnGroupeDuPalierThermique + * NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] + > PuissanceDisponibleDuPalierThermique[pdtHebdo]) + { + PuissanceDisponibleDuPalierThermique[pdtHebdo] + = pminDUnGroupeDuPalierThermique + * NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo]; + } + } + } + else { - if (NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] - < NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo]) + for (int pdtHebdo = 0; pdtHebdo < NombreDePasDeTempsProblemeHebdo; pdtHebdo++) + { NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] = NombreMinDeGroupesEnMarcheDuPalierThermique[pdtHebdo]; - - if (pminDUnGroupeDuPalierThermique - * NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo] - > PuissanceDisponibleDuPalierThermique[pdtHebdo]) - PuissanceDisponibleDuPalierThermique[pdtHebdo] - = pminDUnGroupeDuPalierThermique - * NombreMaxDeGroupesEnMarcheDuPalierThermique[pdtHebdo]; + } } } } } - - return; } void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( PROBLEME_HEBDO* problemeHebdo, std::vector& NbMinOptDeGroupesEnMarche, int Pays, - int Index) + int index) { int NombreDePasDeTemps = problemeHebdo->NombreDePasDeTemps; - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[Pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo->PaliersThermiquesDuPays[Pays]; - const std::vector& NombreMaxDeGroupesEnMarcheDuPalierThermique - = PaliersThermiquesDuPays.PuissanceDisponibleEtCout[Index] + std::vector& NombreMaxDeGroupesEnMarcheDuPalierThermique + = PaliersThermiquesDuPays.PuissanceDisponibleEtCout[index] .NombreMaxDeGroupesEnMarcheDuPalierThermique; const int DureeMinimaleDeMarcheDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[Index]; + = PaliersThermiquesDuPays.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[index]; const int DureeMinimaleDArretDUnGroupeDuPalierThermique - = PaliersThermiquesDuPays.DureeMinimaleDArretDUnGroupeDuPalierThermique[Index]; + = PaliersThermiquesDuPays.DureeMinimaleDArretDUnGroupeDuPalierThermique[index]; - std::vector& ProductionThermique - = problemeHebdo->ResultatsHoraires[Pays].ProductionThermique; + std::vector& ProductionThermique = problemeHebdo + ->ResultatsHoraires[Pays] + .ProductionThermique; bool ResoudreLeProblemeLineaire = true; @@ -229,44 +244,46 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( int t1 = pdt; int t1moins1 = t1 - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTemps + t1moins1; + } if (NbMinOptDeGroupesEnMarche[t1] - NbMinOptDeGroupesEnMarche[t1moins1] < 0) { - ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[Index] = 0; - ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[Index] + ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[index] = NbMinOptDeGroupesEnMarche[t1moins1] - NbMinOptDeGroupesEnMarche[t1]; - ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[Index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[index] = 0; if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] < NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1]) { if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - < ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[Index]) + < ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[index]) { - ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[Index] + ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[index] = NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1]; } else { - ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[Index] - = ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[Index]; + ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[index] + = ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[index]; } } } else if (NbMinOptDeGroupesEnMarche[t1] - NbMinOptDeGroupesEnMarche[t1moins1] > 0) { - ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[Index] + ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[index] = NbMinOptDeGroupesEnMarche[t1] - NbMinOptDeGroupesEnMarche[t1moins1]; - ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[Index] = 0; - ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[Index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[index] = 0; } else { - ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[Index] = 0; - ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[Index] = 0; - ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[Index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[index] = 0; + ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[index] = 0; } } @@ -281,10 +298,12 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( t1 = k; if (k < 0) + { t1 = NombreDePasDeTemps + k; - SMarche - += ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[Index] - - ProductionThermique[t1].NombreDeGroupesQuiTombentEnPanneDuPalier[Index]; + } + SMarche += ProductionThermique[t1].NombreDeGroupesQuiDemarrentDuPalier[index] + - ProductionThermique[t1] + .NombreDeGroupesQuiTombentEnPanneDuPalier[index]; } if (NbMinOptDeGroupesEnMarche[t1] < SMarche) { @@ -296,7 +315,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( int t1 = pdt - DureeMinimaleDArretDUnGroupeDuPalierThermique; if (t1 < 0) + { t1 = NombreDePasDeTemps + t1; + } double SArret = NombreMaxDeGroupesEnMarcheDuPalierThermique[t1]; for (int k = pdt - DureeMinimaleDArretDUnGroupeDuPalierThermique + 1; k <= pdt; k++) @@ -304,10 +325,14 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( t1 = k; if (t1 < 0) + { t1 = NombreDePasDeTemps + t1; + } int t1moins1 = t1 - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTemps + t1moins1; + } if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] > 0) @@ -315,7 +340,7 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( SArret += NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1]; } - SArret -= ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[Index]; + SArret -= ProductionThermique[t1].NombreDeGroupesQuiSArretentDuPalier[index]; } if (NbMinOptDeGroupesEnMarche[t1] > SArret) { @@ -325,7 +350,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( } if (!ResoudreLeProblemeLineaire) + { return; + } int NombreDeVariables = 0; NombreDeVariables += NombreDePasDeTemps; @@ -362,14 +389,13 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( NbTermesMatrice += 4 * NombreDePasDeTemps; NbTermesMatrice += 2 * NombreDePasDeTemps; NbTermesMatrice += 1 * NombreDePasDeTemps; - NbTermesMatrice - += NombreDePasDeTemps * (1 + (2 * DureeMinimaleDeMarcheDUnGroupeDuPalierThermique)); + NbTermesMatrice += NombreDePasDeTemps + * (1 + (2 * DureeMinimaleDeMarcheDUnGroupeDuPalierThermique)); NbTermesMatrice += NombreDePasDeTemps * (1 + DureeMinimaleDArretDUnGroupeDuPalierThermique); std::vector IndicesColonnes(NbTermesMatrice); std::vector CoefficientsDeLaMatriceDesContraintes(NbTermesMatrice); - NombreDeVariables = 0; for (int pdt = 0; pdt < NombreDePasDeTemps; pdt++) { @@ -421,7 +447,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( int t1moins1 = pdt - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTemps + t1moins1; + } CoefficientsDeLaMatriceDesContraintes[NbTermesMatrice] = -1; IndicesColonnes[NbTermesMatrice] = NumeroDeVariableDeM[t1moins1]; NombreDeTermes++; @@ -464,7 +492,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( int t1 = pdt; t1moins1 = t1 - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTemps + t1moins1; + } Xmax[var] = 0; if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] @@ -485,7 +515,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( { int tmp = k; if (tmp < 0) + { tmp = NombreDePasDeTemps + tmp; + } CoefficientsDeLaMatriceDesContraintes[NbTermesMatrice] = -1; IndicesColonnes[NbTermesMatrice] = NumeroDeVariableDeMPlus[tmp]; @@ -515,7 +547,9 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( { int tmp = k; if (tmp < 0) + { tmp = NombreDePasDeTemps + tmp; + } CoefficientsDeLaMatriceDesContraintes[NbTermesMatrice] = 1; IndicesColonnes[NbTermesMatrice] = NumeroDeVariableDeMMoins[tmp]; NombreDeTermes++; @@ -526,24 +560,30 @@ void OPT_PbLineairePourAjusterLeNombreMinDeGroupesDemarresCoutsDeDemarrage( Sens[NombreDeContraintes] = '<'; t1 = pdt - DureeMinimaleDArretDUnGroupeDuPalierThermique; if (t1 < 0) + { t1 = NombreDePasDeTemps + t1; + } SecondMembre[NombreDeContraintes] = NombreMaxDeGroupesEnMarcheDuPalierThermique[t1]; for (int k = pdt - DureeMinimaleDArretDUnGroupeDuPalierThermique + 1; k <= pdt; k++) { t1 = k; if (t1 < 0) + { t1 = NombreDePasDeTemps + t1; + } t1moins1 = t1 - 1; if (t1moins1 < 0) + { t1moins1 = NombreDePasDeTemps + t1moins1; + } if (NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1] > 0) { - SecondMembre[NombreDeContraintes] - += NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] - - NombreMaxDeGroupesEnMarcheDuPalierThermique[t1moins1]; + SecondMembre[NombreDeContraintes] += NombreMaxDeGroupesEnMarcheDuPalierThermique[t1] + - NombreMaxDeGroupesEnMarcheDuPalierThermique + [t1moins1]; } } NombreDeContraintes++; diff --git a/src/solver/optimisation/opt_numero_de_jour_du_pas_de_temps.cpp b/src/solver/optimisation/opt_numero_de_jour_du_pas_de_temps.cpp index b8a220843a..122c3a36d2 100644 --- a/src/solver/optimisation/opt_numero_de_jour_du_pas_de_temps.cpp +++ b/src/solver/optimisation/opt_numero_de_jour_du_pas_de_temps.cpp @@ -1,41 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/simulation.h" void OPT_NumeroDeJourDuPasDeTemps(PROBLEME_HEBDO* problemeHebdo) { - problemeHebdo->NombreDeJours - = problemeHebdo->NombreDePasDeTemps / problemeHebdo->NombreDePasDeTempsDUneJournee; + problemeHebdo->NombreDeJours = problemeHebdo->NombreDePasDeTemps + / problemeHebdo->NombreDePasDeTempsDUneJournee; for (uint pdtHebdo = 0; pdtHebdo < problemeHebdo->NombreDePasDeTemps; pdtHebdo++) { double X = pdtHebdo / problemeHebdo->NombreDePasDeTempsDUneJournee; diff --git a/src/solver/optimisation/opt_optimisation_hebdo.cpp b/src/solver/optimisation/opt_optimisation_hebdo.cpp index a84f334942..0abed9ff13 100644 --- a/src/solver/optimisation/opt_optimisation_hebdo.cpp +++ b/src/solver/optimisation/opt_optimisation_hebdo.cpp @@ -1,39 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" -#include -#include +#include #include +#include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" extern "C" { @@ -48,11 +40,16 @@ using Antares::Solver::Optimization::OptimizationOptions; void OPT_OptimisationHebdomadaire(const OptimizationOptions& options, PROBLEME_HEBDO* pProblemeHebdo, const AdqPatchParams& adqPatchParams, - Solver::IResultWriter& writer) + Solver::IResultWriter& writer, + Solver::Simulation::ISimulationObserver& simulationObserver) { if (pProblemeHebdo->TypeDOptimisation == OPTIMISATION_LINEAIRE) { - if (!OPT_PilotageOptimisationLineaire(options, pProblemeHebdo, adqPatchParams, writer)) + if (!OPT_PilotageOptimisationLineaire(options, + pProblemeHebdo, + adqPatchParams, + writer, + simulationObserver)) { logs.error() << "Linear optimization failed"; throw UnfeasibleProblemError("Linear optimization failed"); @@ -69,7 +66,8 @@ void OPT_OptimisationHebdomadaire(const OptimizationOptions& options, } else { - throw FatalError("Bug: TypeDOptimisation, OPTIMISATION_LINEAIRE ou OPTIMISATION_QUADRATIQUE " - "non initialise"); + throw FatalError( + "Bug: TypeDOptimisation, OPTIMISATION_LINEAIRE ou OPTIMISATION_QUADRATIQUE " + "non initialise"); } } diff --git a/src/solver/optimisation/opt_optimisation_lineaire.cpp b/src/solver/optimisation/opt_optimisation_lineaire.cpp index ea64560372..b3ca1a3daa 100644 --- a/src/solver/optimisation/opt_optimisation_lineaire.cpp +++ b/src/solver/optimisation/opt_optimisation_lineaire.cpp @@ -1,36 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "sim_structure_probleme_economique.h" -#include "opt_fonctions.h" + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #include -#include "../utils/filename.h" - +#include "antares/solver/lps/LpsFromAntares.h" +#include "antares/solver/optimisation/HebdoProblemToLpsTranslator.h" +#include "antares/solver/optimisation/LinearProblemMatrix.h" +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" +#include "antares/solver/optimisation/opt_export_structure.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/solver/utils/filename.h" using namespace Antares; using namespace Yuni; using Antares::Solver::Optimization::OptimizationOptions; @@ -42,9 +40,13 @@ double OPT_ObjectiveFunctionResult(const PROBLEME_HEBDO* Probleme, const int optimizationNumber) { if (optimizationNumber == PREMIERE_OPTIMISATION) + { return Probleme->coutOptimalSolution1[NumeroDeLIntervalle]; + } else + { return Probleme->coutOptimalSolution2[NumeroDeLIntervalle]; + } } void OPT_EcrireResultatFonctionObjectiveAuFormatTXT( @@ -62,14 +64,29 @@ void OPT_EcrireResultatFonctionObjectiveAuFormatTXT( writer.addEntryFromBuffer(filename, buffer); } +namespace +{ +void notifyProblemHebdo(const PROBLEME_HEBDO* problemeHebdo, + int optimizationNumber, + Solver::Simulation::ISimulationObserver& simulationObserver, + const OptPeriodStringGenerator* optPeriodStringGenerator) +{ + simulationObserver.notifyHebdoProblem(*problemeHebdo, + optimizationNumber, + createMPSfilename(*optPeriodStringGenerator, + optimizationNumber)); +} +} // namespace + bool runWeeklyOptimization(const OptimizationOptions& options, - PROBLEME_HEBDO* problemeHebdo, - const AdqPatchParams& adqPatchParams, - Solver::IResultWriter& writer, - int optimizationNumber) + PROBLEME_HEBDO* problemeHebdo, + const AdqPatchParams& adqPatchParams, + Solver::IResultWriter& writer, + int optimizationNumber, + Solver::Simulation::ISimulationObserver& simulationObserver) { - const int NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsPourUneOptimisation; + const int NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsPourUneOptimisation; int DernierPdtDeLIntervalle; for (uint pdtHebdo = 0, numeroDeLIntervalle = 0; pdtHebdo < problemeHebdo->NombreDePasDeTemps; @@ -90,17 +107,23 @@ bool runWeeklyOptimization(const OptimizationOptions& options, numeroDeLIntervalle, optimizationNumber); - OPT_InitialiserLesCoutsLineaire( - problemeHebdo, PremierPdtDeLIntervalle, DernierPdtDeLIntervalle); + OPT_InitialiserLesCoutsLineaire(problemeHebdo, + PremierPdtDeLIntervalle, + DernierPdtDeLIntervalle); // An optimization period represents a sequence as - or --, // depending whether the optimization is daily or weekly. // These sequences are used when building the names of MPS or criterion files. - auto optPeriodStringGenerator - = createOptPeriodAsString(problemeHebdo->OptimisationAuPasHebdomadaire, - numeroDeLIntervalle, - problemeHebdo->weekInTheYear, - problemeHebdo->year); + auto optPeriodStringGenerator = createOptPeriodAsString( + problemeHebdo->OptimisationAuPasHebdomadaire, + numeroDeLIntervalle, + problemeHebdo->weekInTheYear, + problemeHebdo->year); + + notifyProblemHebdo(problemeHebdo, + optimizationNumber, + simulationObserver, + optPeriodStringGenerator.get()); if (!OPT_AppelDuSimplexe(options, problemeHebdo, @@ -108,15 +131,19 @@ bool runWeeklyOptimization(const OptimizationOptions& options, optimizationNumber, *optPeriodStringGenerator, writer)) + { return false; + } - if (problemeHebdo->ExportMPS != Data::mpsExportStatus::NO_EXPORT - || problemeHebdo->Expansion) + if (problemeHebdo->ExportMPS != Data::mpsExportStatus::NO_EXPORT) { - double optimalSolutionCost - = OPT_ObjectiveFunctionResult(problemeHebdo, numeroDeLIntervalle, optimizationNumber); - OPT_EcrireResultatFonctionObjectiveAuFormatTXT( - optimalSolutionCost, *optPeriodStringGenerator, optimizationNumber, writer); + double optimalSolutionCost = OPT_ObjectiveFunctionResult(problemeHebdo, + numeroDeLIntervalle, + optimizationNumber); + OPT_EcrireResultatFonctionObjectiveAuFormatTXT(optimalSolutionCost, + *optPeriodStringGenerator, + optimizationNumber, + writer); } } return true; @@ -133,18 +160,44 @@ void runThermalHeuristic(PROBLEME_HEBDO* problemeHebdo) OPT_CalculerLesPminThermiquesEnFonctionDeMUTetMDT(problemeHebdo); } } -} // namespace +void resizeProbleme(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + unsigned nombreDeVariables, + unsigned nombreDeContraintes) +{ + ProblemeAResoudre->CoutQuadratique.resize(nombreDeVariables); + ProblemeAResoudre->CoutLineaire.resize(nombreDeVariables); + ProblemeAResoudre->TypeDeVariable.resize(nombreDeVariables); + ProblemeAResoudre->Xmin.resize(nombreDeVariables); + ProblemeAResoudre->Xmax.resize(nombreDeVariables); + ProblemeAResoudre->X.resize(nombreDeVariables); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees.resize(nombreDeVariables); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits.resize(nombreDeVariables); + ProblemeAResoudre->PositionDeLaVariable.resize(nombreDeVariables); + ProblemeAResoudre->NomDesVariables.resize(nombreDeVariables); + ProblemeAResoudre->VariablesEntieres.resize(nombreDeVariables); + + ProblemeAResoudre->Sens.resize(nombreDeContraintes); + ProblemeAResoudre->IndicesDebutDeLigne.resize(nombreDeContraintes); + ProblemeAResoudre->NombreDeTermesDesLignes.resize(nombreDeContraintes); + ProblemeAResoudre->SecondMembre.resize(nombreDeContraintes); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsMarginaux.resize(nombreDeContraintes); + ProblemeAResoudre->CoutsMarginauxDesContraintes.resize(nombreDeContraintes); + ProblemeAResoudre->ComplementDeLaBase.resize(nombreDeContraintes); + ProblemeAResoudre->NomDesContraintes.resize(nombreDeContraintes); +} +} // namespace bool OPT_OptimisationLineaire(const OptimizationOptions& options, PROBLEME_HEBDO* problemeHebdo, const AdqPatchParams& adqPatchParams, - Solver::IResultWriter& writer) + Solver::IResultWriter& writer, + Solver::Simulation::ISimulationObserver& simulationObserver) { if (!problemeHebdo->OptimisationAuPasHebdomadaire) { - problemeHebdo->NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTempsDUneJournee; + problemeHebdo->NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTempsDUneJournee; } else { @@ -159,17 +212,38 @@ bool OPT_OptimisationLineaire(const OptimizationOptions& options, OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(problemeHebdo); - OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaire(problemeHebdo, writer); - - bool ret = runWeeklyOptimization( - options, problemeHebdo, adqPatchParams, writer, PREMIERE_OPTIMISATION); + auto builder_data = NewGetConstraintBuilderFromProblemHebdo(problemeHebdo); + ConstraintBuilder builder(builder_data); + LinearProblemMatrix linearProblemMatrix(problemeHebdo, builder); + linearProblemMatrix.Run(); + resizeProbleme(problemeHebdo->ProblemeAResoudre.get(), + problemeHebdo->ProblemeAResoudre->NombreDeVariables, + problemeHebdo->ProblemeAResoudre->NombreDeContraintes); + if (problemeHebdo->ExportStructure && problemeHebdo->firstWeekOfSimulation) + { + OPT_ExportStructures(problemeHebdo, writer); + } - if (ret && !problemeHebdo->Expansion) + bool ret = runWeeklyOptimization(options, + problemeHebdo, + adqPatchParams, + writer, + PREMIERE_OPTIMISATION, + simulationObserver); + + // We only need the 2nd optimization when NOT solving with integer variables + // We also skip the 2nd optimization in the hidden 'Expansion' mode + // and if the 1st one failed. + if (ret && !problemeHebdo->Expansion && !problemeHebdo->OptimisationAvecVariablesEntieres) { // We need to adjust some stuff before running the 2nd optimisation runThermalHeuristic(problemeHebdo); - return runWeeklyOptimization( - options, problemeHebdo, adqPatchParams, writer, DEUXIEME_OPTIMISATION); + return runWeeklyOptimization(options, + problemeHebdo, + adqPatchParams, + writer, + DEUXIEME_OPTIMISATION, + simulationObserver); } return ret; } diff --git a/src/solver/optimisation/opt_period_string_generator_base.h b/src/solver/optimisation/opt_period_string_generator_base.h deleted file mode 100644 index 2a5d2f2d12..0000000000 --- a/src/solver/optimisation/opt_period_string_generator_base.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include - -// --------------------------------------------- -// Optimization period as string : base class -// -------------------------------------------- -class OptPeriodStringGenerator -{ -public: - virtual std::string to_string() const = 0; - virtual ~OptPeriodStringGenerator() = default; -}; diff --git a/src/solver/optimisation/opt_pilotage_optimisation_lineaire.cpp b/src/solver/optimisation/opt_pilotage_optimisation_lineaire.cpp index 49a3a489b6..7d6bff0d80 100644 --- a/src/solver/optimisation/opt_pilotage_optimisation_lineaire.cpp +++ b/src/solver/optimisation/opt_pilotage_optimisation_lineaire.cpp @@ -1,43 +1,37 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/optimization-options/options.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" using Antares::Solver::Optimization::OptimizationOptions; bool OPT_PilotageOptimisationLineaire(const OptimizationOptions& options, PROBLEME_HEBDO* problemeHebdo, const AdqPatchParams& adqPatchParams, - Solver::IResultWriter& writer) + Solver::IResultWriter& writer, + Solver::Simulation::ISimulationObserver& simulationObserver) { if (!problemeHebdo->LeProblemeADejaEteInstancie) { @@ -58,8 +52,8 @@ bool OPT_PilotageOptimisationLineaire(const OptimizationOptions& options, } else { - problemeHebdo->NombreDePasDeTempsPourUneOptimisation - = problemeHebdo->NombreDePasDeTemps; + problemeHebdo->NombreDePasDeTempsPourUneOptimisation = problemeHebdo + ->NombreDePasDeTemps; } OPT_AllocDuProblemeAOptimiser(problemeHebdo); @@ -83,5 +77,9 @@ bool OPT_PilotageOptimisationLineaire(const OptimizationOptions& options, OPT_InitialiserNombreMinEtMaxDeGroupesCoutsDeDemarrage(problemeHebdo); } - return OPT_OptimisationLineaire(options, problemeHebdo, adqPatchParams, writer); + return OPT_OptimisationLineaire(options, + problemeHebdo, + adqPatchParams, + writer, + simulationObserver); } diff --git a/src/solver/optimisation/opt_pilotage_optimisation_quadratique.cpp b/src/solver/optimisation/opt_pilotage_optimisation_quadratique.cpp index b9b25318c8..4f2d37bf96 100644 --- a/src/solver/optimisation/opt_pilotage_optimisation_quadratique.cpp +++ b/src/solver/optimisation/opt_pilotage_optimisation_quadratique.cpp @@ -1,37 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include - -#include "../simulation/simulation.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include +#include "antares/solver/optimisation/QuadraticProblemMatrix.h" +#include "antares/solver/optimisation/constraints/constraint_builder_utils.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" extern "C" { #include "spx_fonctions.h" @@ -42,8 +35,9 @@ bool OPT_PilotageOptimisationQuadratique(PROBLEME_HEBDO* problemeHebdo) if (!problemeHebdo->LeProblemeADejaEteInstancie) { OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(problemeHebdo); - - OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(problemeHebdo); + auto builder_data = NewGetConstraintBuilderFromProblemHebdo(problemeHebdo); + ConstraintBuilder builder(builder_data); + QuadraticProblemMatrix(problemeHebdo, builder).Run(); problemeHebdo->LeProblemeADejaEteInstancie = true; } @@ -64,8 +58,8 @@ bool OPT_PilotageOptimisationQuadratique(PROBLEME_HEBDO* problemeHebdo) OPT_InitialiserLesCoutsQuadratiques(problemeHebdo, pdtHebdo); - result - = OPT_AppelDuSolveurQuadratique(problemeHebdo->ProblemeAResoudre.get(), pdtHebdo) && result; + result = OPT_AppelDuSolveurQuadratique(problemeHebdo->ProblemeAResoudre.get(), pdtHebdo) + && result; } } diff --git a/src/solver/optimisation/opt_rename_problem.cpp b/src/solver/optimisation/opt_rename_problem.cpp index 0d90030460..85edf581b8 100644 --- a/src/solver/optimisation/opt_rename_problem.cpp +++ b/src/solver/optimisation/opt_rename_problem.cpp @@ -1,11 +1,35 @@ -#include "opt_rename_problem.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/opt_rename_problem.h" + +#include #include const std::string HOUR("hour"); const std::string DAY("day"); const std::string WEEK("week"); -const std::map BindingConstraintTimeGranularity - = {{HOUR, "hourly"}, {DAY, "daily"}, {WEEK, "weekly"}}; +const std::map BindingConstraintTimeGranularity = {{HOUR, "hourly"}, + {DAY, "daily"}, + {WEEK, "weekly"}}; const std::string LINK("link"); const std::string AREA("area"); @@ -21,9 +45,10 @@ std::string BuildName(const std::string& name, void Namer::SetLinkElementName(unsigned int element, const std::string& elementType) { const auto location = origin_ + AREA_SEP + destination_; - targetUpdater_.UpdateTargetAtIndex( - BuildName(elementType, LocationIdentifier(location, LINK), TimeIdentifier(timeStep_, HOUR)), - element); + targetUpdater_.UpdateTargetAtIndex(BuildName(elementType, + LocationIdentifier(location, LINK), + TimeIdentifier(timeStep_, HOUR)), + element); } void Namer::SetAreaElementNameHour(unsigned int element, const std::string& elementType) @@ -40,10 +65,10 @@ void Namer::SetAreaElementName(unsigned int element, const std::string& elementType, const std::string& timeStepType) { - targetUpdater_.UpdateTargetAtIndex( - BuildName( - elementType, LocationIdentifier(area_, AREA), TimeIdentifier(timeStep_, timeStepType)), - element); + targetUpdater_.UpdateTargetAtIndex(BuildName(elementType, + LocationIdentifier(area_, AREA), + TimeIdentifier(timeStep_, timeStepType)), + element); } void VariableNamer::SetAreaVariableName(unsigned int variable, @@ -61,11 +86,13 @@ void Namer::SetThermalClusterElementName(unsigned int variable, const std::string& elementType, const std::string& clusterName) { - const auto location - = LocationIdentifier(area_, AREA) + SEPARATOR + "ThermalCluster" + "<" + clusterName + ">"; + const auto location = LocationIdentifier(area_, AREA) + SEPARATOR + "ThermalCluster" + "<" + + clusterName + ">"; - targetUpdater_.UpdateTargetAtIndex( - BuildName(elementType, location, TimeIdentifier(timeStep_, HOUR)), variable); + targetUpdater_.UpdateTargetAtIndex(BuildName(elementType, + location, + TimeIdentifier(timeStep_, HOUR)), + variable); } void VariableNamer::DispatchableProduction(unsigned int variable, const std::string& clusterName) @@ -129,8 +156,10 @@ void VariableNamer::SetShortTermStorageVariableName(unsigned int variable, { const auto location = LocationIdentifier(area_, AREA) + SEPARATOR + "ShortTermStorage" + "<" + shortTermStorageName + ">"; - targetUpdater_.UpdateTargetAtIndex( - BuildName(variableType, location, TimeIdentifier(timeStep_, HOUR)), variable); + targetUpdater_.UpdateTargetAtIndex(BuildName(variableType, + location, + TimeIdentifier(timeStep_, HOUR)), + variable); } void VariableNamer::ShortTermStorageInjection(unsigned int variable, @@ -215,6 +244,20 @@ void ConstraintNamer::FlowDissociation(unsigned int constraint, SetLinkElementName(constraint, "FlowDissociation"); } +void ConstraintNamer::CsrFlowDissociation(unsigned int constraint, + const std::string& origin, + const std::string& destination) +{ + origin_ = origin; + destination_ = destination; + SetLinkElementName(constraint, "CsrFlowDissociation"); +} + +void ConstraintNamer::CsrAreaBalance(unsigned int constraint) +{ + SetAreaElementNameHour(constraint, "CsrAreaBalance"); +} + void ConstraintNamer::AreaBalance(unsigned int constraint) { SetAreaElementNameHour(constraint, "AreaBalance"); @@ -279,9 +322,10 @@ void ConstraintNamer::nameWithTimeGranularity(unsigned int constraint, const std::string& name, const std::string& type) { - targetUpdater_.UpdateTargetAtIndex( - BuildName(name, BindingConstraintTimeGranularity.at(type), TimeIdentifier(timeStep_, type)), - constraint); + targetUpdater_.UpdateTargetAtIndex(BuildName(name, + BindingConstraintTimeGranularity.at(type), + TimeIdentifier(timeStep_, type)), + constraint); } void ConstraintNamer::NbUnitsOutageLessThanNbUnitsStop(unsigned int constraint, @@ -320,11 +364,11 @@ void ConstraintNamer::ConsistenceNODU(unsigned int constraint, const std::string void ConstraintNamer::ShortTermStorageLevel(unsigned int constraint, const std::string& name) { - targetUpdater_.UpdateTargetAtIndex( - BuildName("Level", - LocationIdentifier(area_, AREA) + SEPARATOR + "ShortTermStorage" + "<" + name + ">", - TimeIdentifier(timeStep_, HOUR)), - constraint); + targetUpdater_.UpdateTargetAtIndex(BuildName("Level", + LocationIdentifier(area_, AREA) + SEPARATOR + + "ShortTermStorage" + "<" + name + ">", + TimeIdentifier(timeStep_, HOUR)), + constraint); } void ConstraintNamer::BindingConstraintHour(unsigned int constraint, const std::string& name) @@ -332,6 +376,11 @@ void ConstraintNamer::BindingConstraintHour(unsigned int constraint, const std:: nameWithTimeGranularity(constraint, name, HOUR); } +void ConstraintNamer::CsrBindingConstraintHour(unsigned int constraint, const std::string& name) +{ + nameWithTimeGranularity(constraint, name, HOUR); +} + void ConstraintNamer::BindingConstraintDay(unsigned int constraint, const std::string& name) { nameWithTimeGranularity(constraint, name, DAY); diff --git a/src/solver/optimisation/opt_restaurer_les_donnees.cpp b/src/solver/optimisation/opt_restaurer_les_donnees.cpp index cda6795ce2..ec701b1202 100644 --- a/src/solver/optimisation/opt_restaurer_les_donnees.cpp +++ b/src/solver/optimisation/opt_restaurer_les_donnees.cpp @@ -1,39 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" - -void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) +void OPT_RestaurerLesDonnees(PROBLEME_HEBDO* problemeHebdo) { const std::vector& NumeroDeJourDuPasDeTemps = problemeHebdo->NumeroDeJourDuPasDeTemps; const int DernierPasDeTemps = problemeHebdo->NombreDePasDeTemps; @@ -43,7 +35,7 @@ void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) for (uint32_t interco = 0; interco < problemeHebdo->NombreDInterconnexions; interco++) { if (COUTS_DE_TRANSPORT& CoutDeTransport = problemeHebdo->CoutDeTransport[interco]; - CoutDeTransport.IntercoGereeAvecDesCouts) + CoutDeTransport.IntercoGereeAvecDesCouts) { CoutDeTransport.CoutDeTransportOrigineVersExtremite[pdt] = CoutDeTransport.CoutDeTransportOrigineVersExtremiteRef[pdt]; @@ -61,12 +53,17 @@ void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) = problemeHebdo->CaracteristiquesHydrauliques[pays]; if (!CaracteristiquesHydrauliques.PresenceDHydrauliqueModulable) + { continue; + } - CaracteristiquesHydrauliques.ContrainteDePmaxHydrauliqueHoraire[pdt] - = CaracteristiquesHydrauliques.ContrainteDePmaxHydrauliqueHoraireRef[pdt]; + double& hourlyPmax = CaracteristiquesHydrauliques + .ContrainteDePmaxHydrauliqueHoraire[pdt]; + hourlyPmax = CaracteristiquesHydrauliques.ContrainteDePmaxHydrauliqueHoraireRef[pdt]; if (CaracteristiquesHydrauliques.SansHeuristique) + { continue; + } int jour = NumeroDeJourDuPasDeTemps[pdt]; double PmaxHydEcretee = CaracteristiquesHydrauliques.CntEnergieH2OParJour[jour]; PmaxHydEcretee *= problemeHebdo->CoefficientEcretementPMaxHydraulique[pays]; @@ -76,21 +73,14 @@ void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) if (CaracteristiquesHydrauliques.PresenceDePompageModulable) { // Hydro generating power required to make use of energy stored from pumps - double PmaxHydUplift - = CaracteristiquesHydrauliques.ContrainteDePmaxPompageHoraire[pdt]; + double PmaxHydUplift = CaracteristiquesHydrauliques + .ContrainteDePmaxPompageHoraire[pdt]; PmaxHydUplift *= problemeHebdo->CoefficientEcretementPMaxHydraulique[pays]; - - if (PmaxHydEcretee < PmaxHydUplift) - PmaxHydEcretee = PmaxHydUplift; + PmaxHydEcretee = std::max(PmaxHydUplift, PmaxHydEcretee); } // The generating power allowance cannot exceed the maximum available generating power - if (PmaxHydEcretee - < CaracteristiquesHydrauliques.ContrainteDePmaxHydrauliqueHoraire[pdt]) - { - CaracteristiquesHydrauliques.ContrainteDePmaxHydrauliqueHoraire[pdt] - = PmaxHydEcretee; - } + hourlyPmax = std::min(PmaxHydEcretee, hourlyPmax); } } @@ -98,8 +88,8 @@ void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) { for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; for (int palier = 0; palier < PaliersThermiquesDuPays.NombreDePaliersThermiques; palier++) { @@ -115,8 +105,8 @@ void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) { for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const PALIERS_THERMIQUES& PaliersThermiquesDuPays - = problemeHebdo->PaliersThermiquesDuPays[pays]; + PALIERS_THERMIQUES& PaliersThermiquesDuPays = problemeHebdo + ->PaliersThermiquesDuPays[pays]; for (int palier = 0; palier < PaliersThermiquesDuPays.NombreDePaliersThermiques; palier++) { @@ -132,15 +122,12 @@ void OPT_RestaurerLesDonnees(const PROBLEME_HEBDO* problemeHebdo) = PuissanceDisponibleEtCout.PuissanceMinDuPalierThermique[pdt]; if (PuissanceDisponibleEtCout.PuissanceDisponibleDuPalierThermique[pdt] - > PuissanceDisponibleEtCout - .PuissanceDisponibleDuPalierThermiqueRef[pdt]) + > PuissanceDisponibleEtCout.PuissanceDisponibleDuPalierThermiqueRef[pdt]) { PuissanceDisponibleEtCout.PuissanceDisponibleDuPalierThermique[pdt] - = PuissanceDisponibleEtCout - .PuissanceDisponibleDuPalierThermiqueRef[pdt]; + = PuissanceDisponibleEtCout.PuissanceDisponibleDuPalierThermiqueRef[pdt]; PuissanceDisponibleEtCout.PuissanceMinDuPalierThermique[pdt] - = PuissanceDisponibleEtCout - .PuissanceDisponibleDuPalierThermiqueRef[pdt]; + = PuissanceDisponibleEtCout.PuissanceDisponibleDuPalierThermiqueRef[pdt]; } } } diff --git a/src/solver/optimisation/opt_structure_probleme_a_resoudre.h b/src/solver/optimisation/opt_structure_probleme_a_resoudre.h deleted file mode 100644 index b46b659140..0000000000 --- a/src/solver/optimisation/opt_structure_probleme_a_resoudre.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_OPTIMISATION_STRUCTURE_PROBLEME_A_RESOUDRE_H__ -#define __SOLVER_OPTIMISATION_STRUCTURE_PROBLEME_A_RESOUDRE_H__ - -#include -#include -#include "opt_constants.h" - -/*--------------------------------------------------------------------------------------*/ - -namespace Antares::Solver::Optimization { - -struct OptimizationOptions -{ - bool useOrtools; - std::string solverName; -}; - -} - -/* Le probleme a resoudre */ -struct PROBLEME_ANTARES_A_RESOUDRE -{ - /* La matrice des contraintes */ - int NombreDeVariables; - int NombreDeContraintes; /* Il est egal a : - ( NombreDePays contraintes de bilan - + NombreDePays contraintes de reserve - + NombreDeContraintesCouplantes - )* NombreDePasDeTempsDUneJournee - + NombreDePays contraintes de turbine */ - std::string Sens; - std::vector IndicesDebutDeLigne; - std::vector NombreDeTermesDesLignes; - std::vector CoefficientsDeLaMatriceDesContraintes; - std::vector IndicesColonnes; - int NombreDeTermesAllouesDansLaMatriceDesContraintes; - int IncrementDAllocationMatriceDesContraintes; - int NombreDeTermesDansLaMatriceDesContraintes; - /* Donnees variables de la matrice des contraintes */ - std::vector CoutQuadratique; - std::vector CoutLineaire; - std::vector TypeDeVariable; /* Indicateur du type de variable, il ne doit prendre que les suivantes - (voir le fichier spx_constantes_externes.h mais ne jamais utiliser les - valeurs explicites des constantes): VARIABLE_FIXE , - VARIABLE_BORNEE_DES_DEUX_COTES , - VARIABLE_BORNEE_INFERIEUREMENT , - VARIABLE_BORNEE_SUPERIEUREMENT , - VARIABLE_NON_BORNEE - */ - std::vector Xmin; - std::vector Xmax; - std::vector SecondMembre; - /* Tableau de pointeur a des doubles. Ce tableau est parallele a X, il permet - de renseigner directement les structures de description du reseau avec les - resultats contenus dans X */ - std::vector AdresseOuPlacerLaValeurDesVariablesOptimisees; - /* Resultat */ - std::vector X; - /* Tableau de pointeur a des doubles. Ce tableau est parallele a CoutsMarginauxDesContraintes, - il permet de renseigner directement les structures de description du reseau avec les - resultats sur les couts marginaux */ - std::vector AdresseOuPlacerLaValeurDesCoutsMarginaux; - std::vector CoutsMarginauxDesContraintes; - /* Tableau de pointeur a des doubles. Ce tableau est parallele a CoutsMarginauxDesContraintes, - il permet de renseigner directement les structures de description du reseau avec les - resultats sur les couts reduits */ - std::vector AdresseOuPlacerLaValeurDesCoutsReduits; - std::vector CoutsReduits; - /* En Entree ou en Sortie */ - int ExistenceDUneSolution; /* En sortie, vaut : - OUI_SPX s'il y a une solution, - NON_SPX s'il n'y a pas de solution admissible - SPX_ERREUR_INTERNE si probleme a l'execution (saturation memoire - par exemple), et dans ce cas il n'y a pas de solution - SPX_MATRICE_DE_BASE_SINGULIERE si on n'a pas pu construire de - matrice de base reguliere, et dans ce cas il n'y a pas de solution - */ - - std::vector ProblemesSpx; - - std::vector PositionDeLaVariable; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - std::vector ComplementDeLaBase; /* Vecteur a passer au Simplexe pour recuperer la base optimale */ - - /* Vecteurs de travail pour contruire la matrice des contraintes lineaires */ - std::vector Pi; - std::vector Colonne; - - /* Nommage des variables & contraintes */ - std::vector NomDesVariables; - std::vector NomDesContraintes; - - std::vector StatutDesVariables; - std::vector StatutDesContraintes; - -}; - -#endif /* __SOLVER_OPTIMISATION_STRUCTURE_PROBLEME_A_RESOUDRE_H__ */ diff --git a/src/solver/optimisation/opt_verification_presence_reserve_jmoins1.cpp b/src/solver/optimisation/opt_verification_presence_reserve_jmoins1.cpp index 85c92a5e94..52f3c92f19 100644 --- a/src/solver/optimisation/opt_verification_presence_reserve_jmoins1.cpp +++ b/src/solver/optimisation/opt_verification_presence_reserve_jmoins1.cpp @@ -1,37 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_structure_probleme_a_resoudre.h" - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_extern_variables_globales.h" - -#include "opt_fonctions.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/simulation.h" #include "spx_fonctions.h" @@ -43,8 +35,8 @@ void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO* problemeHebdo) for (uint32_t pays = 0; pays < problemeHebdo->NombreDePays; pays++) { - const std::vector& ReserveHoraireJMoins1 - = ReserveJMoins1[pays].ReserveHoraireJMoins1; + const std::vector& ReserveHoraireJMoins1 = ReserveJMoins1[pays] + .ReserveHoraireJMoins1; for (uint pdt = 0; pdt < problemeHebdo->NombreDePasDeTemps; pdt++) { if (fabs(ReserveHoraireJMoins1[pdt]) > ZERO_RESERVE_J_MOINS1) diff --git a/src/solver/optimisation/optim_post_process_list.cpp b/src/solver/optimisation/optim_post_process_list.cpp index 48fd5d21d5..a9eb38f7e8 100644 --- a/src/solver/optimisation/optim_post_process_list.cpp +++ b/src/solver/optimisation/optim_post_process_list.cpp @@ -1,5 +1,27 @@ -#include "optim_post_process_list.h" -#include "post_process_commands.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/optimisation/optim_post_process_list.h" + +#include "antares/solver/optimisation/post_process_commands.h" namespace Antares::Solver::Simulation { @@ -10,15 +32,18 @@ OptPostProcessList::OptPostProcessList(PROBLEME_HEBDO* problemeHebdo, SimplexOptimization splxOptimization, Calendar& calendar) - : - interfacePostProcessList(problemeHebdo, thread_number) + : + interfacePostProcessList(problemeHebdo, thread_number) { post_process_list.push_back( std::make_unique(problemeHebdo_, thread_number_, areas)); post_process_list.push_back( std::make_unique(problemeHebdo_, areas, false, false)); - post_process_list.push_back(std::make_unique( - problemeHebdo_, areas, sheddingPolicy, splxOptimization, thread_number)); + post_process_list.push_back(std::make_unique(problemeHebdo_, + areas, + sheddingPolicy, + splxOptimization, + thread_number)); post_process_list.push_back( std::make_unique(problemeHebdo_, areas, true, false)); post_process_list.push_back( diff --git a/src/solver/optimisation/optim_post_process_list.h b/src/solver/optimisation/optim_post_process_list.h deleted file mode 100644 index 54cc3b8ca6..0000000000 --- a/src/solver/optimisation/optim_post_process_list.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "../simulation/base_post_process.h" - -namespace Antares::Solver::Simulation -{ -class OptPostProcessList : public interfacePostProcessList -{ -public: - OptPostProcessList(PROBLEME_HEBDO* problemeHebdo, - uint thread_number, - AreaList& areas, - SheddingPolicy sheddingPolicy, - SimplexOptimization splxOptimization, - Calendar& calendar); - - virtual ~OptPostProcessList() = default; -}; - -} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/post_process_commands.cpp b/src/solver/optimisation/post_process_commands.cpp index a1206fe740..1b170ae353 100644 --- a/src/solver/optimisation/post_process_commands.cpp +++ b/src/solver/optimisation/post_process_commands.cpp @@ -1,20 +1,44 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ -#include "post_process_commands.h" -#include "../simulation/common-eco-adq.h" -#include "../simulation/adequacy_patch_runtime_data.h" -#include "adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h" -#include "adequacy_patch_csr/adq_patch_curtailment_sharing.h" +#include "antares/solver/optimisation/post_process_commands.h" + +#include "antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h" +#include "antares/solver/optimisation/adequacy_patch_local_matching/adequacy_patch_weekly_optimization.h" +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/common-eco-adq.h" namespace Antares::Solver::Simulation { const uint nbHoursInWeek = 168; + // ----------------------------- // Dispatchable Margin // ----------------------------- DispatchableMarginPostProcessCmd::DispatchableMarginPostProcessCmd(PROBLEME_HEBDO* problemeHebdo, unsigned int thread_number, - AreaList& areas) : - basePostProcessCommand(problemeHebdo), thread_number_(thread_number), area_list_(areas) + AreaList& areas): + basePostProcessCommand(problemeHebdo), + thread_number_(thread_number), + area_list_(areas) { } @@ -22,29 +46,28 @@ void DispatchableMarginPostProcessCmd::execute(const optRuntimeData& opt_runtime { unsigned int hourInYear = opt_runtime_data.hourInTheYear; unsigned int year = opt_runtime_data.year; - area_list_.each([&](Data::Area& area) { - double* dtgmrg = area.scratchpad[thread_number_].dispatchableGenerationMargin; - for (uint h = 0; h != nbHoursInWeek; ++h) - dtgmrg[h] = 0.; + area_list_.each( + [this, &hourInYear, &year](Data::Area& area) + { + double* dtgmrg = area.scratchpad[thread_number_].dispatchableGenerationMargin; + for (uint h = 0; h != nbHoursInWeek; ++h) + { + dtgmrg[h] = 0.; + } - if (not area.thermal.list.empty()) - { - auto& hourlyResults = problemeHebdo_->ResultatsHoraires[area.index]; + auto& hourlyResults = problemeHebdo_->ResultatsHoraires[area.index]; - auto end = area.thermal.list.end(); - for (auto i = area.thermal.list.begin(); i != end; ++i) - { - auto& cluster = *(i->second); - const auto& availableProduction = cluster.series->getAvailablePowerYearly(year); - for (uint h = 0; h != nbHoursInWeek; ++h) - { - double production = hourlyResults.ProductionThermique[h] - .ProductionThermiqueDuPalier[cluster.index]; - dtgmrg[h] += availableProduction[h + hourInYear] - production; - } - } - } - }); + for (const auto& cluster: area.thermal.list.each_enabled_and_not_mustrun()) + { + const auto& availableProduction = cluster->series.getColumn(year); + for (uint h = 0; h != nbHoursInWeek; ++h) + { + double production = hourlyResults.ProductionThermique[h] + .ProductionThermiqueDuPalier[cluster->index]; + dtgmrg[h] += availableProduction[h + hourInYear] - production; + } + } + }); } // ----------------------------- @@ -53,11 +76,11 @@ void DispatchableMarginPostProcessCmd::execute(const optRuntimeData& opt_runtime HydroLevelsUpdatePostProcessCmd::HydroLevelsUpdatePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, AreaList& areas, bool remixWasRun, - bool computeAnyway) : - basePostProcessCommand(problemeHebdo), - area_list_(areas), - remixWasRun_(remixWasRun), - computeAnyway_(computeAnyway) + bool computeAnyway): + basePostProcessCommand(problemeHebdo), + area_list_(areas), + remixWasRun_(remixWasRun), + computeAnyway_(computeAnyway) { } @@ -73,12 +96,12 @@ RemixHydroPostProcessCmd::RemixHydroPostProcessCmd(PROBLEME_HEBDO* problemeHebdo AreaList& areas, SheddingPolicy sheddingPolicy, SimplexOptimization simplexOptimization, - unsigned int thread_number) : - basePostProcessCommand(problemeHebdo), - area_list_(areas), - thread_number_(thread_number), - shedding_policy_(sheddingPolicy), - splx_optimization_(simplexOptimization) + unsigned int thread_number): + basePostProcessCommand(problemeHebdo), + area_list_(areas), + thread_number_(thread_number), + shedding_policy_(sheddingPolicy), + splx_optimization_(simplexOptimization) { } @@ -99,10 +122,14 @@ void RemixHydroPostProcessCmd::execute(const optRuntimeData& opt_runtime_data) using namespace Antares::Data::AdequacyPatch; DTGmarginForAdqPatchPostProcessCmd::DTGmarginForAdqPatchPostProcessCmd( + const AdqPatchParams& adqPatchParams, PROBLEME_HEBDO* problemeHebdo, AreaList& areas, - unsigned int thread_number) : - basePostProcessCommand(problemeHebdo), area_list_(areas), thread_number_(thread_number) + unsigned int thread_number): + basePostProcessCommand(problemeHebdo), + adqPatchParams_(adqPatchParams), + area_list_(areas), + thread_number_(thread_number) { } @@ -115,7 +142,9 @@ void DTGmarginForAdqPatchPostProcessCmd::execute(const optRuntimeData&) for (uint32_t Area = 0; Area < problemeHebdo_->NombreDePays; Area++) { if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[Area] != physicalAreaInsideAdqPatch) + { continue; + } for (uint hour = 0; hour < nbHoursInWeek; hour++) { @@ -130,14 +159,21 @@ void DTGmarginForAdqPatchPostProcessCmd::execute(const optRuntimeData&) // calculate DTG MRG CSR and adjust ENS if neccessary if (problemeHebdo_->adequacyPatchRuntimeData->wasCSRTriggeredAtAreaHour(Area, hour)) { - dtgMrgCsr = std::max(0.0, dtgMrg - ens); - ens = std::max(0.0, ens - dtgMrg); + if (adqPatchParams_.curtailmentSharing.recomputeDTGMRG) + { + dtgMrgCsr = std::max(0.0, dtgMrg - ens); + ens = std::max(0.0, ens - dtgMrg); + } // set MRG PRICE to value of unsupplied energy cost, if LOLD=1.0 (ENS>0.5) if (ens > 0.5) + { mrgCost = -area_list_[Area]->thermal.unsuppliedEnergyCost; + } } else + { dtgMrgCsr = dtgMrg; + } } } } @@ -149,8 +185,10 @@ void DTGmarginForAdqPatchPostProcessCmd::execute(const optRuntimeData&) InterpolateWaterValuePostProcessCmd::InterpolateWaterValuePostProcessCmd( PROBLEME_HEBDO* problemeHebdo, AreaList& areas, - const Date::Calendar& calendar) : - basePostProcessCommand(problemeHebdo), area_list_(areas), calendar_(calendar) + const Date::Calendar& calendar): + basePostProcessCommand(problemeHebdo), + area_list_(areas), + calendar_(calendar) { } @@ -166,8 +204,9 @@ void InterpolateWaterValuePostProcessCmd::execute(const optRuntimeData& opt_runt // HydroLevelsFinalUpdatePostProcessCmd HydroLevelsFinalUpdatePostProcessCmd::HydroLevelsFinalUpdatePostProcessCmd( PROBLEME_HEBDO* problemeHebdo, - AreaList& areas) : - basePostProcessCommand(problemeHebdo), area_list_(areas) + AreaList& areas): + basePostProcessCommand(problemeHebdo), + area_list_(areas) { } @@ -179,12 +218,13 @@ void HydroLevelsFinalUpdatePostProcessCmd::execute(const optRuntimeData&) // -------------------------------------- // Curtailment sharing for adq patch // -------------------------------------- -CurtailmentSharingPostProcessCmd::CurtailmentSharingPostProcessCmd(const AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - unsigned int thread_number) : +CurtailmentSharingPostProcessCmd::CurtailmentSharingPostProcessCmd( + const AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + AreaList& areas, + unsigned int thread_number): basePostProcessCommand(problemeHebdo), - area_list_(areas), + area_list_(areas), adqPatchParams_(adqPatchParams), thread_number_(thread_number) { @@ -200,7 +240,7 @@ void CurtailmentSharingPostProcessCmd::execute(const optRuntimeData& opt_runtime << ".Total LMR violation:" << totalLmrViolation; const std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(); HourlyCSRProblem hourlyCsrProblem(adqPatchParams_, problemeHebdo_); - for (int hourInWeek : hoursRequiringCurtailmentSharing) + for (int hourInWeek: hoursRequiringCurtailmentSharing) { logs.info() << "[adq-patch] CSR triggered for Year:" << year + 1 << " Hour:" << week * nbHoursInWeek + hourInWeek + 1; @@ -219,19 +259,20 @@ double CurtailmentSharingPostProcessCmd::calculateDensNewAndTotalLmrViolation() { for (uint hour = 0; hour < nbHoursInWeek; hour++) { - const auto [netPositionInit, densNew, totalNodeBalance] - = calculateAreaFlowBalance(problemeHebdo_, - adqPatchParams_.localMatching.setToZeroOutsideInsideLinks, - Area, - hour); + const auto [netPositionInit, densNew, totalNodeBalance] = calculateAreaFlowBalance( + problemeHebdo_, + adqPatchParams_.localMatching.setToZeroOutsideInsideLinks, + Area, + hour); // adjust densNew according to the new specification/request by ELIA /* DENS_new (node A) = max [ 0; ENS_init (node A) + net_position_init (node A) + ? flows (node 1 -> node A) - DTG.MRG(node A)] */ const auto& scratchpad = area_list_[Area]->scratchpad[thread_number_]; double dtgMrg = scratchpad.dispatchableGenerationMargin[hour]; // write down densNew values for all the hours - problemeHebdo_->ResultatsHoraires[Area].ValeursHorairesDENS[hour] - = std::max(0.0, densNew - dtgMrg); + problemeHebdo_->ResultatsHoraires[Area].ValeursHorairesDENS[hour] = std::max( + 0.0, + densNew - dtgMrg); ; // copy spilled Energy values into spilled Energy values after CSR problemeHebdo_->ResultatsHoraires[Area].ValeursHorairesSpilledEnergyAfterCSR[hour] @@ -239,10 +280,11 @@ double CurtailmentSharingPostProcessCmd::calculateDensNewAndTotalLmrViolation() .ValeursHorairesDeDefaillanceNegative[hour]; // check LMR violations totalLmrViolation += LmrViolationAreaHour( - problemeHebdo_, - totalNodeBalance, - adqPatchParams_.curtailmentSharing.thresholdDisplayViolations, - Area, hour); + problemeHebdo_, + totalNodeBalance, + adqPatchParams_.curtailmentSharing.thresholdDisplayViolations, + Area, + hour); } } } @@ -279,10 +321,12 @@ std::vector CurtailmentSharingPostProcessCmd::calculateENSoverAllAreasFo if (problemeHebdo_->adequacyPatchRuntimeData->areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - const std::vector& ENS - = problemeHebdo_->ResultatsHoraires[area].ValeursHorairesDeDefaillancePositive; + const std::vector& ENS = problemeHebdo_->ResultatsHoraires[area] + .ValeursHorairesDeDefaillancePositive; for (uint h = 0; h < nbHoursInWeek; ++h) + { sumENS[h] += ENS[h]; + } } } return sumENS; diff --git a/src/solver/optimisation/post_process_commands.h b/src/solver/optimisation/post_process_commands.h deleted file mode 100644 index d04daf02ce..0000000000 --- a/src/solver/optimisation/post_process_commands.h +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once - -#include "../simulation/base_post_process.h" - -namespace Antares::Solver::Simulation -{ -class DispatchableMarginPostProcessCmd : public basePostProcessCommand -{ -public: - DispatchableMarginPostProcessCmd(PROBLEME_HEBDO* problemeHebdo, - unsigned int thread_number, - AreaList& areas); - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - unsigned int thread_number_ = 0; - const AreaList& area_list_; -}; - -class HydroLevelsUpdatePostProcessCmd : public basePostProcessCommand -{ -public: - HydroLevelsUpdatePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - bool remixWasRun, - bool computeAnyway); - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - const AreaList& area_list_; - bool remixWasRun_ = false; - bool computeAnyway_ = false; -}; - -class RemixHydroPostProcessCmd : public basePostProcessCommand -{ -public: - RemixHydroPostProcessCmd(PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - SheddingPolicy sheddingPolicy, - SimplexOptimization simplexOptimization, - unsigned int thread_number); - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - const AreaList& area_list_; - unsigned int thread_number_ = 0; - SheddingPolicy shedding_policy_; - SimplexOptimization splx_optimization_; -}; - -class DTGmarginForAdqPatchPostProcessCmd : public basePostProcessCommand -{ -public: - DTGmarginForAdqPatchPostProcessCmd(PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - unsigned int thread_number); - - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - const AreaList& area_list_; - unsigned int thread_number_ = 0; -}; - -class InterpolateWaterValuePostProcessCmd : public basePostProcessCommand -{ -public: - InterpolateWaterValuePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - const Date::Calendar& calendar); - - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - const AreaList& area_list_; - const Date::Calendar& calendar_; -}; - -class HydroLevelsFinalUpdatePostProcessCmd : public basePostProcessCommand -{ -public: - HydroLevelsFinalUpdatePostProcessCmd(PROBLEME_HEBDO* problemeHebdo, AreaList& areas); - - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - const AreaList& area_list_; -}; - -class CurtailmentSharingPostProcessCmd : public basePostProcessCommand -{ - using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; -public: - CurtailmentSharingPostProcessCmd(const AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemeHebdo, - AreaList& areas, - unsigned int thread_number); - - void execute(const optRuntimeData& opt_runtime_data) override; - -private: - double calculateDensNewAndTotalLmrViolation(); - std::vector calculateENSoverAllAreasForEachHour() const; - std::set identifyHoursForCurtailmentSharing(const std::vector& sumENS) const; - std::set getHoursRequiringCurtailmentSharing() const; - - const AreaList& area_list_; - const AdqPatchParams& adqPatchParams_; - unsigned int thread_number_ = 0; -}; - -} // namespace Antares::Solver::Simulation diff --git a/src/solver/optimisation/variables/VariableManagement.cpp b/src/solver/optimisation/variables/VariableManagement.cpp new file mode 100644 index 0000000000..6187670c97 --- /dev/null +++ b/src/solver/optimisation/variables/VariableManagement.cpp @@ -0,0 +1,204 @@ +#include "VariableManagement.h" + +using namespace VariableManagement; + +VariableManager::VariableManager( + std::vector& CorrespondanceVarNativesVarOptim, + std::vector& NumeroDeVariableStockFinal, + std::vector>& NumeroDeVariableDeTrancheDeStock, + const int32_t& NombreDePasDeTempsPourUneOptimisation): + CorrespondanceVarNativesVarOptim_(CorrespondanceVarNativesVarOptim), + NumeroDeVariableStockFinal_(NumeroDeVariableStockFinal), + NumeroDeVariableDeTrancheDeStock_(NumeroDeVariableDeTrancheDeStock), + NombreDePasDeTempsPourUneOptimisation_(NombreDePasDeTempsPourUneOptimisation) +{ +} + +int VariableManager::GetShiftedTimeStep(int offset, int delta, unsigned int hourInWeek) const +{ + int pdt = hourInWeek + offset; + const int nbTimeSteps = NombreDePasDeTempsPourUneOptimisation_; + + if (offset != 0) + { + if (offset >= 0) + { + pdt = pdt % nbTimeSteps; + } + else + { + pdt = (pdt + delta) % nbTimeSteps; + } + } + return pdt; +} + +int& VariableManager::DispatchableProduction(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariableDuPalierThermique[index]; +} + +int& VariableManager::NumberOfDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt] + .NumeroDeVariableDuNombreDeGroupesEnMarcheDuPalierThermique[index]; +} + +int& VariableManager::NumberStoppingDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt] + .NumeroDeVariableDuNombreDeGroupesQuiSArretentDuPalierThermique[index]; +} + +int& VariableManager::NumberStartingDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt] + .NumeroDeVariableDuNombreDeGroupesQuiDemarrentDuPalierThermique[index]; +} + +int& VariableManager::NumberBreakingDownDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt] + .NumeroDeVariableDuNombreDeGroupesQuiTombentEnPanneDuPalierThermique[index]; +} + +int& VariableManager::NTCDirect(unsigned int index, unsigned int hourInWeek, int offset, int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariableDeLInterconnexion[index]; +} + +int& VariableManager::IntercoDirectCost(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt] + .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[index]; +} + +int& VariableManager::IntercoIndirectCost(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt] + .NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[index]; +} + +int& VariableManager::ShortTermStorageInjection(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].SIM_ShortTermStorage.InjectionVariable[index]; +} + +int& VariableManager::ShortTermStorageWithdrawal(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].SIM_ShortTermStorage.WithdrawalVariable[index]; +} + +int& VariableManager::ShortTermStorageLevel(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].SIM_ShortTermStorage.LevelVariable[index]; +} + +int& VariableManager::HydProd(unsigned int index, unsigned int hourInWeek, int offset, int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariablesDeLaProdHyd[index]; +} + +int& VariableManager::HydProdDown(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariablesVariationHydALaBaisse[index]; +} + +int& VariableManager::HydProdUp(unsigned int index, unsigned int hourInWeek, int offset, int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariablesVariationHydALaHausse[index]; +} + +int& VariableManager::Pumping(unsigned int index, unsigned int hourInWeek, int offset, int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariablesDePompage[index]; +} + +int& VariableManager::HydroLevel(unsigned int index, unsigned int hourInWeek, int offset, int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariablesDeNiveau[index]; +} + +int& VariableManager::Overflow(unsigned int index, unsigned int hourInWeek, int offset, int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariablesDeDebordement[index]; +} + +int& VariableManager::FinalStorage(unsigned int index) +{ + return NumeroDeVariableStockFinal_[index]; +} + +int& VariableManager::LayerStorage(unsigned area, unsigned layer) +{ + return NumeroDeVariableDeTrancheDeStock_[area][layer]; +} + +int& VariableManager::PositiveUnsuppliedEnergy(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariableDefaillancePositive[index]; +} + +int& VariableManager::NegativeUnsuppliedEnergy(unsigned int index, + unsigned int hourInWeek, + int offset, + int delta) +{ + auto pdt = GetShiftedTimeStep(offset, delta, hourInWeek); + return CorrespondanceVarNativesVarOptim_[pdt].NumeroDeVariableDefaillanceNegative[index]; +} diff --git a/src/solver/optimisation/variables/VariableManagement.h b/src/solver/optimisation/variables/VariableManagement.h new file mode 100644 index 0000000000..1c3144aa0a --- /dev/null +++ b/src/solver/optimisation/variables/VariableManagement.h @@ -0,0 +1,105 @@ +#pragma once + +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace VariableManagement +{ + +/*! +Factory class that hold variables indices +*/ +class VariableManager +{ +public: + VariableManager(std::vector& CorrespondanceVarNativesVarOptim, + std::vector& NumeroDeVariableStockFinal, + std::vector>& NumeroDeVariableDeTrancheDeStock, + const int32_t& NombreDePasDeTempsPourUneOptimisation); + + int& DispatchableProduction(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& NumberOfDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& NumberStoppingDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + int& NumberStartingDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& NumberBreakingDownDispatchableUnits(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& NTCDirect(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& IntercoDirectCost(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& IntercoIndirectCost(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& ShortTermStorageInjection(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& ShortTermStorageWithdrawal(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& ShortTermStorageLevel(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& HydProd(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& HydProdDown(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& HydProdUp(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& Pumping(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& HydroLevel(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& Overflow(unsigned int index, unsigned int hourInWeek, int offset = 0, int delta = 0); + + int& FinalStorage(unsigned int index); + + int& LayerStorage(unsigned area, unsigned layer); + + int& PositiveUnsuppliedEnergy(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + + int& NegativeUnsuppliedEnergy(unsigned int index, + unsigned int hourInWeek, + int offset = 0, + int delta = 0); + +private: + std::vector& CorrespondanceVarNativesVarOptim_; + std::vector& NumeroDeVariableStockFinal_; + std::vector>& NumeroDeVariableDeTrancheDeStock_; + const int32_t& NombreDePasDeTempsPourUneOptimisation_; + int GetShiftedTimeStep(int offset, int delta, unsigned int hourInWeek) const; +}; + +} // namespace VariableManagement diff --git a/src/solver/optimisation/variables/VariableManagerUtils.cpp b/src/solver/optimisation/variables/VariableManagerUtils.cpp new file mode 100644 index 0000000000..e884946614 --- /dev/null +++ b/src/solver/optimisation/variables/VariableManagerUtils.cpp @@ -0,0 +1,10 @@ +#include "VariableManagerUtils.h" + +VariableManagement::VariableManager VariableManagerFromProblemHebdo(PROBLEME_HEBDO* problemeHebdo) +{ + return VariableManagement::VariableManager( + problemeHebdo->CorrespondanceVarNativesVarOptim, + problemeHebdo->NumeroDeVariableStockFinal, + problemeHebdo->NumeroDeVariableDeTrancheDeStock, + problemeHebdo->NombreDePasDeTempsPourUneOptimisation); +} diff --git a/src/solver/optimisation/variables/VariableManagerUtils.h b/src/solver/optimisation/variables/VariableManagerUtils.h new file mode 100644 index 0000000000..1597fac34b --- /dev/null +++ b/src/solver/optimisation/variables/VariableManagerUtils.h @@ -0,0 +1,5 @@ +#pragma once + +#include "VariableManagement.h" + +VariableManagement::VariableManager VariableManagerFromProblemHebdo(PROBLEME_HEBDO* problemeHebdo); diff --git a/src/solver/optimisation/weekly_optimization.cpp b/src/solver/optimisation/weekly_optimization.cpp index 07a3f64764..8f36d762d2 100644 --- a/src/solver/optimisation/weekly_optimization.cpp +++ b/src/solver/optimisation/weekly_optimization.cpp @@ -1,47 +1,53 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ -#include "weekly_optimization.h" -#include "opt_fonctions.h" +#include "antares/solver/optimisation/weekly_optimization.h" + +#include "antares/solver/optimisation/opt_fonctions.h" namespace Antares::Solver::Optimization { -DefaultWeeklyOptimization::DefaultWeeklyOptimization(const OptimizationOptions& options, - PROBLEME_HEBDO* problemeHebdo, - AdqPatchParams& adqPatchParams, - uint thread_number, - IResultWriter& writer) : - WeeklyOptimization(options, problemeHebdo, adqPatchParams, thread_number, writer) +DefaultWeeklyOptimization::DefaultWeeklyOptimization( + const OptimizationOptions& options, + PROBLEME_HEBDO* problemeHebdo, + AdqPatchParams& adqPatchParams, + uint thread_number, + IResultWriter& writer, + Simulation::ISimulationObserver& simulationObserver): + WeeklyOptimization(options, + problemeHebdo, + adqPatchParams, + thread_number, + writer, + simulationObserver) { } -void DefaultWeeklyOptimization::solve(uint, int) +void DefaultWeeklyOptimization::solve() { - OPT_OptimisationHebdomadaire(options_, problemeHebdo_, adqPatchParams_, writer_); + OPT_OptimisationHebdomadaire(options_, + problemeHebdo_, + adqPatchParams_, + writer_, + simulationObserver_.get()); } } // namespace Antares::Solver::Optimization diff --git a/src/solver/optimisation/weekly_optimization.h b/src/solver/optimisation/weekly_optimization.h deleted file mode 100644 index 0849f7068d..0000000000 --- a/src/solver/optimisation/weekly_optimization.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include "base_weekly_optimization.h" -#include "../simulation/sim_structure_probleme_economique.h" - -namespace Antares::Solver::Optimization -{ -class DefaultWeeklyOptimization : public WeeklyOptimization -{ -public: - explicit DefaultWeeklyOptimization(const OptimizationOptions& options, - PROBLEME_HEBDO* problemeHebdo, - Antares::Data::AdequacyPatch::AdqPatchParams&, - uint numSpace, - IResultWriter& writer); - ~DefaultWeeklyOptimization() override = default; - void solve(uint, int) override; -}; -} // namespace Antares::Solver::Optimization diff --git a/src/solver/signal-handling/CMakeLists.txt b/src/solver/signal-handling/CMakeLists.txt new file mode 100644 index 0000000000..8b41212625 --- /dev/null +++ b/src/solver/signal-handling/CMakeLists.txt @@ -0,0 +1,33 @@ +set(PROJ signal-handling) +set(HEADERS + include/antares/${PROJ}/common.h + include/antares/${PROJ}/public.h +) +set(SRC_SIGNAL + ${HEADERS} + common.cpp + linux.cpp + windows.cpp +) +source_group("misc\\${PROJ}" FILES ${SRC_SIGNAL}) + +add_library(${PROJ} ${SRC_SIGNAL}) +add_library(Antares::${PROJ} ALIAS ${PROJ}) + +target_link_libraries(${PROJ} + PRIVATE + yuni-static-core + Antares::study + PUBLIC + Antares::result_writer + Antares::memory +) + +target_include_directories(${PROJ} + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) \ No newline at end of file diff --git a/src/solver/signal-handling/common.cpp b/src/solver/signal-handling/common.cpp index a708c79d86..e1932d3e96 100644 --- a/src/solver/signal-handling/common.cpp +++ b/src/solver/signal-handling/common.cpp @@ -1,10 +1,32 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/signal-handling/common.h" + #include #include -#include "common.h" using namespace Antares; -namespace Antares::Solver { +namespace Antares::Solver +{ // weak_ptr because the lifetime must not be managed by this feature. // If the study lifetime ends before we receive a signal, we shoud just do @@ -16,13 +38,18 @@ void setApplicationResultWriter(std::weak_ptr writer) APPLICATION_WRITER = writer; } -} +} // namespace Antares::Solver -namespace { -void finalizeWrite() { - if (auto writer = Antares::Solver::APPLICATION_WRITER.lock()) { +namespace +{ +void finalizeWrite() +{ + if (auto writer = Antares::Solver::APPLICATION_WRITER.lock()) + { writer->finalize(true); - } else { + } + else + { logs.warning() << "Could not finalize write: invalid writer"; exit(EXIT_FAILURE); } @@ -30,7 +57,7 @@ void finalizeWrite() { exit(EXIT_SUCCESS); } -} +} // namespace void signalCtrl_term(int) { diff --git a/src/solver/signal-handling/common.h b/src/solver/signal-handling/common.h deleted file mode 100644 index 1c4f096646..0000000000 --- a/src/solver/signal-handling/common.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include - -void signalCtrl_term(int); -void signalCtrl_int(int); - -namespace Antares::Solver { -/*! - * Defines the provided writer as the unique writer managed by the running application. - */ -void setApplicationResultWriter(std::weak_ptr writer); - -} diff --git a/src/solver/signal-handling/include/antares/signal-handling/common.h b/src/solver/signal-handling/include/antares/signal-handling/common.h new file mode 100644 index 0000000000..72062c8a3d --- /dev/null +++ b/src/solver/signal-handling/include/antares/signal-handling/common.h @@ -0,0 +1,38 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include + +#include + +void signalCtrl_term(int); +void signalCtrl_int(int); + +namespace Antares::Solver +{ +/*! + * Defines the provided writer as the unique writer managed by the running application. + */ +void setApplicationResultWriter(std::weak_ptr writer); + +} // namespace Antares::Solver diff --git a/src/solver/signal-handling/include/antares/signal-handling/public.h b/src/solver/signal-handling/include/antares/signal-handling/public.h new file mode 100644 index 0000000000..8689eaa86e --- /dev/null +++ b/src/solver/signal-handling/include/antares/signal-handling/public.h @@ -0,0 +1,31 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include + +#include "antares/writer/i_writer.h" + +namespace Antares::Solver +{ +void initializeSignalHandlers(std::weak_ptr writer); +} diff --git a/src/solver/signal-handling/linux.cpp b/src/solver/signal-handling/linux.cpp index 16ace73582..385a853168 100644 --- a/src/solver/signal-handling/linux.cpp +++ b/src/solver/signal-handling/linux.cpp @@ -1,8 +1,28 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef YUNI_OS_WINDOWS #include -#include "common.h" -#include "public.h" +#include "antares/signal-handling/common.h" +#include "antares/signal-handling/public.h" namespace Antares::Solver { diff --git a/src/solver/signal-handling/public.h b/src/solver/signal-handling/public.h deleted file mode 100644 index d1cbf36688..0000000000 --- a/src/solver/signal-handling/public.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include - -namespace Antares::Solver -{ -void initializeSignalHandlers(std::weak_ptr writer); -} diff --git a/src/solver/signal-handling/windows.cpp b/src/solver/signal-handling/windows.cpp index fa4bbdd104..fc93af13a6 100644 --- a/src/solver/signal-handling/windows.cpp +++ b/src/solver/signal-handling/windows.cpp @@ -1,8 +1,29 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifdef YUNI_OS_WINDOWS #include -#include "common.h" + #include "../application.h" +#include "common.h" BOOL WINAPI ConsoleHandler(DWORD dwType) { diff --git a/src/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h b/src/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h deleted file mode 100644 index 36b20d28fb..0000000000 --- a/src/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h +++ /dev/null @@ -1,23 +0,0 @@ -// -// Created by marechaljas on 17/03/23. -// - -#pragma once - -#include -#include "ITimeSeriesNumbersWriter.h" -#include -#include "antares/study/binding_constraint/BindingConstraintsRepository.h" - -namespace Antares::Solver::Simulation { -class BindingConstraintsTimeSeriesNumbersWriter: public ITimeSeriesNumbersWriter { - -public: - explicit BindingConstraintsTimeSeriesNumbersWriter(IResultWriter& resultWriter); - BindingConstraintsTimeSeriesNumbersWriter() = default; - void write(const Data::BindingConstraintGroupRepository &bindingConstraintGroupRepository) override; - -private: - IResultWriter& writer_; -}; -} // Simulation diff --git a/src/solver/simulation/CMakeLists.txt b/src/solver/simulation/CMakeLists.txt index 1e95d30615..fbfeb17f6a 100644 --- a/src/solver/simulation/CMakeLists.txt +++ b/src/solver/simulation/CMakeLists.txt @@ -2,65 +2,86 @@ # Simulation # set(SRC_SIMULATION - sim_alloc_probleme_hebdo.cpp - sim_alloc_probleme_hebdo.h - sim_allocation_tableaux.cpp - sim_calcul_economique.cpp - sim_extern_variables_globales.h - sim_structure_donnees.h - sim_structure_probleme_economique.h - sim_variables_globales.cpp - sim_constants.h - sim_spread_generator.h + sim_alloc_probleme_hebdo.cpp + include/antares/solver/simulation/sim_alloc_probleme_hebdo.h + sim_allocation_tableaux.cpp + sim_calcul_economique.cpp + include/antares/solver/simulation/sim_extern_variables_globales.h + include/antares/solver/simulation/sim_structure_donnees.h + include/antares/solver/simulation/sim_structure_probleme_economique.h + sim_variables_globales.cpp + include/antares/solver/simulation/sim_constants.h + include/antares/solver/simulation/sim_spread_generator.h sim_spread_generator.cpp - simulation.h - solver.h - solver.hxx - timeseries-numbers.h - timeseries-numbers.cpp - apply-scenario.h - apply-scenario.cpp + include/antares/solver/simulation/simulation.h + include/antares/solver/simulation/solver.h + include/antares/solver/simulation/solver.hxx + include/antares/solver/simulation/timeseries-numbers.h + timeseries-numbers.cpp + include/antares/solver/simulation/apply-scenario.h + apply-scenario.cpp - # Solver - solver.utils.h - solver.h - solver.hxx - solver.data.h - solver.data.cpp - common-eco-adq.h - common-eco-adq.cpp - common-hydro-remix.cpp - common-hydro-levels.cpp - adequacy.h - adequacy.cpp - economy.h - economy.cpp - base_post_process.h - base_post_process.cpp - opt_time_writer.h - opt_time_writer.cpp - adequacy_patch_runtime_data.h - adequacy_patch_runtime_data.cpp - ITimeSeriesNumbersWriter.h - TimeSeriesNumbersWriter.cpp - BindingConstraintsTimeSeriesNumbersWriter.h) + # Solver + include/antares/solver/simulation/solver_utils.h + solver_utils.cpp + include/antares/solver/simulation/solver.h + include/antares/solver/simulation/solver.hxx + include/antares/solver/simulation/solver.data.h + solver.data.cpp + include/antares/solver/simulation/common-eco-adq.h + common-eco-adq.cpp + common-hydro-remix.cpp + common-hydro-levels.cpp + include/antares/solver/simulation/adequacy.h + adequacy.cpp + include/antares/solver/simulation/economy.h + economy.cpp + include/antares/solver/simulation/base_post_process.h + base_post_process.cpp + include/antares/solver/simulation/opt_time_writer.h + opt_time_writer.cpp + include/antares/solver/simulation/adequacy_patch_runtime_data.h + adequacy_patch_runtime_data.cpp + include/antares/solver/simulation/ITimeSeriesNumbersWriter.h + TimeSeriesNumbersWriter.cpp + include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h + include/antares/solver/simulation/ISimulationObserver.h + economy_mode.cpp + adequacy_mode.cpp + include/antares/solver/simulation/economy_mode.h + include/antares/solver/simulation/adequacy_mode.h +) source_group("simulation" FILES ${SRC_SIMULATION}) # # --- Library VARIABLES --- # -add_library(antares-solver-simulation - ${SRC_SIMULATION} ) +add_library(antares-solver-simulation) +target_sources(antares-solver-simulation + PRIVATE + ${SRC_SIMULATION}) + +target_include_directories(antares-solver-simulation + PUBLIC + $ +) -target_include_directories(antares-solver-simulation PUBLIC - ${CMAKE_SOURCE_DIR}/solver/simulation) +target_link_libraries(antares-solver-simulation + PUBLIC + Antares::infoCollection + yuni-static-core + Antares::study + Antares::result_writer + Antares::concurrency + Antares::solverUtils + Antares::misc + model_antares + antares-solver-hydro + antares-solver-variable + antares-solver-ts-generator +) -target_link_libraries(antares-solver-simulation PRIVATE - Antares::infoCollection - PUBLIC - yuni-static-core - Antares::study - Antares::result_writer - Antares::concurrency +install(DIRECTORY include/antares + DESTINATION "include" ) diff --git a/src/solver/simulation/ITimeSeriesNumbersWriter.h b/src/solver/simulation/ITimeSeriesNumbersWriter.h deleted file mode 100644 index 066f8a8c50..0000000000 --- a/src/solver/simulation/ITimeSeriesNumbersWriter.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Created by marechaljas on 17/03/23. -// - -#pragma once -#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" - -namespace Antares::Solver::Simulation { -class ITimeSeriesNumbersWriter { - -public: - virtual ~ITimeSeriesNumbersWriter() = default; - virtual void write(const Data::BindingConstraintGroupRepository& list) = 0; -}; -} \ No newline at end of file diff --git a/src/solver/simulation/TimeSeriesNumbersWriter.cpp b/src/solver/simulation/TimeSeriesNumbersWriter.cpp index 28882ef5fb..31016bbc49 100644 --- a/src/solver/simulation/TimeSeriesNumbersWriter.cpp +++ b/src/solver/simulation/TimeSeriesNumbersWriter.cpp @@ -1,58 +1,66 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ // // Created by marechaljas on 17/03/23. // -#include "BindingConstraintsTimeSeriesNumbersWriter.h" -#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" #include #include #include -namespace Antares::Solver::Simulation { -BindingConstraintsTimeSeriesNumbersWriter::BindingConstraintsTimeSeriesNumbersWriter(IResultWriter& writer) -: writer_(writer) -{ - -} +#include "antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h" +#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" -namespace // anonymous +namespace Antares::Solver::Simulation { - struct TSNumbersPredicate - { - uint32_t operator()(uint32_t value) const - { - return value + 1; - } - }; -} // anonymous namespace +BindingConstraintsTimeSeriesNumbersWriter::BindingConstraintsTimeSeriesNumbersWriter( + IResultWriter& writer): + writer_(writer) +{ +} // TODO : remove duplication static void genericStoreTimeseriesNumbers(Solver::IResultWriter& writer, - const Matrix& timeseriesNumbers, + const Data::TimeSeriesNumbers& timeseriesNumbers, const std::string& id, const std::string& directory) { - TSNumbersPredicate predicate; - std::filesystem::path path = std::filesystem::path() / "ts-numbers" / directory.c_str() / id.c_str(); + std::filesystem::path path = std::filesystem::path() / "ts-numbers" / directory.c_str() + / id.c_str(); path.replace_extension("txt"); std::string buffer; - timeseriesNumbers.saveToBuffer(buffer, - 0, // precision - true, // print_dimensions - predicate, // predicate - true); // save even if all coeffs are zero - + timeseriesNumbers.saveToBuffer(buffer); writer.addEntryFromBuffer(path.string(), buffer); } -void BindingConstraintsTimeSeriesNumbersWriter::write(const Data::BindingConstraintGroupRepository &bindingConstraintGroupRepository) { - for (auto const& group: bindingConstraintGroupRepository) { +void BindingConstraintsTimeSeriesNumbersWriter::write( + const Data::BindingConstraintGroupRepository& bindingConstraintGroupRepository) +{ + for (const auto& group: bindingConstraintGroupRepository) + { genericStoreTimeseriesNumbers(writer_, group->timeseriesNumbers, group->name(), "bindingconstraints"); } - } -} // Simulation +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/adequacy.cpp b/src/solver/simulation/adequacy.cpp index 73e11c3ffa..f4759a0ab1 100644 --- a/src/solver/simulation/adequacy.cpp +++ b/src/solver/simulation/adequacy.cpp @@ -1,43 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "adequacy.h" -#include + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/simulation/adequacy.h" + #include +#include using namespace Yuni; using Antares::Constants::nbHoursInAWeek; namespace Antares::Solver::Simulation { -Adequacy::Adequacy(Data::Study& study, IResultWriter& resultWriter) : +Adequacy::Adequacy(Data::Study& study, + IResultWriter& resultWriter, + Simulation::ISimulationObserver& simulationObserver): study(study), - preproOnly(false), - resultWriter(resultWriter) + resultWriter(resultWriter), + simulationObserver_(simulationObserver) { } @@ -73,29 +70,26 @@ bool Adequacy::simulationBegin() pProblemesHebdo.resize(pNbMaxPerformedYearsInParallel); for (uint numSpace = 0; numSpace < pNbMaxPerformedYearsInParallel; numSpace++) { - SIM_InitialisationProblemeHebdo(study, pProblemesHebdo[numSpace], 168, numSpace); - - assert((uint)nbHoursInAWeek == (uint)pProblemesHebdo[numSpace].NombreDePasDeTemps - && "inconsistency"); - if ((uint)nbHoursInAWeek != (uint)pProblemesHebdo[numSpace].NombreDePasDeTemps) - { - logs.fatal() << "internal error"; - return false; - } + SIM_InitialisationProblemeHebdo(study, + pProblemesHebdo[numSpace], + nbHoursInAWeek, + numSpace); } } - for (auto& pb : pProblemesHebdo) + for (auto& pb: pProblemesHebdo) + { pb.TypeDOptimisation = OPTIMISATION_LINEAIRE; + } pStartTime = study.calendar.days[study.parameters.simulationDays.first].hours.first; pNbWeeks = study.parameters.simulationDays.numberOfWeeks(); return true; } -bool Adequacy::simplexIsRequired(uint hourInTheYear, +bool Adequacy::simplexIsRequired(uint hourInTheYear, uint numSpace, - const ALL_HYDRO_VENTILATION_RESULTS& hydroVentilationResults) const + const HYDRO_VENTILATION_RESULTS& hydroVentilationResults) const { uint areaCount = study.areas.size(); uint indx = hourInTheYear; @@ -106,14 +100,17 @@ bool Adequacy::simplexIsRequired(uint hourInTheYear, for (uint areaIdx = 0; areaIdx != areaCount; ++areaIdx) { - auto& hydroVentilation = hydroVentilationResults[numSpace][areaIdx]; + auto& hydroVentilation = hydroVentilationResults[areaIdx]; - double quantity - = pProblemesHebdo[numSpace].ConsommationsAbattues[j].ConsommationAbattueDuPays[areaIdx] - - hydroVentilation.HydrauliqueModulableQuotidien[dayInTheYear] / 24.; + double quantity = pProblemesHebdo[numSpace] + .ConsommationsAbattues[j] + .ConsommationAbattueDuPays[areaIdx] + - hydroVentilation.HydrauliqueModulableQuotidien[dayInTheYear] / 24.; if (quantity > 0.) + { return true; // Call to the solver is required to find an optimal solution + } } } @@ -126,41 +123,56 @@ bool Adequacy::year(Progression::Task& progression, yearRandomNumbers& randomForYear, std::list& failedWeekList, bool isFirstPerformedYearOfSimulation, - const ALL_HYDRO_VENTILATION_RESULTS& hydroVentilationResults, - OptimizationStatisticsWriter& optWriter) + const HYDRO_VENTILATION_RESULTS& hydroVentilationResults, + OptimizationStatisticsWriter& optWriter, + const Antares::Data::Area::ScratchMap& scratchmap) { // No failed week at year start failedWeekList.clear(); - pProblemesHebdo[numSpace].year = state.year; + auto& currentProblem = pProblemesHebdo[numSpace]; + currentProblem.year = state.year; - PrepareRandomNumbers(study, pProblemesHebdo[numSpace], randomForYear); + PrepareRandomNumbers(study, currentProblem, randomForYear); + SetInitialHydroLevel(study, currentProblem, hydroVentilationResults); state.startANewYear(); int hourInTheYear = pStartTime; if (isFirstPerformedYearOfSimulation) - pProblemesHebdo[numSpace].firstWeekOfSimulation = true; + { + currentProblem.firstWeekOfSimulation = true; + } bool reinitOptim = true; for (uint w = 0; w != pNbWeeks; ++w) { state.hourInTheYear = hourInTheYear; - pProblemesHebdo[numSpace].weekInTheYear = state.weekInTheYear = w; - pProblemesHebdo[numSpace].HeureDansLAnnee = hourInTheYear; - - ::SIM_RenseignementProblemeHebdo(study, pProblemesHebdo[numSpace], state.weekInTheYear, - numSpace, hourInTheYear, hydroVentilationResults); - - BuildThermalPartOfWeeklyProblem(study, pProblemesHebdo[numSpace], - hourInTheYear, randomForYear.pThermalNoisesByArea, state.year); + currentProblem.weekInTheYear = state.weekInTheYear = w; + currentProblem.HeureDansLAnnee = hourInTheYear; + + ::SIM_RenseignementProblemeHebdo(study, + currentProblem, + state.weekInTheYear, + hourInTheYear, + hydroVentilationResults, + scratchmap); + + BuildThermalPartOfWeeklyProblem(study, + currentProblem, + hourInTheYear, + randomForYear.pThermalNoisesByArea, + state.year); // Reinit optimisation if needed - pProblemesHebdo[numSpace].ReinitOptimisation = reinitOptim; + currentProblem.ReinitOptimisation = reinitOptim; reinitOptim = false; - state.simplexRunNeeded = (w == 0) || simplexIsRequired(hourInTheYear, numSpace, hydroVentilationResults); + state.simplexRunNeeded = (w == 0) + || simplexIsRequired(hourInTheYear, + numSpace, + hydroVentilationResults); if (state.simplexRunNeeded) // Call to Solver is mandatory for the first week and optional - // otherwise + // otherwise { uint nbAreas = study.areas.size(); for (uint ar = 0; ar != nbAreas; ++ar) @@ -168,11 +180,10 @@ bool Adequacy::year(Progression::Task& progression, auto& area = *(study.areas.byIndex[ar]); for (uint hw = 0; hw != nbHoursInAWeek; ++hw) { - double& conso = pProblemesHebdo[numSpace] - .ConsommationsAbattues[hw] + double& conso = currentProblem.ConsommationsAbattues[hw] .ConsommationAbattueDuPays[ar]; - double stratReserve - = area.reserves[Data::fhrStrategicReserve][hw + hourInTheYear]; + double stratReserve = area.reserves[Data::fhrStrategicReserve] + [hw + hourInTheYear]; assert(ar < state.resSpilled.width); assert(hw < state.resSpilled.height); @@ -189,7 +200,9 @@ bool Adequacy::year(Progression::Task& progression, conso = 0.; } else + { state.resSpilled[ar][hw] = 0.; + } } } } @@ -197,20 +210,21 @@ bool Adequacy::year(Progression::Task& progression, try { OPT_OptimisationHebdomadaire(createOptimizationOptions(study), - &pProblemesHebdo[numSpace], + ¤tProblem, study.parameters.adqPatchParams, - resultWriter); + resultWriter, + simulationObserver_.get()); - computingHydroLevels(study.areas, pProblemesHebdo[numSpace], false); + computingHydroLevels(study.areas, currentProblem, false); RemixHydroForAllAreas(study.areas, - pProblemesHebdo[numSpace], + currentProblem, study.parameters.shedding.policy, study.parameters.simplexOptimizationRange, numSpace, hourInTheYear); - computingHydroLevels(study.areas, pProblemesHebdo[numSpace], true); + computingHydroLevels(study.areas, currentProblem, true); } catch (Data::AssertionError& ex) { @@ -248,39 +262,46 @@ bool Adequacy::year(Progression::Task& progression, for (uint i = 0; i != nbHoursInAWeek; ++i) { - auto& varduales - = pProblemesHebdo[numSpace].VariablesDualesDesContraintesDeNTC[i]; + auto& varduales = currentProblem.VariablesDualesDesContraintesDeNTC[i]; for (uint lnkindex = 0; lnkindex != runtime.interconnectionsCount(); ++lnkindex) + { varduales.VariableDualeParInterconnexion[lnkindex] = 0.; + } } for (uint hw = 0; hw != nbHoursInAWeek; ++hw) { - auto& ntc = pProblemesHebdo[numSpace].ValeursDeNTC[hw]; + auto& ntc = currentProblem.ValeursDeNTC[hw]; ntc.ValeurDuFlux.resize(runtime.interconnectionsCount(), 0); } for (uint ar = 0; ar != nbAreas; ++ar) { - auto& hourlyResults = pProblemesHebdo[numSpace].ResultatsHoraires[ar]; + auto& hourlyResults = currentProblem.ResultatsHoraires[ar]; std::fill(hourlyResults.ValeursHorairesDeDefaillancePositive.begin(), - hourlyResults.ValeursHorairesDeDefaillancePositive.end(), 0); + hourlyResults.ValeursHorairesDeDefaillancePositive.end(), + 0); std::fill(hourlyResults.ValeursHorairesDeDefaillanceNegative.begin(), - hourlyResults.ValeursHorairesDeDefaillanceNegative.end(), 0); + hourlyResults.ValeursHorairesDeDefaillanceNegative.end(), + 0); std::fill(hourlyResults.CoutsMarginauxHoraires.begin(), - hourlyResults.CoutsMarginauxHoraires.end(), 0); + hourlyResults.CoutsMarginauxHoraires.end(), + 0); std::fill(hourlyResults.PompageHoraire.begin(), - hourlyResults.PompageHoraire.end(), 0); + hourlyResults.PompageHoraire.end(), + 0); std::fill(hourlyResults.debordementsHoraires.begin(), - hourlyResults.debordementsHoraires.end(), 0); + hourlyResults.debordementsHoraires.end(), + 0); std::fill(hourlyResults.niveauxHoraires.begin(), - hourlyResults.niveauxHoraires.end(), 0); + hourlyResults.niveauxHoraires.end(), + 0); } uint indx = hourInTheYear; @@ -293,27 +314,28 @@ bool Adequacy::year(Progression::Task& progression, { assert(k < state.resSpilled.width); assert(j < state.resSpilled.height); - auto& hydroVentilation = hydroVentilationResults[numSpace][k]; - auto& hourlyResults = pProblemesHebdo[numSpace].ResultatsHoraires[k]; - - hourlyResults.TurbinageHoraire[j] - = hydroVentilation.HydrauliqueModulableQuotidien[dayInTheYear] / 24.; - - state.resSpilled[k][j] - = +hydroVentilation.HydrauliqueModulableQuotidien[dayInTheYear] / 24. - - pProblemesHebdo[numSpace] - .ConsommationsAbattues[j] - .ConsommationAbattueDuPays[k]; + auto& hydroVentilation = hydroVentilationResults[k]; + auto& hourlyResults = currentProblem.ResultatsHoraires[k]; + + hourlyResults.TurbinageHoraire[j] = hydroVentilation + .HydrauliqueModulableQuotidien + [dayInTheYear] + / 24.; + + state.resSpilled[k][j] = +hydroVentilation + .HydrauliqueModulableQuotidien[dayInTheYear] + / 24. + - currentProblem.ConsommationsAbattues[j] + .ConsommationAbattueDuPays[k]; } } - computingHydroLevels(study.areas, pProblemesHebdo[numSpace], false, true); + computingHydroLevels(study.areas, currentProblem, false, true); } - interpolateWaterValue( - study.areas, pProblemesHebdo[numSpace], study.calendar, hourInTheYear); + interpolateWaterValue(study.areas, currentProblem, study.calendar, hourInTheYear); - updatingWeeklyFinalHydroLevel(study.areas, pProblemesHebdo[numSpace]); + updatingWeeklyFinalHydroLevel(study.areas, currentProblem); variables.weekBegin(state); uint previousHourInTheYear = state.hourInTheYear; @@ -323,7 +345,7 @@ bool Adequacy::year(Progression::Task& progression, { state.hourInTheWeek = hw; - state.ntc = pProblemesHebdo[numSpace].ValeursDeNTC[hw]; + state.ntc = currentProblem.ValeursDeNTC[hw]; variables.hourBegin(state.hourInTheYear); @@ -338,27 +360,25 @@ bool Adequacy::year(Progression::Task& progression, hourInTheYear += nbHoursInAWeek; - pProblemesHebdo[numSpace].firstWeekOfSimulation = false; + currentProblem.firstWeekOfSimulation = false; - optWriter.addTime(w, - pProblemesHebdo[numSpace].tempsResolution1[0], - pProblemesHebdo[numSpace].tempsResolution2[0]); + optWriter.addTime(w, currentProblem.timeMeasure); ++progression; } - updatingAnnualFinalHydroLevel(study.areas, pProblemesHebdo[numSpace]); - optWriter.finalize(); - finalizeOptimizationStatistics(pProblemesHebdo[numSpace], state); + finalizeOptimizationStatistics(currentProblem, state); return true; } -void Adequacy::incrementProgression(Progression::Task& progression) +void Adequacy::incrementProgression(Progression::Task& progression) const { for (uint w = 0; w < pNbWeeks; ++w) + { ++progression; + } } // Retrieve weighted average balance for each area @@ -386,9 +406,36 @@ void Adequacy::simulationEnd() } } -void Adequacy::prepareClustersInMustRunMode(uint numSpace, uint year) +void Adequacy::prepareClustersInMustRunMode(Data::Area::ScratchMap& scratchmap, uint year) { - PrepareDataFromClustersInMustrunMode(study, numSpace, year); -} + for (uint i = 0; i < study.areas.size(); ++i) + { + auto& area = *study.areas[i]; + auto& scratchpad = scratchmap.at(&area); + + std::ranges::fill(scratchpad.mustrunSum, 0); + std::ranges::fill(scratchpad.originalMustrunSum, 0); + + auto& mrs = scratchpad.mustrunSum; + auto& adq = scratchpad.originalMustrunSum; + for (const auto& cluster: area.thermal.list.each_mustrun_and_enabled()) + { + const auto& availableProduction = cluster->series.getColumn(year); + for (uint h = 0; h != cluster->series.timeSeries.height; ++h) + { + mrs[h] += availableProduction[h]; + } + + if (cluster->mustrunOrigin) + { + for (uint h = 0; h != cluster->series.timeSeries.height; ++h) + { + adq[h] += 2 * availableProduction[h]; // Why do we add the available production + // twice ? + } + } + } + } +} } // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/adequacy.h b/src/solver/simulation/adequacy.h deleted file mode 100644 index 8832670f1a..0000000000 --- a/src/solver/simulation/adequacy.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_ADEQUACY_H__ -#define __SOLVER_SIMULATION_ADEQUACY_H__ - -#include "../variable/variable.h" -#include "../variable/adequacy/all.h" -#include "../variable/economy/all.h" -#include "../variable/state.h" -#include "common-eco-adq.h" - -#include "solver.h" // for definition of type yearRandomNumbers -#include "antares/infoCollection/StudyInfoCollector.h" -#include "opt_time_writer.h" - -namespace Antares::Solver::Simulation -{ -class Adequacy -{ -public: - //! Name of the type of simulation - static const char* Name() - { - return "adequacy"; - } - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Constructor - ** - ** \param study The current study - */ - Adequacy(Data::Study& study, IResultWriter& resultWriter); - //! Destructor - ~Adequacy() = default; - //@} - - Benchmarking::OptimizationInfo getOptimizationInfo() const; - -public: - //! Current study - Data::Study& study; - //! All variables - Solver::Variable::Adequacy::AllVariables variables; - //! Prepro only - bool preproOnly; - -protected: - void setNbPerformedYearsInParallel(uint nbMaxPerformedYearsInParallel); - - bool simulationBegin(); - - bool year(Progression::Task& progression, - Variable::State& state, - uint numSpace, - yearRandomNumbers& randomForYear, - std::list& failedWeekList, - bool isFirstPerformedYearOfSimulation, - const ALL_HYDRO_VENTILATION_RESULTS&, - OptimizationStatisticsWriter& optWriter); - - void incrementProgression(Progression::Task& progression); - - void simulationEnd(); - - /*! - ** \brief Prepare clusters in 'must-run' mode - */ - void prepareClustersInMustRunMode(uint numSpace, uint year); - - void initializeState(Variable::State& state, uint numSpace); - -private: - bool simplexIsRequired(uint hourInTheYear, - uint numSpace, - const ALL_HYDRO_VENTILATION_RESULTS&) const; - - uint pNbWeeks; - uint pStartTime; - uint pNbMaxPerformedYearsInParallel; - bool pPreproOnly; - std::vector pProblemesHebdo; - Matrix<> pRES; - IResultWriter& resultWriter; - -}; // class Adequacy - -} // namespace Antares::Solver::Simulation - -#endif // __SOLVER_SIMULATION_ADEQUACY_H__ diff --git a/src/solver/simulation/adequacy_mode.cpp b/src/solver/simulation/adequacy_mode.cpp new file mode 100644 index 0000000000..c0dd81b176 --- /dev/null +++ b/src/solver/simulation/adequacy_mode.cpp @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/simulation/adequacy_mode.h" + +#include "antares/solver/simulation/adequacy.h" +#include "antares/solver/simulation/solver.h" + +namespace Antares::Solver +{ +void runSimulationInAdequacyMode(Antares::Data::Study& study, + const Settings& settings, + Benchmarking::DurationCollector& durationCollector, + IResultWriter& resultWriter, + Benchmarking::OptimizationInfo& info, + Simulation::ISimulationObserver& simulationObserver) +{ + // Type of the simulation + typedef Solver::Simulation::ISimulation SimulationType; + SimulationType simulation(study, settings, durationCollector, resultWriter, simulationObserver); + simulation.checkWriter(); + simulation.run(); + + if (!(settings.noOutput || settings.tsGeneratorsOnly)) + { + durationCollector("synthesis_export") + << [&simulation] { simulation.writeResults(/*synthesis:*/ true); }; + + info = simulation.getOptimizationInfo(); + } +} +} // namespace Antares::Solver diff --git a/src/solver/simulation/adequacy_patch_runtime_data.cpp b/src/solver/simulation/adequacy_patch_runtime_data.cpp index 205bf762f2..448132f500 100644 --- a/src/solver/simulation/adequacy_patch_runtime_data.cpp +++ b/src/solver/simulation/adequacy_patch_runtime_data.cpp @@ -1,13 +1,37 @@ -#include "adequacy_patch_runtime_data.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" namespace { constexpr double thresholdForCostCoefficient = 1.e-12; + double computeHurdleCostCoefficient(double unsuppliedEnergyCost1, double unsuppliedEnergyCost2) { double m = std::max(unsuppliedEnergyCost1, unsuppliedEnergyCost2); if (std::fabs(m) < thresholdForCostCoefficient) + { m = thresholdForCostCoefficient; + } return 1. / m; } } // namespace @@ -44,6 +68,7 @@ AdequacyPatchRuntimeData::AdequacyPatchRuntimeData( originAreaMode[i] = from->adequacyPatchMode; extremityAreaMode[i] = with->adequacyPatchMode; hurdleCostCoefficients[i] = computeHurdleCostCoefficient( - from->thermal.unsuppliedEnergyCost, with->thermal.unsuppliedEnergyCost); + from->thermal.unsuppliedEnergyCost, + with->thermal.unsuppliedEnergyCost); } } diff --git a/src/solver/simulation/adequacy_patch_runtime_data.h b/src/solver/simulation/adequacy_patch_runtime_data.h deleted file mode 100644 index 62971f28a3..0000000000 --- a/src/solver/simulation/adequacy_patch_runtime_data.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once -#include -#include -#include -#include - -class AdequacyPatchRuntimeData -{ -private: - using adqPatchParamsMode = Antares::Data::AdequacyPatch::AdequacyPatchMode; - std::vector> csrTriggeredHoursPerArea_; - -public: - explicit AdequacyPatchRuntimeData() = default; - AdequacyPatchRuntimeData(const Antares::Data::AreaList& areas, - const std::vector& links); - - std::vector areaMode; - std::vector originAreaMode; - std::vector extremityAreaMode; - std::vector hurdleCostCoefficients; - bool AdequacyFirstStep = true; - - bool wasCSRTriggeredAtAreaHour(int area, int hour) const; - void addCSRTriggeredAtAreaHour(int area, int hour); -}; diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 0e01da1ec0..83dffb0dec 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "apply-scenario.h" +#include "antares/solver/simulation/apply-scenario.h" + #include namespace Antares::Solver @@ -49,8 +44,10 @@ void ApplyCustomScenario(Data::Study& study) rules->apply(); } else + { logs.error() << "Scenario Builder: Impossible to find the active ruleset '" << rulename << "'"; + } } study.scenarioRulesDestroy(); diff --git a/src/solver/simulation/apply-scenario.h b/src/solver/simulation/apply-scenario.h deleted file mode 100644 index 4c4cdd1552..0000000000 --- a/src/solver/simulation/apply-scenario.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_APPLY_SCENARIO_H__ -#define __SOLVER_SIMULATION_APPLY_SCENARIO_H__ - -#include - -namespace Antares::Solver -{ -void ApplyCustomScenario(Data::Study& study); -} // namespace Antares::Solver - -#endif // __SOLVER_SIMULATION_APPLY_SCENARIO_H__ diff --git a/src/solver/simulation/base_post_process.cpp b/src/solver/simulation/base_post_process.cpp index be07fb1bc8..4cd7bb8cf9 100644 --- a/src/solver/simulation/base_post_process.cpp +++ b/src/solver/simulation/base_post_process.cpp @@ -1,55 +1,81 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/simulation/base_post_process.h" #include -#include "base_post_process.h" -#include "../optimisation/optim_post_process_list.h" -#include "../optimisation/adequacy_patch_csr/adq_patch_post_process_list.h" + +#include "antares/solver/optimisation/adequacy_patch_csr/adq_patch_post_process_list.h" +#include "antares/solver/optimisation/optim_post_process_list.h" namespace Antares::Solver::Simulation { -basePostProcessCommand::basePostProcessCommand(PROBLEME_HEBDO* problemeHebdo) - : problemeHebdo_(problemeHebdo) +basePostProcessCommand::basePostProcessCommand(PROBLEME_HEBDO* problemeHebdo): + problemeHebdo_(problemeHebdo) { } -interfacePostProcessList::interfacePostProcessList(PROBLEME_HEBDO* problemesHebdo, uint numSpace) : - problemeHebdo_(problemesHebdo), thread_number_(numSpace) +interfacePostProcessList::interfacePostProcessList(PROBLEME_HEBDO* problemesHebdo, uint numSpace): + problemeHebdo_(problemesHebdo), + thread_number_(numSpace) { } - std::unique_ptr interfacePostProcessList::create( - AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemeHebdo, - uint thread_number, - AreaList& areas, - SheddingPolicy sheddingPolicy, - SimplexOptimization splxOptimization, - Calendar& calendar) + AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + uint thread_number, + AreaList& areas, + SheddingPolicy sheddingPolicy, + SimplexOptimization splxOptimization, + Calendar& calendar) { if (adqPatchParams.enabled) + { return std::make_unique(adqPatchParams, - problemeHebdo, + problemeHebdo, thread_number, areas, sheddingPolicy, splxOptimization, calendar); + } else - return std::make_unique(problemeHebdo, + { + return std::make_unique(problemeHebdo, thread_number, - areas, + areas, sheddingPolicy, splxOptimization, calendar); + } } void interfacePostProcessList::runAll(const optRuntimeData& opt_runtime_data) { - for (auto& post_process : post_process_list) + for (auto& post_process: post_process_list) { post_process->execute(opt_runtime_data); } } -} // namespace Antares::Solver::Simulation \ No newline at end of file +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/base_post_process.h b/src/solver/simulation/base_post_process.h deleted file mode 100644 index 8aaf70c2f6..0000000000 --- a/src/solver/simulation/base_post_process.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#include -#include - -#include "../simulation/sim_structure_probleme_economique.h" - -using namespace Antares::Data; -using namespace Antares::Date; -using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; - -namespace Antares::Solver::Simulation -{ - - -struct optRuntimeData -{ - optRuntimeData(unsigned int y, unsigned int w, unsigned int h) : - year(y), week(w), hourInTheYear(h) - {} - - unsigned int year = 0; - unsigned int week = 0; - unsigned int hourInTheYear = 0; -}; - -class basePostProcessCommand -{ -public: - virtual ~basePostProcessCommand() = default; - virtual void execute(const optRuntimeData& opt_runtime_data) = 0; - -protected: - // Memeber functions - basePostProcessCommand(PROBLEME_HEBDO* problemeHebdo); - - // Data members - PROBLEME_HEBDO* problemeHebdo_; -}; - -class interfacePostProcessList -{ -public: - virtual ~interfacePostProcessList() = default; - - // gp : we should put all these arguments in a structure, so that we pass a structure - // gp : to the create(...) method, and to underlying calls to constructors. - // gp : In case we need new data for a new post process, we would not have to change - // gp : the constructors' signatures of the post process list classes. - static std::unique_ptr create(AdqPatchParams& adqPatchParams, - PROBLEME_HEBDO* problemeHebdo, - uint thread_number, - AreaList& areas, - SheddingPolicy sheddingPolicy, - SimplexOptimization splxOptimization, - Calendar& calendar); - void runAll(const optRuntimeData& opt_runtime_data); - -protected: - // Member functions - interfacePostProcessList(PROBLEME_HEBDO* problemeHebdo, uint thread_number); - - // Data mambers - PROBLEME_HEBDO* const problemeHebdo_ = nullptr; - const unsigned int thread_number_ = 0; - std::vector> post_process_list; -}; - -} // namespace Antares::Solver::Simulation \ No newline at end of file diff --git a/src/solver/simulation/common-eco-adq.cpp b/src/solver/simulation/common-eco-adq.cpp index a3f2099ce9..27d2cdae6c 100644 --- a/src/solver/simulation/common-eco-adq.cpp +++ b/src/solver/simulation/common-eco-adq.cpp @@ -1,44 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include -#include -#include + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/simulation/common-eco-adq.h" -#include "common-eco-adq.h" -#include #include +#include #include -#include "simulation.h" -#include "../aleatoire/alea_fonctions.h" -using namespace Yuni; +#include +#include +#include +#include "antares/study/simulation.h" namespace Antares::Solver::Simulation { @@ -57,8 +47,9 @@ static void RecalculDesEchangesMoyens(Data::Study& study, assert(balance[j] && "Impossible to find the variable"); if (balance[j]) { - problem.SoldeMoyenHoraire[i].SoldeMoyenDuPays[j] - = balance[j]->avgdata.hourly[decalPasDeTemps]; + problem.SoldeMoyenHoraire[i].SoldeMoyenDuPays[j] = balance[j] + ->avgdata + .hourly[decalPasDeTemps]; } else { @@ -72,11 +63,15 @@ static void RecalculDesEchangesMoyens(Data::Study& study, for (uint j = 0; j < study.runtime->interconnectionsCount(); ++j) { auto* link = study.runtime->areaLink[j]; - int ret = retrieveAverageNTC( - study, link->directCapacities, link->timeseriesNumbers, avgDirect); - - ret = retrieveAverageNTC( - study, link->indirectCapacities, link->timeseriesNumbers, avgIndirect) + int ret = retrieveAverageNTC(study, + link->directCapacities.timeSeries, + link->timeseriesNumbers, + avgDirect); + + ret = retrieveAverageNTC(study, + link->indirectCapacities.timeSeries, + link->timeseriesNumbers, + avgIndirect) && ret; if (!ret) { @@ -96,7 +91,12 @@ static void RecalculDesEchangesMoyens(Data::Study& study, try { NullResultWriter resultWriter; - OPT_OptimisationHebdomadaire(createOptimizationOptions(study), &problem, study.parameters.adqPatchParams, resultWriter); + NullSimulationObserver simulationObserver; + OPT_OptimisationHebdomadaire(createOptimizationOptions(study), + &problem, + study.parameters.adqPatchParams, + resultWriter, + simulationObserver); } catch (Data::UnfeasibleProblemError&) { @@ -107,68 +107,10 @@ static void RecalculDesEchangesMoyens(Data::Study& study, { const uint indx = i + PasDeTempsDebut; auto& ntcValues = problem.ValeursDeNTC[i]; - assert(&ntcValues); for (uint j = 0; j < study.runtime->interconnectionsCount(); ++j) { - transitMoyenInterconnexionsRecalculQuadratique[j][indx] - = ntcValues.ValeurDuFlux[j]; - } - } -} - -void PrepareDataFromClustersInMustrunMode(Data::Study& study, uint numSpace, uint year) -{ - bool inAdequacy = (study.parameters.mode == Data::stdmAdequacy); - - for (uint i = 0; i < study.areas.size(); ++i) - { - auto& area = *study.areas[i]; - auto& scratchpad = area.scratchpad[numSpace]; - - memset(scratchpad.mustrunSum, 0, sizeof(double) * HOURS_PER_YEAR); - if (inAdequacy) - memset(scratchpad.originalMustrunSum, 0, sizeof(double) * HOURS_PER_YEAR); - - double* mrs = scratchpad.mustrunSum; - double* adq = scratchpad.originalMustrunSum; - - if (!area.thermal.mustrunList.empty()) - { - auto end = area.thermal.mustrunList.end(); - for (auto i = area.thermal.mustrunList.begin(); i != end; ++i) - { - auto& cluster = *(i->second); - const auto& availableProduction = cluster.series->getAvailablePowerYearly(year); - if (inAdequacy && cluster.mustrunOrigin) - { - for (uint h = 0; h != cluster.series->timeSeries.height; ++h) - { - mrs[h] += availableProduction[h]; - adq[h] += availableProduction[h]; - } - } - else - { - for (uint h = 0; h != cluster.series->timeSeries.height; ++h) - mrs[h] += availableProduction[h]; - } - } - } - - if (inAdequacy) - { - auto end = area.thermal.list.end(); - for (auto i = area.thermal.list.begin(); i != end; ++i) - { - auto& cluster = *(i->second); - if (!cluster.mustrunOrigin) - continue; - - const auto& availableProduction = cluster.series->getAvailablePowerYearly(year); - for (uint h = 0; h != cluster.series->timeSeries.height; ++h) - adq[h] += availableProduction[h]; - } + transitMoyenInterconnexionsRecalculQuadratique[j][indx] = ntcValues.ValeurDuFlux[j]; } } } @@ -177,7 +119,9 @@ bool ShouldUseQuadraticOptimisation(const Data::Study& study) { const bool flowQuadEnabled = study.parameters.variablesPrintInfo.isPrinted("FLOW QUAD."); if (!flowQuadEnabled) + { return false; + } for (uint j = 0; j < study.runtime->interconnectionsCount(); ++j) { @@ -186,7 +130,7 @@ bool ShouldUseQuadraticOptimisation(const Data::Study& study) for (uint hour = 0; hour < HOURS_PER_YEAR; ++hour) { - if (Math::Abs(impedances[hour]) >= 1e-100) + if (std::abs(impedances[hour]) >= 1e-100) { return true; } @@ -238,137 +182,179 @@ void PrepareRandomNumbers(Data::Study& study, yearRandomNumbers& randomForYear) { uint indexArea = 0; - study.areas.each([&](Data::Area& area) { - double rnd = 0.; - - rnd = randomForYear.pUnsuppliedEnergy[indexArea]; - - double alea; - - if (area.spreadUnsuppliedEnergyCost == 0) - { - if (rnd < 0.5) - alea = 1.e-4 * (5 + 2 * rnd); - else - alea = -1.e-4 * (5 + 2 * (rnd - 0.5)); - } - else - { - alea = (rnd - 0.5) * (area.spreadUnsuppliedEnergyCost); - - if (Math::Abs(alea) < 5.e-4) - { - if (alea >= 0) - alea += 5.e-4; - else - alea -= 5.e-4; - } - } - problem.CoutDeDefaillancePositive[area.index] = area.thermal.unsuppliedEnergyCost + alea; - - rnd = randomForYear.pSpilledEnergy[indexArea]; - - if (area.spreadSpilledEnergyCost == 0) - { - if (rnd < 0.5) - alea = 1.e-4 * (5 + 2 * rnd); - else - alea = -1.e-4 * (5 + 2 * (rnd - 0.5)); - } - else - { - alea = (rnd - 0.5) * (area.spreadSpilledEnergyCost); - - if (Math::Abs(alea) < 5.e-4) - { - if (alea >= 0) - alea += 5.e-4; - else - alea -= 5.e-4; - } - } - problem.CoutDeDefaillanceNegative[area.index] = area.thermal.spilledEnergyCost + alea; - - - //----------------------------- - // Thermal noises - //----------------------------- - auto end = area.thermal.list.mapping.end(); - for (auto it = area.thermal.list.mapping.begin(); it != end; ++it) - { - auto cluster = it->second; - if (!cluster->enabled) - continue; - uint clusterIndex = cluster->areaWideIndex; - double& rnd = randomForYear.pThermalNoisesByArea[indexArea][clusterIndex]; - double randomClusterProdCost(0.); - if (cluster->spreadCost == 0) // 5e-4 < |randomClusterProdCost| < 6e-4 - { - if (rnd < 0.5) - randomClusterProdCost = 1e-4 * (5 + 2 * rnd); - else - randomClusterProdCost = -1e-4 * (5 + 2 * (rnd - 0.5)); - } - else - { - randomClusterProdCost = (rnd - 0.5) * (cluster->spreadCost); - - if (Math::Abs(randomClusterProdCost) < 5.e-4) - { - if (Math::Abs(randomClusterProdCost) >= 0) - randomClusterProdCost += 5.e-4; - else - randomClusterProdCost -= 5.e-4; - } - } - rnd = randomClusterProdCost; - } - - //----------------------------- - // Hydro noises - //----------------------------- - auto& noise = problem.BruitSurCoutHydraulique[area.index]; - switch (study.parameters.power.fluctuations) - { - case Data::lssFreeModulations: - { - for (uint j = 0; j != 8784; ++j) - noise[j] = randomForYear.pHydroCostsByArea_freeMod[indexArea][j]; - - auto& penalty = problem.CaracteristiquesHydrauliques[area.index]; - penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations = 5.e-4; - penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax = 5.e-4; - break; - } - - case Data::lssMinimizeRamping: - case Data::lssMinimizeExcursions: - { - std::fill(noise.begin(), noise.end(), 0); - - auto& penalty = problem.CaracteristiquesHydrauliques[area.index]; - double rnd = randomForYear.pHydroCosts_rampingOrExcursion[indexArea]; - - penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations - = 0.01 * (1. + rnd / 10.); - penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax - = 0.1 * (1. + rnd / 100.); - break; - } - - case Data::lssUnknown: - { - assert(false && "invalid power fluctuations"); - std::fill(noise.begin(), noise.end(), 0); + study.areas.each( + [&study, &problem, &randomForYear, &indexArea](const Data::Area& area) + { + double rnd = 0.; + + rnd = randomForYear.pUnsuppliedEnergy[indexArea]; + + double alea; + + if (area.spreadUnsuppliedEnergyCost == 0) + { + if (rnd < 0.5) + { + alea = 1.e-4 * (5 + 2 * rnd); + } + else + { + alea = -1.e-4 * (5 + 2 * (rnd - 0.5)); + } + } + else + { + alea = (rnd - 0.5) * (area.spreadUnsuppliedEnergyCost); + + if (std::abs(alea) < 5.e-4) + { + if (alea >= 0) + { + alea += 5.e-4; + } + else + { + alea -= 5.e-4; + } + } + } + problem.CoutDeDefaillancePositive[area.index] = area.thermal.unsuppliedEnergyCost + alea; + + rnd = randomForYear.pSpilledEnergy[indexArea]; + + if (area.spreadSpilledEnergyCost == 0) + { + if (rnd < 0.5) + { + alea = 1.e-4 * (5 + 2 * rnd); + } + else + { + alea = -1.e-4 * (5 + 2 * (rnd - 0.5)); + } + } + else + { + alea = (rnd - 0.5) * (area.spreadSpilledEnergyCost); + + if (std::abs(alea) < 5.e-4) + { + if (alea >= 0) + { + alea += 5.e-4; + } + else + { + alea -= 5.e-4; + } + } + } + problem.CoutDeDefaillanceNegative[area.index] = area.thermal.spilledEnergyCost + alea; + + //----------------------------- + // Thermal noises + //----------------------------- + for (auto& cluster: area.thermal.list.each_enabled()) + { + uint clusterIndex = cluster->areaWideIndex; + double& rnd = randomForYear.pThermalNoisesByArea[indexArea][clusterIndex]; + double randomClusterProdCost(0.); + if (cluster->spreadCost == 0) // 5e-4 < |randomClusterProdCost| < 6e-4 + { + if (rnd < 0.5) + { + randomClusterProdCost = 1e-4 * (5 + 2 * rnd); + } + else + { + randomClusterProdCost = -1e-4 * (5 + 2 * (rnd - 0.5)); + } + } + else + { + randomClusterProdCost = (rnd - 0.5) * (cluster->spreadCost); + + if (std::abs(randomClusterProdCost) < 5.e-4) + { + if (std::abs(randomClusterProdCost) >= 0) + { + randomClusterProdCost += 5.e-4; + } + else + { + randomClusterProdCost -= 5.e-4; + } + } + } + rnd = randomClusterProdCost; + } + + //----------------------------- + // Hydro noises + //----------------------------- + auto& noise = problem.BruitSurCoutHydraulique[area.index]; + switch (study.parameters.power.fluctuations) + { + case Data::lssFreeModulations: + { + for (uint j = 0; j != 8784; ++j) + { + noise[j] = randomForYear.pHydroCostsByArea_freeMod[indexArea][j]; + } + + auto& penalty = problem.CaracteristiquesHydrauliques[area.index]; + penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations = 5.e-4; + penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax = 5.e-4; + break; + } + + case Data::lssMinimizeRamping: + case Data::lssMinimizeExcursions: + { + std::fill(noise.begin(), noise.end(), 0); + + auto& penalty = problem.CaracteristiquesHydrauliques[area.index]; + double rnd = randomForYear.pHydroCosts_rampingOrExcursion[indexArea]; + + penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations + = 0.01 * (1. + rnd / 10.); + penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax + = 0.1 * (1. + rnd / 100.); + break; + } + + case Data::lssUnknown: + { + assert(false && "invalid power fluctuations"); + std::fill(noise.begin(), noise.end(), 0); + + auto& penalty = problem.CaracteristiquesHydrauliques[area.index]; + penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations = 1e-4; + penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax = 1e-4; + break; + } + } + indexArea++; + }); +} - auto& penalty = problem.CaracteristiquesHydrauliques[area.index]; - penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurSommeDesVariations = 1e-4; - penalty.PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax = 1e-4; - break; - } - } - indexArea++; - }); +void SetInitialHydroLevel(Data::Study& study, + PROBLEME_HEBDO& problem, + const HYDRO_VENTILATION_RESULTS& hydroVentilationResults) +{ + uint firstDaySimu = study.parameters.simulationDays.first; + study.areas.each( + [&problem, &firstDaySimu, &hydroVentilationResults](const Data::Area& area) + { + if (area.hydro.reservoirManagement) + { + double capacity = area.hydro.reservoirCapacity; + problem.previousSimulationFinalLevel[area.index] = hydroVentilationResults[area.index] + .NiveauxReservoirsDebutJours + [firstDaySimu] + * capacity; + } + }); } void BuildThermalPartOfWeeklyProblem(Data::Study& study, @@ -379,28 +365,31 @@ void BuildThermalPartOfWeeklyProblem(Data::Study& study, { int hourInYear = PasDeTempsDebut; const uint nbPays = study.areas.size(); - for (unsigned hourInWeek = 0; hourInWeek < problem.NombreDePasDeTemps; ++hourInWeek, ++hourInYear) + for (unsigned hourInWeek = 0; hourInWeek < problem.NombreDePasDeTemps; + ++hourInWeek, ++hourInYear) { for (uint areaIdx = 0; areaIdx < nbPays; ++areaIdx) { auto& area = *study.areas.byIndex[areaIdx]; - area.thermal.list.each([&](const Data::ThermalCluster& cluster) + for (auto& cluster: area.thermal.list.each_enabled_and_not_mustrun()) { - auto& Pt = problem.PaliersThermiquesDuPays[areaIdx] - .PuissanceDisponibleEtCout[cluster.index]; - - Pt.CoutHoraireDeProductionDuPalierThermique[hourInWeek] = - cluster.getMarketBidCost(hourInYear, year) - + thermalNoises[areaIdx][cluster.areaWideIndex]; - - Pt.PuissanceDisponibleDuPalierThermique[hourInWeek] - = cluster.series->getAvailablePower(hourInYear, year); - - Pt.PuissanceMinDuPalierThermique[hourInWeek] - = (Pt.PuissanceDisponibleDuPalierThermique[hourInWeek] < cluster.PthetaInf[hourInYear]) - ? Pt.PuissanceDisponibleDuPalierThermique[hourInWeek] - : cluster.PthetaInf[hourInYear]; - }); + auto& Pt = problem.PaliersThermiquesDuPays[areaIdx] + .PuissanceDisponibleEtCout[cluster->index]; + + Pt.CoutHoraireDeProductionDuPalierThermique[hourInWeek] + = cluster->getMarketBidCost(hourInYear, year) + + thermalNoises[areaIdx][cluster->areaWideIndex]; + + Pt.PuissanceDisponibleDuPalierThermique[hourInWeek] = cluster->series + .getCoefficient(year, + hourInYear); + + Pt.PuissanceMinDuPalierThermique[hourInWeek] + = (Pt.PuissanceDisponibleDuPalierThermique[hourInWeek] + < cluster->PthetaInf[hourInYear]) + ? Pt.PuissanceDisponibleDuPalierThermique[hourInWeek] + : cluster->PthetaInf[hourInYear]; + } } } @@ -408,21 +397,21 @@ void BuildThermalPartOfWeeklyProblem(Data::Study& study, { auto& area = *study.areas.byIndex[k]; - for (uint l = 0; l != area.thermal.list.size(); ++l) + for (uint l = 0; l != area.thermal.list.enabledAndNotMustRunCount(); ++l) { - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[l] - .PuissanceDisponibleDuPalierThermiqueRef - = - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[l] - .PuissanceDisponibleDuPalierThermique; + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[l] + .PuissanceDisponibleDuPalierThermiqueRef + = problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[l] + .PuissanceDisponibleDuPalierThermique; } } - } int retrieveAverageNTC(const Data::Study& study, const Matrix<>& capacities, - const Matrix& tsNumbers, + const Data::TimeSeriesNumbers& tsNumbers, std::vector& avg) { const auto& parameters = study.parameters; @@ -438,14 +427,16 @@ int retrieveAverageNTC(const Data::Study& study, for (uint y = 0; y < study.parameters.nbYears; y++) { if (!yearsFilter[y]) + { continue; + } - uint32_t tsIndex = (width == 1) ? 0 : tsNumbers[0][y]; + uint32_t tsIndex = (width == 1) ? 0 : tsNumbers[y]; weightOfTS[tsIndex] += yearsWeight[y]; } // No need for the year number, only the TS index is required - for (const auto& it : weightOfTS) + for (const auto& it: weightOfTS) { const uint32_t tsIndex = it.first; const double weight = it.second; @@ -468,20 +459,20 @@ void finalizeOptimizationStatistics(PROBLEME_HEBDO& problem, { auto& firstOptStat = problem.optimizationStatistics[0]; state.averageOptimizationTime1 = firstOptStat.getAverageSolveTime(); - firstOptStat.reset(); auto& secondOptStat = problem.optimizationStatistics[1]; state.averageOptimizationTime2 = secondOptStat.getAverageSolveTime(); + + state.averageUpdateTime = firstOptStat.getAverageUpdateTime() + + secondOptStat.getAverageUpdateTime(); + + firstOptStat.reset(); secondOptStat.reset(); } OptimizationOptions createOptimizationOptions(const Data::Study& study) { - return { - study.parameters.ortoolsUsed, - study.parameters.ortoolsSolver - }; + return study.parameters.optOptions; } - } // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/common-hydro-levels.cpp b/src/solver/simulation/common-hydro-levels.cpp index 4c027a0595..b0ba258b0e 100644 --- a/src/solver/simulation/common-hydro-levels.cpp +++ b/src/solver/simulation/common-hydro-levels.cpp @@ -1,34 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include "common-eco-adq.h" -#include "simulation.h" #include +#include +#include "antares/solver/simulation/common-eco-adq.h" +#include "antares/solver/simulation/simulation.h" namespace Antares::Solver::Simulation { @@ -39,42 +33,39 @@ void computingHydroLevels(const Data::AreaList& areas, bool remixWasRun, bool computeAnyway) { - areas.each([&](const Data::Area& area) { - if (!area.hydro.reservoirManagement) - return; + for (const auto& [_, area]: areas) + { + if (!area->hydro.reservoirManagement) + { + continue; + } - if (not computeAnyway) + if (!computeAnyway && area->hydro.useHeuristicTarget != remixWasRun) { - if (area.hydro.useHeuristicTarget != remixWasRun) - return; + continue; } - uint index = area.index; + uint index = area->index; - double reservoirCapacity = area.hydro.reservoirCapacity; + double reservoirCapacity = area->hydro.reservoirCapacity; - std::vector& inflows - = problem.CaracteristiquesHydrauliques[index].ApportNaturelHoraire; + std::vector& inflows = problem.CaracteristiquesHydrauliques[index] + .ApportNaturelHoraire; RESULTATS_HORAIRES& weeklyResults = problem.ResultatsHoraires[index]; std::vector& turb = weeklyResults.TurbinageHoraire; std::vector& pump = weeklyResults.PompageHoraire; - double pumpingRatio = area.hydro.pumpingEfficiency; + double pumpingRatio = area->hydro.pumpingEfficiency; double nivInit = problem.CaracteristiquesHydrauliques[index].NiveauInitialReservoir; std::vector& niv = weeklyResults.niveauxHoraires; std::vector& ovf = weeklyResults.debordementsHoraires; - computeTimeStepLevel computeLvlObj(nivInit, - inflows, - ovf, - turb, - pumpingRatio, - pump, - reservoirCapacity); + computeTimeStepLevel + computeLvlObj(nivInit, inflows, ovf, turb, pumpingRatio, pump, reservoirCapacity); for (uint h = 0; h < nbHoursInAWeek - 1; h++) { @@ -85,7 +76,7 @@ void computingHydroLevels(const Data::AreaList& areas, computeLvlObj.run(); niv[nbHoursInAWeek - 1] = computeLvlObj.getLevel() * 100 / reservoirCapacity; - }); + } } void interpolateWaterValue(const Data::AreaList& areas, @@ -99,79 +90,67 @@ void interpolateWaterValue(const Data::AreaList& areas, daysOfWeek[0] = weekFirstDay; for (int d = 1; d < 7; d++) + { daysOfWeek[d] = weekFirstDay + d; + } - areas.each([&](const Data::Area& area) { - uint index = area.index; + for (const auto& [_, area]: areas) + { + uint index = area->index; RESULTATS_HORAIRES& weeklyResults = problem.ResultatsHoraires[index]; - std::vector& waterVal = weeklyResults.valeurH2oHoraire; - - for (uint h = 0; h < nbHoursInAWeek; h++) - waterVal[h] = 0.; + auto& waterVal = weeklyResults.valeurH2oHoraire; + std::fill(waterVal.begin(), waterVal.end(), 0.); - if (!area.hydro.reservoirManagement || !area.hydro.useWaterValue) + if (!area->hydro.reservoirManagement || !area->hydro.useWaterValue) + { return; + } - if (!area.hydro.useWaterValue) + if (!area->hydro.useWaterValue) + { return; + } - double reservoirCapacity = area.hydro.reservoirCapacity; + double reservoirCapacity = area->hydro.reservoirCapacity; std::vector& niv = weeklyResults.niveauxHoraires; - Antares::Data::getWaterValue( - problem.previousSimulationFinalLevel[index] * 100 / reservoirCapacity, - area.hydro.waterValues, - weekFirstDay, - waterVal[0]); + waterVal[0] = Data::getWaterValue(problem.previousSimulationFinalLevel[index] * 100 + / reservoirCapacity, + area->hydro.waterValues, + weekFirstDay); + for (uint h = 1; h < nbHoursInAWeek; h++) { - Antares::Data::getWaterValue(niv[h - 1], - area.hydro.waterValues, - daysOfWeek[h / 24], - waterVal[h]); + waterVal[h] = Data::getWaterValue(niv[h - 1], + area->hydro.waterValues, + daysOfWeek[h / 24]); } - }); + } } -void updatingWeeklyFinalHydroLevel(const Data::AreaList& areas, - PROBLEME_HEBDO& problem) +void updatingWeeklyFinalHydroLevel(const Data::AreaList& areas, PROBLEME_HEBDO& problem) { - areas.each([&](const Data::Area& area) { - if (!area.hydro.reservoirManagement) - return; + for (const auto& [_, area]: areas) + { + if (!area->hydro.reservoirManagement) + { + continue; + } - uint index = area.index; + uint index = area->index; - double reservoirCapacity = area.hydro.reservoirCapacity; + double reservoirCapacity = area->hydro.reservoirCapacity; RESULTATS_HORAIRES& weeklyResults = problem.ResultatsHoraires[index]; std::vector& niv = weeklyResults.niveauxHoraires; - problem.previousSimulationFinalLevel[index] - = niv[nbHoursInAWeek - 1] * reservoirCapacity / 100; - }); -} - -void updatingAnnualFinalHydroLevel(const Data::AreaList& areas, PROBLEME_HEBDO& problem) -{ - if (!problem.hydroHotStart) - return; - - areas.each([&](const Data::Area& area) { - if (!area.hydro.reservoirManagement) - return; - - uint index = area.index; - - double reservoirCapacity = area.hydro.reservoirCapacity; - - problem.previousYearFinalLevels[index] - = problem.previousSimulationFinalLevel[index] / reservoirCapacity; - }); + problem.previousSimulationFinalLevel[index] = niv[nbHoursInAWeek - 1] * reservoirCapacity + / 100; + } } } // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/common-hydro-remix.cpp b/src/solver/simulation/common-hydro-remix.cpp index e2de5f9517..de8e3f5328 100644 --- a/src/solver/simulation/common-hydro-remix.cpp +++ b/src/solver/simulation/common-hydro-remix.cpp @@ -1,48 +1,44 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include +#include +#include + #include -#include "common-eco-adq.h" #include -#include -#include "simulation.h" #include - -using namespace Yuni; +#include +#include +#include "antares/solver/simulation/common-eco-adq.h" +#include "antares/study/simulation.h" #define EPSILON 1e-6 namespace Antares::Solver::Simulation { template -static bool Remix(const Data::AreaList& areas, PROBLEME_HEBDO& problem, uint numSpace, uint hourInYear) +static bool Remix(const Data::AreaList& areas, + PROBLEME_HEBDO& problem, + uint numSpace, + uint hourInYear) { double HE[168]; @@ -54,155 +50,172 @@ static bool Remix(const Data::AreaList& areas, PROBLEME_HEBDO& problem, uint num bool status = true; - areas.each([&](const Data::Area& area) { - auto index = area.index; - - auto& weeklyResults = problem.ResultatsHoraires[index]; - - auto& D = weeklyResults.ValeursHorairesDeDefaillancePositive; - - auto& S = weeklyResults.ValeursHorairesDeDefaillanceNegative; - - auto& H = weeklyResults.TurbinageHoraire; - - memset(remix, 0, sizeof(remix)); - memset(G, 0, sizeof(G)); - - uint endHour = step; - uint offset = 0; - for (; offset < 168; offset += step, endHour += step) - { - { - double WD = 0.; - for (uint i = offset; i != endHour; ++i) - WD += D[i]; - if (WD < EPSILON) - continue; - } - - double WH = 0.; - - for (uint i = offset; i != endHour; ++i) - { - if (S[i] < EPSILON) - WH += H[i]; - } - - if (WH < EPSILON) - continue; - - WH = 0.; - - double bottom = std::numeric_limits::max(); - double top = 0; - - uint loadTS = area.load.series->getIndex(problem.year); - auto& load = area.load.series->timeSeries; - assert(load.width > 0); - - auto& L = (loadTS < load.width) ? load[loadTS] : load[0]; - - const double* M = area.scratchpad[numSpace].dispatchableGenerationMargin; - - for (uint i = offset; i < endHour; ++i) - { - double h_d = H[i] + D[i]; - if (h_d > 0. && Math::Zero(S[i] + M[i])) - { - assert(i + hourInYear < load.height); - double Li = L[i + hourInYear]; - - remix[i] = true; - G[i] = Li - h_d; - - if (G[i] < bottom) - bottom = G[i]; - if (Li > top) - top = Li; - - WH += H[i]; - } - } - - const auto& P - = problem.CaracteristiquesHydrauliques[index].ContrainteDePmaxHydrauliqueHoraire; - - double ecart = 1.; - uint loop = 100; - do - { - double niveau = (top + bottom) * 0.5; - double stock = 0.; - - for (uint i = offset; i != endHour; ++i) - { - if (remix[i]) - { - double HEi; - uint iYear = i + hourInYear; - if (niveau > L[iYear]) - { - HEi = H[i] + D[i]; - if (HEi > P[i]) - { - HEi = P[i]; - DE[i] = H[i] + D[i] - HEi; - } - else - DE[i] = 0; - } - else - { - if (G[i] > niveau) - { - HEi = 0; - DE[i] = H[i] + D[i]; - } - else - { - HEi = niveau - G[i]; - if (HEi > P[i]) - HEi = P[i]; - DE[i] = H[i] + D[i] - HEi; - } - } - stock += HEi; - HE[i] = HEi; - } - else - { - HE[i] = H[i]; - DE[i] = D[i]; - } - } - - ecart = WH - stock; - if (ecart > 0.) - bottom = niveau; - else - top = niveau; - - if (!--loop) - { - status = false; - logs.error() << "hydro remix: " << area.name - << ": infinite loop detected. please check input data"; - break; - } - } while (Math::Abs(ecart) > 0.01); - - for (uint i = offset; i != endHour; ++i) - { - H[i] = HE[i]; - assert(not Math::NaN(HE[i]) && "hydro remix: nan detected"); - } - for (uint i = offset; i != endHour; ++i) - { - D[i] = DE[i]; - assert(not Math::NaN(DE[i]) && "hydro remix: nan detected"); - } - } - }); + areas.each( + [&HE, &DE, &remix, &G, &status, &problem, &numSpace, &hourInYear](const Data::Area& area) + { + auto index = area.index; + + auto& weeklyResults = problem.ResultatsHoraires[index]; + + auto& D = weeklyResults.ValeursHorairesDeDefaillancePositive; + + auto& S = weeklyResults.ValeursHorairesDeDefaillanceNegative; + + auto& H = weeklyResults.TurbinageHoraire; + + memset(remix, 0, sizeof(remix)); + memset(G, 0, sizeof(G)); + + uint endHour = step; + uint offset = 0; + for (; offset < 168; offset += step, endHour += step) + { + { + double WD = 0.; + for (uint i = offset; i != endHour; ++i) + { + WD += D[i]; + } + if (WD < EPSILON) + { + continue; + } + } + + double WH = 0.; + + for (uint i = offset; i != endHour; ++i) + { + if (S[i] < EPSILON) + { + WH += H[i]; + } + } + + if (WH < EPSILON) + { + continue; + } + + WH = 0.; + + double bottom = std::numeric_limits::max(); + double top = 0; + + auto* L = area.load.series.getColumn(problem.year); + + const double* M = area.scratchpad[numSpace].dispatchableGenerationMargin; + + for (uint i = offset; i < endHour; ++i) + { + double h_d = H[i] + D[i]; + if (h_d > 0. && Utils::isZero(S[i] + M[i])) + { + double Li = L[i + hourInYear]; + + remix[i] = true; + G[i] = Li - h_d; + + if (G[i] < bottom) + { + bottom = G[i]; + } + if (Li > top) + { + top = Li; + } + + WH += H[i]; + } + } + + const auto& P = problem.CaracteristiquesHydrauliques[index] + .ContrainteDePmaxHydrauliqueHoraire; + + double ecart = 1.; + uint loop = 100; + do + { + double niveau = (top + bottom) * 0.5; + double stock = 0.; + + for (uint i = offset; i != endHour; ++i) + { + if (remix[i]) + { + double HEi; + uint iYear = i + hourInYear; + if (niveau > L[iYear]) + { + HEi = H[i] + D[i]; + if (HEi > P[i]) + { + HEi = P[i]; + DE[i] = H[i] + D[i] - HEi; + } + else + { + DE[i] = 0; + } + } + else + { + if (G[i] > niveau) + { + HEi = 0; + DE[i] = H[i] + D[i]; + } + else + { + HEi = niveau - G[i]; + if (HEi > P[i]) + { + HEi = P[i]; + } + DE[i] = H[i] + D[i] - HEi; + } + } + stock += HEi; + HE[i] = HEi; + } + else + { + HE[i] = H[i]; + DE[i] = D[i]; + } + } + + ecart = WH - stock; + if (ecart > 0.) + { + bottom = niveau; + } + else + { + top = niveau; + } + + if (!--loop) + { + status = false; + logs.error() << "hydro remix: " << area.name + << ": infinite loop detected. please check input data"; + break; + } + } while (std::abs(ecart) > 0.01); + + for (uint i = offset; i != endHour; ++i) + { + H[i] = HE[i]; + assert(not std::isnan(HE[i]) && "hydro remix: nan detected"); + } + for (uint i = offset; i != endHour; ++i) + { + D[i] = DE[i]; + assert(not std::isnan(DE[i]) && "hydro remix: nan detected"); + } + } + }); return status; } diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 5caaf948fe..f14d4cabf0 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -1,47 +1,45 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "economy.h" -#include + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/simulation/economy.h" + #include -#include "simulation.h" -#include "../optimisation/opt_fonctions.h" -#include "../optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h" -#include "common-eco-adq.h" +#include +#include "antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h" +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/common-eco-adq.h" +#include "antares/solver/simulation/simulation.h" using namespace Yuni; using Antares::Constants::nbHoursInAWeek; namespace Antares::Solver::Simulation { -Economy::Economy(Data::Study& study, IResultWriter& resultWriter) : +Economy::Economy(Data::Study& study, + IResultWriter& resultWriter, + Simulation::ISimulationObserver& simulationObserver): study(study), preproOnly(false), - resultWriter(resultWriter) + resultWriter(resultWriter), + simulationObserver_(simulationObserver) { } @@ -78,84 +76,94 @@ bool Economy::simulationBegin() for (uint numSpace = 0; numSpace < pNbMaxPerformedYearsInParallel; numSpace++) { - SIM_InitialisationProblemeHebdo(study, pProblemesHebdo[numSpace], 168, numSpace); - - if ((uint)nbHoursInAWeek != (uint)pProblemesHebdo[numSpace].NombreDePasDeTemps) - { - logs.fatal() << "internal error"; - return false; - } + SIM_InitialisationProblemeHebdo(study, + pProblemesHebdo[numSpace], + nbHoursInAWeek, + numSpace); auto options = createOptimizationOptions(study); - weeklyOptProblems_[numSpace] = - Antares::Solver::Optimization::WeeklyOptimization::create( - study, - options, - study.parameters.adqPatchParams, - &pProblemesHebdo[numSpace], - numSpace, - resultWriter); - postProcessesList_[numSpace] = - interfacePostProcessList::create(study.parameters.adqPatchParams, - &pProblemesHebdo[numSpace], - numSpace, - study.areas, - study.parameters.shedding.policy, - study.parameters.simplexOptimizationRange, - study.calendar); + weeklyOptProblems_[numSpace] = Antares::Solver::Optimization::WeeklyOptimization:: + create(study, + options, + study.parameters.adqPatchParams, + &pProblemesHebdo[numSpace], + numSpace, + resultWriter, + simulationObserver_.get()); + postProcessesList_[numSpace] = interfacePostProcessList::create( + study.parameters.adqPatchParams, + &pProblemesHebdo[numSpace], + numSpace, + study.areas, + study.parameters.shedding.policy, + study.parameters.simplexOptimizationRange, + study.calendar); } } - for (auto& pb : pProblemesHebdo) + for (auto& pb: pProblemesHebdo) + { pb.TypeDOptimisation = OPTIMISATION_LINEAIRE; + } pStartTime = study.calendar.days[study.parameters.simulationDays.first].hours.first; pNbWeeks = study.parameters.simulationDays.numberOfWeeks(); return true; } - bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, yearRandomNumbers& randomForYear, std::list& failedWeekList, bool isFirstPerformedYearOfSimulation, - const ALL_HYDRO_VENTILATION_RESULTS& hydroVentilationResults, - OptimizationStatisticsWriter& optWriter) + const HYDRO_VENTILATION_RESULTS& hydroVentilationResults, + OptimizationStatisticsWriter& optWriter, + const Antares::Data::Area::ScratchMap& scratchmap) { // No failed week at year start failedWeekList.clear(); - pProblemesHebdo[numSpace].year = state.year; + auto& currentProblem = pProblemesHebdo[numSpace]; + currentProblem.year = state.year; - PrepareRandomNumbers(study, pProblemesHebdo[numSpace], randomForYear); + PrepareRandomNumbers(study, currentProblem, randomForYear); + SetInitialHydroLevel(study, currentProblem, hydroVentilationResults); state.startANewYear(); int hourInTheYear = pStartTime; if (isFirstPerformedYearOfSimulation) - pProblemesHebdo[numSpace].firstWeekOfSimulation = true; + { + currentProblem.firstWeekOfSimulation = true; + } bool reinitOptim = true; for (uint w = 0; w != pNbWeeks; ++w) { state.hourInTheYear = hourInTheYear; - pProblemesHebdo[numSpace].weekInTheYear = state.weekInTheYear = w; - pProblemesHebdo[numSpace].HeureDansLAnnee = hourInTheYear; - - ::SIM_RenseignementProblemeHebdo(study, pProblemesHebdo[numSpace], state.weekInTheYear, - numSpace, hourInTheYear, hydroVentilationResults); - - BuildThermalPartOfWeeklyProblem(study, pProblemesHebdo[numSpace], - hourInTheYear, randomForYear.pThermalNoisesByArea, state.year); + currentProblem.weekInTheYear = state.weekInTheYear = w; + currentProblem.HeureDansLAnnee = hourInTheYear; + + ::SIM_RenseignementProblemeHebdo(study, + currentProblem, + state.weekInTheYear, + hourInTheYear, + hydroVentilationResults, + scratchmap); + + BuildThermalPartOfWeeklyProblem(study, + currentProblem, + hourInTheYear, + randomForYear.pThermalNoisesByArea, + state.year); // Reinit optimisation if needed - pProblemesHebdo[numSpace].ReinitOptimisation = reinitOptim; + currentProblem.ReinitOptimisation = reinitOptim; reinitOptim = false; try { - weeklyOptProblems_[numSpace]->solve(w, hourInTheYear); + weeklyOptProblems_[numSpace]->solve(); // Runs all the post processes in the list of post-process commands optRuntimeData opt_runtime_data(state.year, w, hourInTheYear); @@ -169,7 +177,7 @@ bool Economy::year(Progression::Task& progression, { state.hourInTheWeek = hw; - state.ntc = pProblemesHebdo[numSpace].ValeursDeNTC[hw]; + state.ntc = currentProblem.ValeursDeNTC[hw]; variables.hourBegin(state.hourInTheYear); @@ -184,12 +192,10 @@ bool Economy::year(Progression::Task& progression, for (int opt = 0; opt < 7; opt++) { - state.optimalSolutionCost1 += pProblemesHebdo[numSpace].coutOptimalSolution1[opt]; - state.optimalSolutionCost2 += pProblemesHebdo[numSpace].coutOptimalSolution2[opt]; + state.optimalSolutionCost1 += currentProblem.coutOptimalSolution1[opt]; + state.optimalSolutionCost2 += currentProblem.coutOptimalSolution2[opt]; } - optWriter.addTime(w, - pProblemesHebdo[numSpace].tempsResolution1[0], - pProblemesHebdo[numSpace].tempsResolution2[0]); + optWriter.addTime(w, currentProblem.timeMeasure); } catch (Data::AssertionError& ex) { @@ -220,15 +226,13 @@ bool Economy::year(Progression::Task& progression, hourInTheYear += nbHoursInAWeek; - pProblemesHebdo[numSpace].firstWeekOfSimulation = false; + currentProblem.firstWeekOfSimulation = false; ++progression; } - updatingAnnualFinalHydroLevel(study.areas, pProblemesHebdo[numSpace]); - optWriter.finalize(); - finalizeOptimizationStatistics(pProblemesHebdo[numSpace], state); + finalizeOptimizationStatistics(currentProblem, state); return true; } @@ -236,7 +240,9 @@ bool Economy::year(Progression::Task& progression, void Economy::incrementProgression(Progression::Task& progression) { for (uint w = 0; w < pNbWeeks; ++w) + { ++progression; + } } // Retrieve weighted average balance for each area @@ -264,9 +270,25 @@ void Economy::simulationEnd() } } -void Economy::prepareClustersInMustRunMode(uint numSpace, uint year) +void Economy::prepareClustersInMustRunMode(Data::Area::ScratchMap& scratchmap, uint year) { - PrepareDataFromClustersInMustrunMode(study, numSpace, year); + for (uint i = 0; i < study.areas.size(); ++i) + { + auto& area = *study.areas[i]; + auto& scratchpad = scratchmap.at(&area); + + std::ranges::fill(scratchpad.mustrunSum, 0); + + auto& mrs = scratchpad.mustrunSum; + for (const auto& cluster: area.thermal.list.each_mustrun_and_enabled()) + { + const auto& availableProduction = cluster->series.getColumn(year); + for (uint h = 0; h != cluster->series.timeSeries.height; ++h) + { + mrs[h] += availableProduction[h]; + } + } + } } } // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h deleted file mode 100644 index 7eb8c174f5..0000000000 --- a/src/solver/simulation/economy.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_ECONOMY_H__ -#define __SOLVER_SIMULATION_ECONOMY_H__ - -#include "../variable/variable.h" -#include "../variable/economy/all.h" -#include "../variable/state.h" - -#include "../optimisation/base_weekly_optimization.h" -#include "base_post_process.h" - -#include "solver.h" // for definition of type yearRandomNumbers -#include "antares/infoCollection/StudyInfoCollector.h" -#include "opt_time_writer.h" - -namespace Antares::Solver::Simulation -{ -class Economy -{ -public: - //! Name of the type of simulation - static const char* Name() - { - return "economy"; - } - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Constructor - ** - ** \param study The current study - */ - Economy(Data::Study& study, IResultWriter& resultWriter); - //! Destructor - ~Economy() = default; - //@} - - Benchmarking::OptimizationInfo getOptimizationInfo() const; - -public: - //! Current study - Data::Study& study; - //! All variables - Solver::Variable::Economy::AllVariables variables; - //! Prepro only - bool preproOnly; - -protected: - void setNbPerformedYearsInParallel(uint nbMaxPerformedYearsInParallel); - - bool simulationBegin(); - - bool year(Progression::Task& progression, - Variable::State& state, - uint numSpace, - yearRandomNumbers& randomForYear, - std::list& failedWeekList, - bool isFirstPerformedYearOfSimulation, - const ALL_HYDRO_VENTILATION_RESULTS&, - OptimizationStatisticsWriter& optWriter); - - void incrementProgression(Progression::Task& progression); - - void simulationEnd(); - - /*! - ** \brief Prepare clusters in 'must-run' mode - */ - void prepareClustersInMustRunMode(uint numSpace, uint year); - - void initializeState(Variable::State& state, uint numSpace); - -private: - uint pNbWeeks; - uint pStartTime; - uint pNbMaxPerformedYearsInParallel; - bool pPreproOnly; - std::vector pProblemesHebdo; - std::vector> weeklyOptProblems_; - std::vector> postProcessesList_; - IResultWriter& resultWriter; -}; // class Economy - -} // namespace Antares::Solver::Simulation - -#endif // __SOLVER_SIMULATION_ECONOMY_H__ diff --git a/src/solver/simulation/economy_mode.cpp b/src/solver/simulation/economy_mode.cpp new file mode 100644 index 0000000000..12a1b24297 --- /dev/null +++ b/src/solver/simulation/economy_mode.cpp @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#include "antares/solver/simulation/economy_mode.h" + +#include "antares/solver/simulation/economy.h" +#include "antares/solver/simulation/solver.h" + +namespace Antares::Solver +{ +void runSimulationInEconomicMode(Antares::Data::Study& study, + const Settings& settings, + Benchmarking::DurationCollector& durationCollector, + IResultWriter& resultWriter, + Benchmarking::OptimizationInfo& info, + Simulation::ISimulationObserver& simulationObserver) +{ + // Type of the simulation + typedef Solver::Simulation::ISimulation SimulationType; + SimulationType simulation(study, settings, durationCollector, resultWriter, simulationObserver); + simulation.checkWriter(); + simulation.run(); + + if (!(settings.noOutput || settings.tsGeneratorsOnly)) + { + durationCollector("synthesis_export") + << [&simulation] { simulation.writeResults(/*synthesis:*/ true); }; + + info = simulation.getOptimizationInfo(); + } +} +} // namespace Antares::Solver diff --git a/src/solver/simulation/include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h b/src/solver/simulation/include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h new file mode 100644 index 0000000000..8030c4427a --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include + +#include +#include "antares/study/binding_constraint/BindingConstraintsRepository.h" + +#include "ITimeSeriesNumbersWriter.h" + +namespace Antares::Solver::Simulation +{ +class BindingConstraintsTimeSeriesNumbersWriter: public ITimeSeriesNumbersWriter +{ +public: + explicit BindingConstraintsTimeSeriesNumbersWriter(IResultWriter& resultWriter); + BindingConstraintsTimeSeriesNumbersWriter() = delete; + void write( + const Data::BindingConstraintGroupRepository& bindingConstraintGroupRepository) override; + +private: + IResultWriter& writer_; +}; +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/include/antares/solver/simulation/ISimulationObserver.h b/src/solver/simulation/include/antares/solver/simulation/ISimulationObserver.h new file mode 100644 index 0000000000..fe6145dd0f --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/ISimulationObserver.h @@ -0,0 +1,66 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "sim_structure_probleme_economique.h" + +namespace Antares::Solver::Simulation +{ + +/** + * @class ISimulationObserver + * @brief The ISimulationObserver class is an interface for observing the simulation. + * @details It declares the notifyHebdoProblem method. + */ +class ISimulationObserver +{ +public: + virtual ~ISimulationObserver() = default; + /** + * @brief The notifyHebdoProblem method is used to notify of a problem during the simulation. + * @param problemeHebdo A pointer to a PROBLEME_HEBDO object representing the problem. + * @param optimizationNumber The number of the optimization. + * @param name The name of the problem. + */ + virtual void notifyHebdoProblem(const PROBLEME_HEBDO& problemeHebdo, + int optimizationNumber, + std::string_view name) + = 0; +}; + +/** + * @class NullSimulationObserver + * @brief The NullSimulationObserver class is a null object for the ISimulationObserver interface. + * @details It overrides the notifyHebdoProblem method with an empty implementation. + */ +class NullSimulationObserver: public ISimulationObserver +{ +public: + ~NullSimulationObserver() override = default; + + void notifyHebdoProblem(const PROBLEME_HEBDO&, int, std::string_view) override + { + // null object pattern + } +}; +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/include/antares/solver/simulation/ITimeSeriesNumbersWriter.h b/src/solver/simulation/include/antares/solver/simulation/ITimeSeriesNumbersWriter.h new file mode 100644 index 0000000000..f8e7cc7fc0 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/ITimeSeriesNumbersWriter.h @@ -0,0 +1,33 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once +#include "antares/study/binding_constraint/BindingConstraintGroupRepository.h" + +namespace Antares::Solver::Simulation +{ +class ITimeSeriesNumbersWriter +{ +public: + virtual ~ITimeSeriesNumbersWriter() = default; + virtual void write(const Data::BindingConstraintGroupRepository& list) = 0; +}; +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/include/antares/solver/simulation/adequacy.h b/src/solver/simulation/include/antares/solver/simulation/adequacy.h new file mode 100644 index 0000000000..4e04acdcbe --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/adequacy.h @@ -0,0 +1,110 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_ADEQUACY_H__ +#define __SOLVER_SIMULATION_ADEQUACY_H__ + +#include "antares/infoCollection/StudyInfoCollector.h" +#include "antares/solver/simulation/common-eco-adq.h" +#include "antares/solver/simulation/opt_time_writer.h" +#include "antares/solver/simulation/solver.h" // for definition of type yearRandomNumbers +#include "antares/solver/variable/adequacy/all.h" +#include "antares/solver/variable/economy/all.h" +#include "antares/solver/variable/state.h" +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Simulation +{ +class Adequacy +{ +public: + //! Name of the type of simulation + static const char* Name() + { + return "adequacy"; + } + + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Constructor + ** + ** \param study The current study + */ + Adequacy(Data::Study& study, + IResultWriter& resultWriter, + Simulation::ISimulationObserver& simulationObserver); + //! Destructor + ~Adequacy() = default; + //@} + + Benchmarking::OptimizationInfo getOptimizationInfo() const; + + //! Current study + Data::Study& study; + //! All variables + Solver::Variable::Adequacy::AllVariables variables; + //! Prepro only + bool preproOnly = false; + +protected: + void setNbPerformedYearsInParallel(uint nbMaxPerformedYearsInParallel); + + bool simulationBegin(); + + bool year(Progression::Task& progression, + Variable::State& state, + uint numSpace, + yearRandomNumbers& randomForYear, + std::list& failedWeekList, + bool isFirstPerformedYearOfSimulation, + const HYDRO_VENTILATION_RESULTS&, + OptimizationStatisticsWriter& optWriter, + const Antares::Data::Area::ScratchMap& scratchmap); + + void incrementProgression(Progression::Task& progression) const; + + void simulationEnd(); + + /*! + ** \brief Prepare clusters in 'must-run' mode + */ + void prepareClustersInMustRunMode(Data::Area::ScratchMap& scratchmap, uint year); + + void initializeState(Variable::State& state, uint numSpace); + +private: + bool simplexIsRequired(uint hourInTheYear, + uint numSpace, + const HYDRO_VENTILATION_RESULTS&) const; + + uint pNbWeeks; + uint pStartTime; + uint pNbMaxPerformedYearsInParallel; + std::vector pProblemesHebdo; + Matrix<> pRES; + IResultWriter& resultWriter; + + std::reference_wrapper simulationObserver_; +}; // class Adequacy + +} // namespace Antares::Solver::Simulation + +#endif // __SOLVER_SIMULATION_ADEQUACY_H__ diff --git a/src/solver/simulation/include/antares/solver/simulation/adequacy_mode.h b/src/solver/simulation/include/antares/solver/simulation/adequacy_mode.h new file mode 100644 index 0000000000..66734027b9 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/adequacy_mode.h @@ -0,0 +1,38 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/infoCollection/StudyInfoCollector.h" +#include "antares/solver/misc/options.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/writer/i_writer.h" + +namespace Antares::Solver +{ +void runSimulationInAdequacyMode(Antares::Data::Study& study, + const Settings& settings, + Benchmarking::DurationCollector& durationCollector, + IResultWriter& resultWriter, + Benchmarking::OptimizationInfo& info, + Simulation::ISimulationObserver& simulationObserver); +} diff --git a/src/solver/simulation/include/antares/solver/simulation/adequacy_patch_runtime_data.h b/src/solver/simulation/include/antares/solver/simulation/adequacy_patch_runtime_data.h new file mode 100644 index 0000000000..f91576a233 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/adequacy_patch_runtime_data.h @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once +#include +#include + +#include +#include + +using adqPatchParamsMode = Antares::Data::AdequacyPatch::AdequacyPatchMode; + +class AdequacyPatchRuntimeData +{ +private: + std::vector> csrTriggeredHoursPerArea_; + +public: + explicit AdequacyPatchRuntimeData() = default; + AdequacyPatchRuntimeData(const Antares::Data::AreaList& areas, + const std::vector& links); + + std::vector areaMode; + std::vector originAreaMode; + std::vector extremityAreaMode; + std::vector hurdleCostCoefficients; + bool AdequacyFirstStep = true; + + bool wasCSRTriggeredAtAreaHour(int area, int hour) const; + void addCSRTriggeredAtAreaHour(int area, int hour); +}; diff --git a/src/solver/simulation/include/antares/solver/simulation/apply-scenario.h b/src/solver/simulation/include/antares/solver/simulation/apply-scenario.h new file mode 100644 index 0000000000..60724ed89b --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/apply-scenario.h @@ -0,0 +1,31 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_APPLY_SCENARIO_H__ +#define __SOLVER_SIMULATION_APPLY_SCENARIO_H__ + +#include + +namespace Antares::Solver +{ +void ApplyCustomScenario(Data::Study& study); +} // namespace Antares::Solver + +#endif // __SOLVER_SIMULATION_APPLY_SCENARIO_H__ diff --git a/src/solver/simulation/include/antares/solver/simulation/base_post_process.h b/src/solver/simulation/include/antares/solver/simulation/base_post_process.h new file mode 100644 index 0000000000..6918fb85d3 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/base_post_process.h @@ -0,0 +1,91 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include + +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +using namespace Antares::Data; +using namespace Antares::Date; +using AdqPatchParams = Antares::Data::AdequacyPatch::AdqPatchParams; + +namespace Antares::Solver::Simulation +{ + +struct optRuntimeData +{ + optRuntimeData(unsigned int y, unsigned int w, unsigned int h): + year(y), + week(w), + hourInTheYear(h) + { + } + + unsigned int year = 0; + unsigned int week = 0; + unsigned int hourInTheYear = 0; +}; + +class basePostProcessCommand +{ +public: + virtual ~basePostProcessCommand() = default; + virtual void execute(const optRuntimeData& opt_runtime_data) = 0; + +protected: + // Memeber functions + basePostProcessCommand(PROBLEME_HEBDO* problemeHebdo); + + // Data members + PROBLEME_HEBDO* problemeHebdo_; +}; + +class interfacePostProcessList +{ +public: + virtual ~interfacePostProcessList() = default; + + // gp : we should put all these arguments in a structure, so that we pass a structure + // gp : to the create(...) method, and to underlying calls to constructors. + // gp : In case we need new data for a new post process, we would not have to change + // gp : the constructors' signatures of the post process list classes. + static std::unique_ptr create(AdqPatchParams& adqPatchParams, + PROBLEME_HEBDO* problemeHebdo, + uint thread_number, + AreaList& areas, + SheddingPolicy sheddingPolicy, + SimplexOptimization splxOptimization, + Calendar& calendar); + void runAll(const optRuntimeData& opt_runtime_data); + +protected: + // Member functions + interfacePostProcessList(PROBLEME_HEBDO* problemeHebdo, uint thread_number); + + // Data mambers + PROBLEME_HEBDO* const problemeHebdo_ = nullptr; + const unsigned int thread_number_ = 0; + std::vector> post_process_list; +}; + +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/common-eco-adq.h b/src/solver/simulation/include/antares/solver/simulation/common-eco-adq.h similarity index 75% rename from src/solver/simulation/common-eco-adq.h rename to src/solver/simulation/include/antares/solver/simulation/common-eco-adq.h index 3d1f47c3b0..0bf24cd71d 100644 --- a/src/solver/simulation/common-eco-adq.h +++ b/src/solver/simulation/include/antares/solver/simulation/common-eco-adq.h @@ -1,43 +1,37 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_SIMULATION_COMMON_ECONOMY_ADEQUACY_H__ #define __SOLVER_SIMULATION_COMMON_ECONOMY_ADEQUACY_H__ +#include + #include -#include -#include "../variable/variable.h" -#include "../optimisation/opt_fonctions.h" -#include "../variable/economy/all.h" #include -#include "../variable/economy/dispatchable-generation-margin.h" // for OP.MRG - -#include "solver.h" // for definition of type yearRandomNumbers -#include +#include +#include "antares/solver/optimisation/opt_fonctions.h" +#include "antares/solver/simulation/solver.h" // for definition of type yearRandomNumbers +#include "antares/solver/variable/economy/all.h" +#include "antares/solver/variable/economy/dispatchable-generation-margin.h" // for OP.MRG +#include "antares/solver/variable/variable.h" namespace Antares { @@ -62,17 +56,16 @@ void PrepareRandomNumbers(Data::Study& study, PROBLEME_HEBDO& problem, yearRandomNumbers& randomForYear); +void SetInitialHydroLevel(Data::Study& study, + PROBLEME_HEBDO& problem, + const HYDRO_VENTILATION_RESULTS& hydroVentilationResults); + void BuildThermalPartOfWeeklyProblem(Data::Study& study, PROBLEME_HEBDO& problem, const int PasDeTempsDebut, double** thermalNoises, unsigned int year); -/*! -** \brief Prepare data from clusters in mustrun mode (eco+adq) -*/ -void PrepareDataFromClustersInMustrunMode(Data::Study& study, uint numSpace, uint year); - /*! ** \brief Get if the quadratic optimization should be used according ** to the input data (eco+adq) @@ -117,7 +110,6 @@ void computingHydroLevels(const Data::AreaList& areas, bool remixWasRun, bool computeAnyway = false); - /* ** \brief Interpolates water values related to reservoir levels for outputs only ** @@ -140,16 +132,7 @@ void interpolateWaterValue(const Data::AreaList& areas, ** \param areas : the areas of study ** \param problem The weekly problem, from the solver */ -void updatingWeeklyFinalHydroLevel(const Data::AreaList& areas, - PROBLEME_HEBDO& problem); - -/* -** \brief Updating the year final reservoir level, to be used as a start for the year. -** -** \param areas : the areas of study -** \param problem The weekly problem, living over the whole simuation. -*/ -void updatingAnnualFinalHydroLevel(const Data::AreaList& areas, PROBLEME_HEBDO& problem); +void updatingWeeklyFinalHydroLevel(const Data::AreaList& areas, PROBLEME_HEBDO& problem); /* ** \brief Compute the weighted average NTC for a link @@ -161,7 +144,7 @@ void updatingAnnualFinalHydroLevel(const Data::AreaList& areas, PROBLEME_HEBDO& */ int retrieveAverageNTC(const Data::Study& study, const Matrix<>& capacities, - const Matrix& tsNumbers, + const Data::TimeSeriesNumbers& tsNumbers, std::vector& avg); void finalizeOptimizationStatistics(PROBLEME_HEBDO& problem, diff --git a/src/solver/simulation/include/antares/solver/simulation/economy.h b/src/solver/simulation/include/antares/solver/simulation/economy.h new file mode 100644 index 0000000000..592fac59f8 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/economy.h @@ -0,0 +1,110 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_ECONOMY_H__ +#define __SOLVER_SIMULATION_ECONOMY_H__ + +#include "antares/infoCollection/StudyInfoCollector.h" +#include "antares/solver/optimisation/base_weekly_optimization.h" +#include "antares/solver/simulation/opt_time_writer.h" +#include "antares/solver/simulation/solver.h" // for definition of type yearRandomNumbers +#include "antares/solver/variable/economy/all.h" +#include "antares/solver/variable/state.h" +#include "antares/solver/variable/variable.h" + +#include "base_post_process.h" + +namespace Antares::Solver::Simulation +{ +class Economy +{ +public: + //! Name of the type of simulation + static const char* Name() + { + return "economy"; + } + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Constructor + ** + ** \param study The current study + */ + Economy(Data::Study& study, + IResultWriter& resultWriter, + Simulation::ISimulationObserver& simulationObserver); + //! Destructor + ~Economy() = default; + //@} + + Benchmarking::OptimizationInfo getOptimizationInfo() const; + +public: + //! Current study + Data::Study& study; + //! All variables + Solver::Variable::Economy::AllVariables variables; + //! Prepro only + bool preproOnly; + +protected: + void setNbPerformedYearsInParallel(uint nbMaxPerformedYearsInParallel); + + bool simulationBegin(); + + bool year(Progression::Task& progression, + Variable::State& state, + uint numSpace, + yearRandomNumbers& randomForYear, + std::list& failedWeekList, + bool isFirstPerformedYearOfSimulation, + const HYDRO_VENTILATION_RESULTS&, + OptimizationStatisticsWriter& optWriter, + const Antares::Data::Area::ScratchMap& scratchmap); + + void incrementProgression(Progression::Task& progression); + + void simulationEnd(); + + /*! + ** \brief Prepare clusters in 'must-run' mode + */ + void prepareClustersInMustRunMode(Data::Area::ScratchMap& scratchmap, uint year); + + void initializeState(Variable::State& state, uint numSpace); + +private: + uint pNbWeeks; + uint pStartTime; + uint pNbMaxPerformedYearsInParallel; + std::vector pProblemesHebdo; + std::vector> + weeklyOptProblems_; + std::vector> postProcessesList_; + IResultWriter& resultWriter; + std::reference_wrapper simulationObserver_; +}; // class Economy + +} // namespace Antares::Solver::Simulation + +#endif // __SOLVER_SIMULATION_ECONOMY_H__ diff --git a/src/solver/simulation/include/antares/solver/simulation/economy_mode.h b/src/solver/simulation/include/antares/solver/simulation/economy_mode.h new file mode 100644 index 0000000000..e26ebbb7e0 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/economy_mode.h @@ -0,0 +1,38 @@ + +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include "antares/infoCollection/StudyInfoCollector.h" +#include "antares/solver/misc/options.h" +#include "antares/solver/simulation/ISimulationObserver.h" +#include "antares/writer/i_writer.h" + +namespace Antares::Solver +{ +void runSimulationInEconomicMode(Antares::Data::Study& study, + const Settings& settings, + Benchmarking::DurationCollector& durationCollector, + IResultWriter& resultWriter, + Benchmarking::OptimizationInfo& info, + Simulation::ISimulationObserver& simulationObserver); +} diff --git a/src/solver/simulation/include/antares/solver/simulation/opt_time_writer.h b/src/solver/simulation/include/antares/solver/simulation/opt_time_writer.h new file mode 100644 index 0000000000..4c9ccf3f31 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/opt_time_writer.h @@ -0,0 +1,41 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include + +#include +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "simulation.h" + +class OptimizationStatisticsWriter +{ +public: + void addTime(uint week, const TIME_MEASURES& timeMeasure); + OptimizationStatisticsWriter(Antares::Solver::IResultWriter& writer, uint year); + void finalize(); + +private: + void printHeader(); + std::ostringstream pBuffer; + uint pYear; + Antares::Solver::IResultWriter& pWriter; +}; diff --git a/src/solver/simulation/include/antares/solver/simulation/sim_alloc_probleme_hebdo.h b/src/solver/simulation/include/antares/solver/simulation/sim_alloc_probleme_hebdo.h new file mode 100644 index 0000000000..f1ed9bca0c --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/sim_alloc_probleme_hebdo.h @@ -0,0 +1,45 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include "antares/config/config.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +void SIM_AllocationProblemeDonneesGenerales(PROBLEME_HEBDO& problem, + const Antares::Data::Study& study, + unsigned NombreDePasDeTemps); + +void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, + const Antares::Data::Study& study, + unsigned NombreDePasDeTemps); + +void SIM_AllocationLinks(PROBLEME_HEBDO& problem, + const uint linkCount, + unsigned NombreDePasDeTemps); + +void SIM_AllocationConstraints(PROBLEME_HEBDO& problem, + const Antares::Data::Study& study, + unsigned NombreDePasDeTemps); + +void SIM_AllocateAreas(PROBLEME_HEBDO& problem, + const Antares::Data::Study& study, + unsigned NombreDePasDeTemps); diff --git a/src/solver/simulation/include/antares/solver/simulation/sim_constants.h b/src/solver/simulation/include/antares/solver/simulation/sim_constants.h new file mode 100644 index 0000000000..2c131b319e --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/sim_constants.h @@ -0,0 +1,30 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +constexpr double LINFINI_ANTARES = 1.e+80; +constexpr int LINFINI_ENTIER = 20000000; + +constexpr char OPTIMISATION_LINEAIRE = 1; +constexpr char OPTIMISATION_QUADRATIQUE = 2; + +constexpr double ZERO_RESERVE_J_MOINS1 = 1.e-2; diff --git a/src/solver/simulation/include/antares/solver/simulation/sim_extern_variables_globales.h b/src/solver/simulation/include/antares/solver/simulation/sim_extern_variables_globales.h new file mode 100644 index 0000000000..d6c526b37e --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/sim_extern_variables_globales.h @@ -0,0 +1,34 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_EXTERN_H__ +#define __SOLVER_SIMULATION_EXTERN_H__ + +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +#include "sim_structure_donnees.h" + +/* Valeurs generees de maniere aleatoire */ + +/* Resultats */ +/*-Economique-*/ +extern std::vector> transitMoyenInterconnexionsRecalculQuadratique; + +#endif /* __SOLVER_SIMULATION_EXTERN_H__ */ diff --git a/src/solver/simulation/include/antares/solver/simulation/sim_spread_generator.h b/src/solver/simulation/include/antares/solver/simulation/sim_spread_generator.h new file mode 100644 index 0000000000..c28ec9a75a --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/sim_spread_generator.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#pragma once + +#include + +namespace SIM +{ +class SpreadGenerator +{ + static constexpr double rangeDefault = 1.e-3; + +public: + explicit SpreadGenerator(double range = rangeDefault); + void reset(unsigned int seed); + double generate(); + +private: + Antares::MersenneTwister mt_; + const double range_; +}; +} // namespace SIM diff --git a/src/solver/simulation/include/antares/solver/simulation/sim_structure_donnees.h b/src/solver/simulation/include/antares/solver/simulation/sim_structure_donnees.h new file mode 100644 index 0000000000..8e58abaa96 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/sim_structure_donnees.h @@ -0,0 +1,32 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_DATA_STRUCTS_H__ +#define __SOLVER_SIMULATION_DATA_STRUCTS_H__ + +typedef struct +{ + double* Horaire; +} PRODUCTION_THERMIQUE; + +/* Old define */ +#define DEFINITION_STRUCTURES_DONNEES + +#endif /* __SOLVER_SIMULATION_DATA_STRUCTS_H__ */ diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/include/antares/solver/simulation/sim_structure_probleme_economique.h similarity index 83% rename from src/solver/simulation/sim_structure_probleme_economique.h rename to src/solver/simulation/include/antares/solver/simulation/sim_structure_probleme_economique.h index 5a94273a9b..66400ed678 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/include/antares/solver/simulation/sim_structure_probleme_economique.h @@ -1,40 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_SIMULATION_ECO_STRUCTS_H__ #define __SOLVER_SIMULATION_ECO_STRUCTS_H__ -#include "../optimisation/opt_structure_probleme_a_resoudre.h" -#include "../utils/optimization_statistics.h" -#include "../../libs/antares/study/fwd.h" -#include "../../libs/antares/study/study.h" -#include -#include #include +#include +#include + +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/utils/optimization_statistics.h" +#include "antares/study/fwd.h" +#include "antares/study/study.h" class AdequacyPatchRuntimeData; @@ -163,6 +158,8 @@ struct CONTRAINTES_COUPLANTES std::vector OffsetTemporelSurLePalierDispatch; const char* NomDeLaContrainteCouplante; + + std::shared_ptr bindingConstraint; }; namespace ShortTermStorage @@ -193,11 +190,6 @@ struct RESULTS }; } // namespace ShortTermStorage -struct RESULTATS_CONTRAINTES_COUPLANTES -{ - std::vector variablesDuales; -}; - struct DEMAND_MARKET_POOL { double* TotalDemandOfMarketPool; @@ -258,12 +250,8 @@ struct PDISP_ET_COUTS_HORAIRES_PAR_PALIER std::vector CoutHoraireDeProductionDuPalierThermique; - std::vector CoutHoraireDuPalierThermiqueUp; - std::vector CoutHoraireDuPalierThermiqueDown; - std::vector NombreMaxDeGroupesEnMarcheDuPalierThermique; std::vector NombreMinDeGroupesEnMarcheDuPalierThermique; - }; struct PALIERS_THERMIQUES @@ -276,7 +264,7 @@ struct PALIERS_THERMIQUES std::vector PminDuPalierThermiquePendantUneHeure; std::vector PminDuPalierThermiquePendantUnJour; std::vector NumeroDuPalierDansLEnsembleDesPaliersThermiques; - mutable std::vector PuissanceDisponibleEtCout; + std::vector PuissanceDisponibleEtCout; std::vector CoutDeDemarrageDUnGroupeDuPalierThermique; std::vector CoutDArretDUnGroupeDuPalierThermique; @@ -311,8 +299,6 @@ struct ENERGIES_ET_PUISSANCES_HYDRAULIQUES double PenalisationDeLaVariationDeProductionHydrauliqueSurVariationMax; double WeeklyWaterValueStateRegular; - double WeeklyWaterValueStateUp; - double WeeklyWaterValueStateDown; bool TurbinageEntreBornes; bool SansHeuristique; @@ -332,10 +318,10 @@ struct ENERGIES_ET_PUISSANCES_HYDRAULIQUES bool DirectLevelAccess; /* determines the type of constraints bearing on the final stok level*/ bool AccurateWaterValue; /* determines the type of modelling used for water budget*/ double LevelForTimeInterval; /* value computed by the simulator in water-value based modes*/ - std::vector WaterLayerValues; /* reference costs for the last time step (caution : dimension set to - 100, should be made dynamic)*/ - std::vector InflowForTimeInterval; /* Energy input to the reservoir, used to in the bounding - constraint on final level*/ + std::vector WaterLayerValues; /* reference costs for the last time step (caution : + dimension set to 100, should be made dynamic)*/ + std::vector InflowForTimeInterval; /* Energy input to the reservoir, used to in the + bounding constraint on final level*/ }; class computeTimeStepLevel @@ -353,14 +339,13 @@ class computeTimeStepLevel double excessDown; public: - computeTimeStepLevel( - const double& startLvl, - std::vector& infl, - std::vector& overfl, - std::vector& H, - double pumpEff, - std::vector& Pump, - double rc) : + computeTimeStepLevel(const double& startLvl, + std::vector& infl, + std::vector& overfl, + std::vector& H, + double pumpEff, + std::vector& Pump, + double rc): step(0), level(startLvl), capacity(rc), @@ -415,39 +400,26 @@ struct PRODUCTION_THERMIQUE_OPTIMALE { std::vector ProductionThermiqueDuPalier; - std::vector ProductionThermiqueDuPalierUp; - std::vector ProductionThermiqueDuPalierDown; - std::vector NombreDeGroupesEnMarcheDuPalier; std::vector NombreDeGroupesQuiDemarrentDuPalier; std::vector NombreDeGroupesQuiSArretentDuPalier; std::vector NombreDeGroupesQuiTombentEnPanneDuPalier; - }; struct RESULTATS_HORAIRES { std::vector ValeursHorairesDeDefaillancePositive; - std::vector ValeursHorairesDENS; // adq patch domestic unsupplied energy - mutable std::vector ValeursHorairesLmrViolations; // adq patch lmr violations + std::vector ValeursHorairesDENS; // adq patch domestic unsupplied energy + std::vector ValeursHorairesLmrViolations; // adq patch lmr violations std::vector ValeursHorairesSpilledEnergyAfterCSR; // adq patch spillage after CSR std::vector ValeursHorairesDtgMrgCsr; // adq patch DTG MRG after CSR - std::vector ValeursHorairesDeDefaillancePositiveUp; - std::vector ValeursHorairesDeDefaillancePositiveDown; - std::vector ValeursHorairesDeDefaillancePositiveAny; std::vector ValeursHorairesDeDefaillanceNegative; - std::vector ValeursHorairesDeDefaillanceNegativeUp; - std::vector ValeursHorairesDeDefaillanceNegativeDown; - std::vector ValeursHorairesDeDefaillanceNegativeAny; - std::vector ValeursHorairesDeDefaillanceEnReserve; std::vector PompageHoraire; std::vector TurbinageHoraire; - std::vector TurbinageHoraireUp; - std::vector TurbinageHoraireDown; std::vector niveauxHoraires; std::vector valeurH2oHoraire; @@ -469,9 +441,16 @@ struct COUTS_DE_TRANSPORT std::vector CoutDeTransportOrigineVersExtremiteRef; std::vector CoutDeTransportExtremiteVersOrigineRef; +}; +struct TIME_MEASURE +{ + long solveTime = 0; + long updateTime = 0; }; +using TIME_MEASURES = std::array; + struct VARIABLES_DUALES_INTERCONNEXIONS { std::vector VariableDualeParInterconnexion; @@ -487,6 +466,7 @@ struct PROBLEME_HEBDO char TypeDeLissageHydraulique = PAS_DE_LISSAGE_HYDRAULIQUE; bool WaterValueAccurate = false; bool OptimisationAvecCoutsDeDemarrage = false; + bool OptimisationAvecVariablesEntieres = false; uint32_t NombreDePays = 0; std::vector NomsDesPays; uint32_t NombreDePaliersThermiques = 0; @@ -494,29 +474,29 @@ struct PROBLEME_HEBDO uint32_t NombreDInterconnexions = 0; std::vector PaysOrigineDeLInterconnexion; std::vector PaysExtremiteDeLInterconnexion; - mutable std::vector CoutDeTransport; + std::vector CoutDeTransport; - mutable std::vector ValeursDeNTC; + std::vector ValeursDeNTC; uint32_t NombreDePasDeTemps = 0; std::vector NumeroDeJourDuPasDeTemps; - //TODO use uint32_t and figure why tests fails + // TODO use uint32_t and figure why tests fails int32_t NombreDePasDeTempsPourUneOptimisation = 0; std::vector NumeroDIntervalleOptimiseDuPasDeTemps; uint32_t NombreDeJours = 0; - //TODO same as NombreDePasDeTemps + // TODO same as NombreDePasDeTemps int32_t NombreDePasDeTempsDUneJournee = 0; - mutable std::vector ConsommationsAbattues; + std::vector ConsommationsAbattues; std::vector CoutDeDefaillancePositive; std::vector CoutDeDefaillanceNegative; std::vector CoutDeDefaillanceEnReserve; std::vector PaliersThermiquesDuPays; - mutable std::vector CaracteristiquesHydrauliques; + std::vector CaracteristiquesHydrauliques; uint32_t NumberOfShortTermStorages = 0; // problemeHebdo->ShortTermStorage[areaIndex][clusterIndex].capacity; @@ -528,12 +508,14 @@ struct PROBLEME_HEBDO std::vector DefaillanceNegativeUtiliserHydro; std::vector DefaillanceNegativeUtiliserConsoAbattue; - char TypeDOptimisation = OPTIMISATION_LINEAIRE; // OPTIMISATION_LINEAIRE or OPTIMISATION_QUADRATIQUE + char TypeDOptimisation = OPTIMISATION_LINEAIRE; // OPTIMISATION_LINEAIRE or + // OPTIMISATION_QUADRATIQUE std::vector> BruitSurCoutHydraulique; uint32_t NombreDeContraintesCouplantes = 0; - mutable std::vector MatriceDesContraintesCouplantes; - std::vector ResultatsContraintesCouplantes; + std::vector MatriceDesContraintesCouplantes; + std::unordered_map, std::vector> + ResultatsContraintesCouplantes; std::vector SoldeMoyenHoraire; // Used for quadratic opt /* Implementation details : I/O, error management, etc. */ @@ -550,10 +532,11 @@ struct PROBLEME_HEBDO std::vector CorrespondanceVarNativesVarOptim; std::vector CorrespondanceCntNativesCntOptim; - std::vector CorrespondanceCntNativesCntOptimJournalieres; + std::vector + CorrespondanceCntNativesCntOptimJournalieres; CORRESPONDANCES_DES_CONTRAINTES_HEBDOMADAIRES CorrespondanceCntNativesCntOptimHebdomadaires; - mutable std::vector ReserveJMoins1; + std::vector ReserveJMoins1; std::vector IndexDebutIntercoOrigine; std::vector IndexSuivantIntercoOrigine; @@ -576,7 +559,6 @@ struct PROBLEME_HEBDO bool YaDeLaReserveJmoins1 = false; - std::vector previousYearFinalLevels; std::vector AllMustRunGeneration; OptimizationStatistics optimizationStatistics[2]; @@ -586,7 +568,6 @@ struct PROBLEME_HEBDO /* Hydro management */ std::vector CoefficientEcretementPMaxHydraulique; - bool hydroHotStart = false; std::vector previousSimulationFinalLevel; /* Results */ @@ -596,8 +577,7 @@ struct PROBLEME_HEBDO std::vector coutOptimalSolution1; std::vector coutOptimalSolution2; - std::vector tempsResolution1; - std::vector tempsResolution2; + TIME_MEASURES timeMeasure; /* Unused for now, will be used in future revisions */ #if 0 diff --git a/src/solver/simulation/include/antares/solver/simulation/simulation.h b/src/solver/simulation/include/antares/solver/simulation/simulation.h new file mode 100644 index 0000000000..bf214beff6 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/simulation.h @@ -0,0 +1,58 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_SIMULATION_H__ +#define __SOLVER_SIMULATION_H__ + +#include +#include "antares/config/config.h" +#include "antares/solver/hydro/management/management.h" + +#include "sim_structure_donnees.h" + +struct PROBLEME_HEBDO; + +// TODO remove when global variables have been removed (looking at you, +// transitMoyenInterconnexionsRecalculQuadratique) +void SIM_AllocationTableaux(const Antares::Data::Study& study); + +/*! +** \brief Alloue toutes les donnees d'un probleme hebdo +*/ +void SIM_AllocationProblemeHebdo(const Antares::Data::Study& study, + PROBLEME_HEBDO& problem, + uint NombreDePasDeTemps); + +/*! +** \brief Alloue et initialise un probleme hebdo +*/ +void SIM_InitialisationProblemeHebdo(Antares::Data::Study& study, + PROBLEME_HEBDO& problem, + unsigned int NombreDePasDeTemps, + uint numspace); + +void SIM_RenseignementProblemeHebdo(const Antares::Data::Study& study, + PROBLEME_HEBDO& problem, + uint weekInTheYear, + const int, + const Antares::HYDRO_VENTILATION_RESULTS&, + const Antares::Data::Area::ScratchMap&); + +#endif /* __SOLVER_SIMULATION_H__ */ diff --git a/src/solver/simulation/include/antares/solver/simulation/solver.data.h b/src/solver/simulation/include/antares/solver/simulation/solver.data.h new file mode 100644 index 0000000000..16de52d570 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/solver.data.h @@ -0,0 +1,65 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_SIMULATION_SOLVER_DATA_H__ +#define __SOLVER_SIMULATION_SOLVER_DATA_H__ + +#include + +#include + +namespace Antares::Solver::Private::Simulation +{ +class CacheData +{ +public: + /*! + ** \brief Re-Initialize the inner variables + */ + void initialize(const Antares::Data::Parameters& parameters); + +public: + //! True if the prepro `load` must be used + bool haveToRefreshTSLoad; + //! True if the prepro `solar` must be used + bool haveToRefreshTSSolar; + //! True if the prepro `wind` must be used + bool haveToRefreshTSWind; + //! True if the prepro `hydro` must be used + bool haveToRefreshTSHydro; + //! True if the prepro `thermal` must be used + bool haveToRefreshTSThermal; + + //! Refresh time interval for Load + unsigned int refreshIntervalLoad; + //! Refresh time interval for Solar + unsigned int refreshIntervalSolar; + //! Refresh time interval for Hydro + unsigned int refreshIntervalHydro; + //! Refresh time interval for wind + unsigned int refreshIntervalWind; + //! Refresh time interval for thermal + unsigned int refreshIntervalThermal; + +}; // class CacheData + +} // namespace Antares::Solver::Private::Simulation + +#endif // __SOLVER_SIMULATION_SOLVER_H__ diff --git a/src/solver/simulation/include/antares/solver/simulation/solver.h b/src/solver/simulation/include/antares/solver/simulation/solver.h new file mode 100644 index 0000000000..6dc6f85eb8 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/solver.h @@ -0,0 +1,169 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_SOLVER_H__ +#define __SOLVER_SIMULATION_SOLVER_H__ + +#include +#include + +#include +#include +#include +#include +#include +#include "antares/solver/hydro/management/management.h" +#include "antares/solver/misc/options.h" +#include "antares/solver/simulation/solver.data.h" +#include "antares/solver/simulation/solver_utils.h" +#include "antares/solver/variable/state.h" + +namespace Antares::Solver::Simulation +{ + +template +class yearJob; + +template +class ISimulation: public Impl +{ + friend class yearJob; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Constructor (with a given study) + */ + ISimulation(Data::Study& study, + const ::Settings& settings, + Benchmarking::DurationCollector& duration_collector, + IResultWriter& resultWriter, + Simulation::ISimulationObserver& simulationObserver); + //! Destructor + ~ISimulation(); + //@} + + // Check that the writer is valid + void checkWriter() const; + + /*! + ** \brief Run the simulation + */ + void run(); + + /*! + ** \brief Export the results to disk + ** + ** \tparam ResultsForYearByYear False to write down the rglobal esults of the simulation, + ** true for the results of the current year (year-by-year mode) + ** \param year The current year, if applicable + */ + void writeResults(bool synthesis, uint year = 0, uint numSpace = 9999); + + //! Reference to the current study + Data::Study& study; + //! The global settings + const ::Settings& settings; + +private: + /*! + ** \brief Regenerate time-series if required for a given year + */ + void regenerateTimeSeries(uint year); + + /*! + ** \brief Builds sets of parallel years + ** + ** \return The max number of years in a set of parallel years (to be executed or not) + */ + uint buildSetsOfParallelYears(uint firstYear, + uint endYear, + std::vector& setsOfParallelYears); + + /*! + ** \brief Allocate storage for random numbers of parallel years + ** + ** \param randomParallelYears ... to be finished ... + */ + void allocateMemoryForRandomNumbers(randomNumbers& randomForParallelYears); + + /*! + ** \brief Computes random numbers for each years of a list + ** + ** \param randomForYears Storage for random numbers for years in the list + ** \param years List of years + */ + void computeRandomNumbers(randomNumbers& randomForYears, + std::vector& years, + std::map& isYearPerformed, + MersenneTwister& randomHydro); + + /*! + ** \brief Computes statistics on annual (system and solution) costs, to be printed in output + *into separate files + ** + ** Adds the contributions of each performed year contained in the current set to annual system + *and solution costs averages over all years. + ** These average costs are meant to be printed in output into separate files. + ** Same thing for min and max costs over all years. + ** Storing these costs to compute std deviation later. + */ + void computeAnnualCostsStatistics(std::vector& state, + setOfParallelYears& batch); + + /*! + ** \brief Iterate through all MC years + ** + ** \param firstYear The first real MC year + ** \param endYear The last MC year + */ + void loopThroughYears(uint firstYear, uint endYear, std::vector& state); + + //! Some temporary to avoid performing useless complex checks + Solver::Private::Simulation::CacheData pData; + //! + uint pNbYearsReallyPerformed; + //! Max number of years performed in parallel + uint pNbMaxPerformedYearsInParallel; + //! Year by year output results + bool pYearByYear; + //! The first set of parallel year(s) with a performed year was already run ? + bool pFirstSetParallelWithAPerformedYearWasRun; + + //! Statistics about annual (system and solution) costs + annualCostsStatistics pAnnualStatistics; + + // Collecting durations inside the simulation + Benchmarking::DurationCollector& pDurationCollector; + +public: + //! The queue service that runs every set of parallel years + std::shared_ptr pQueueService = nullptr; + //! Result writer + Antares::Solver::IResultWriter& pResultWriter; + + std::reference_wrapper simulationObserver_; +}; // class ISimulation +} // namespace Antares::Solver::Simulation + +#include "solver.hxx" + +#endif // __SOLVER_SIMULATION_SOLVER_H__ diff --git a/src/solver/simulation/include/antares/solver/simulation/solver.hxx b/src/solver/simulation/include/antares/solver/simulation/solver.hxx new file mode 100644 index 0000000000..21e0aeb7a1 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/solver.hxx @@ -0,0 +1,1083 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_SIMULATION_SOLVER_HXX__ +#define __SOLVER_SIMULATION_SOLVER_HXX__ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include "antares/concurrency/concurrency.h" +#include "antares/solver/hydro/management/HydroInputsChecker.h" +#include "antares/solver/hydro/management/management.h" +#include "antares/solver/simulation/opt_time_writer.h" +#include "antares/solver/simulation/timeseries-numbers.h" +#include "antares/solver/ts-generator/generator.h" +#include "antares/solver/variable/print.h" + +namespace Antares::Solver::Simulation +{ + +template +class yearJob +{ +public: + yearJob(ISimulation* simulation, + unsigned int pY, + std::map& pYearFailed, + std::map& pIsFirstPerformedYearOfASet, + bool pFirstSetParallelWithAPerformedYearWasRun, + unsigned int pNumSpace, + randomNumbers& pRandomForParallelYears, + bool pPerformCalculations, + Data::Study& pStudy, + Variable::State& pState, + bool pYearByYear, + Benchmarking::DurationCollector& durationCollector, + IResultWriter& resultWriter, + ISimulationObserver& simulationObserver): + simulation_(simulation), + y(pY), + yearFailed(pYearFailed), + isFirstPerformedYearOfASet(pIsFirstPerformedYearOfASet), + firstSetParallelWithAPerformedYearWasRun(pFirstSetParallelWithAPerformedYearWasRun), + numSpace(pNumSpace), + randomForParallelYears(pRandomForParallelYears), + performCalculations(pPerformCalculations), + study(pStudy), + state(pState), + yearByYear(pYearByYear), + pDurationCollector(durationCollector), + pResultWriter(resultWriter), + simulationObserver_(simulationObserver), + hydroManagement(study.areas, study.parameters, study.calendar, resultWriter) + { + scratchmap = study.areas.buildScratchMap(numSpace); + } + + yearJob(const yearJob&) = delete; + yearJob& operator=(const yearJob&) = delete; + ~yearJob() = default; + +private: + ISimulation* simulation_; + unsigned int y; + std::map& yearFailed; + std::map& isFirstPerformedYearOfASet; + bool firstSetParallelWithAPerformedYearWasRun; + unsigned int numSpace; + randomNumbers& randomForParallelYears; + bool performCalculations; + Data::Study& study; + Variable::State& state; + bool yearByYear; + Benchmarking::DurationCollector& pDurationCollector; + IResultWriter& pResultWriter; + std::reference_wrapper simulationObserver_; + HydroManagement hydroManagement; + Antares::Data::Area::ScratchMap scratchmap; + +private: + /* + ** \brief Log failed week + ** + ** \param y MC Year + ** \param study The Antares study + ** \param failedWeek List of failing week + */ + void logFailedWeek(int y, const Data::Study& study, const std::list& failedWeekList) + { + if (!failedWeekList.empty()) + { + std::stringstream failedWeekStr; + std::ranges::copy(failedWeekList, std::ostream_iterator(failedWeekStr, " ")); + + std::string s = failedWeekStr.str(); + s = s.substr(0, s.length() - 1); // get rid of the trailing space + + std::string failedStr = failedWeekList.size() != 1 ? " failed at weeks " + : " failed at week "; + + logs.info(); // empty line + + if (Data::stopSimulation(study.parameters.include.unfeasibleProblemBehavior)) + { + logs.fatal() << "Year " << y + 1 << failedStr << s << "."; + } + else + { + logs.warning() << "Year " << y + 1 << failedStr << s << "."; + } + } + } + +public: + void operator()() + { + Progression::Task progression(study, y, Solver::Progression::sectYear); + + if (performCalculations) + { + // Index of the current year in the list of structures + uint indexYear = randomForParallelYears.yearNumberToIndex[y]; + + // Getting random tables for this year + yearRandomNumbers& randomForCurrentYear = randomForParallelYears.pYears[indexYear]; + double* randomReservoirLevel = nullptr; + + // 1 - Applying random levels for current year + randomReservoirLevel = randomForCurrentYear.pReservoirLevels; + + // 2 - Preparing the Time-series numbers + // removed + + // 3 - Preparing data related to Clusters in 'must-run' mode + simulation_->prepareClustersInMustRunMode(scratchmap, y); + + // 4 - Hydraulic ventilation + pDurationCollector("hydro_ventilation") << [this, &randomReservoirLevel] + { hydroManagement.makeVentilation(randomReservoirLevel, y, scratchmap); }; + + // Updating the state + state.year = y; + + // 5 - Resetting all variables for the output + simulation_->variables.yearBegin(y, numSpace); + + // 6 - The Solver itself + bool isFirstPerformedYearOfSimulation = isFirstPerformedYearOfASet[y] + && not firstSetParallelWithAPerformedYearWasRun; + std::list failedWeekList; + + OptimizationStatisticsWriter optWriter(pResultWriter, y); + yearFailed[y] = !simulation_->year(progression, + state, + numSpace, + randomForCurrentYear, + failedWeekList, + isFirstPerformedYearOfSimulation, + hydroManagement.ventilationResults(), + optWriter, + scratchmap); + + // Log failing weeks + logFailedWeek(y, study, failedWeekList); + + simulation_->variables.yearEndBuild(state, y, numSpace); + + // 7 - End of the year, this is the last stade where the variables can retrieve + // their data for this year. + simulation_->variables.yearEnd(y, numSpace); + + // 8 - Spatial clusters + // Notifying all variables to perform spatial aggregates. + // This must be done only when all variables have finished to compute their + // data for the year. + simulation_->variables.yearEndSpatialAggregates(simulation_->variables, y, numSpace); + + // 9 - Write results for the current year + if (yearByYear) + { + pDurationCollector("yby_export") << [this] + { + // Before writing, some variable may require minor modifications + simulation_->variables.beforeYearByYearExport(y, numSpace); + // writing the results for the current year into the output + simulation_->writeResults(false, y, numSpace); // false for synthesis + }; + } + } + else + { + simulation_->incrementProgression(progression); + + logs.info() << " playlist: ignoring the year " << (y + 1); + + yearFailed[y] = false; + + } // End if(performCalculations) + + } // End of onExecute() method +}; + +template +inline ISimulation::ISimulation( + Data::Study& study, + const ::Settings& settings, + Benchmarking::DurationCollector& duration_collector, + IResultWriter& resultWriter, + Simulation::ISimulationObserver& simulationObserver): + ImplementationType(study, resultWriter, simulationObserver), + study(study), + settings(settings), + pNbYearsReallyPerformed(0), + pNbMaxPerformedYearsInParallel(0), + pYearByYear(study.parameters.yearByYear), + pFirstSetParallelWithAPerformedYearWasRun(false), + pDurationCollector(duration_collector), + pQueueService(study.pQueueService), + pResultWriter(resultWriter), + simulationObserver_(simulationObserver) +{ + // Ask to the interface to show the messages + logs.info(); + logs.info() << LOG_UI_DISPLAY_MESSAGES_ON; + + // Running ! + logs.checkpoint() << "Running the simulation (" << ImplementationType::Name() << ')'; + logs.info() << "Allocating resources..."; + + if (pYearByYear && (settings.noOutput || settings.tsGeneratorsOnly)) + { + pYearByYear = false; + } +} + +template +inline void ISimulation::checkWriter() const +{ + // The zip writer needs a queue service (async mutexed write) + if (!pQueueService && pResultWriter.needsTheJobQueue()) + { + throw Solver::Initialization::Error::NoQueueService(); + } +} + +template +inline ISimulation::~ISimulation() +{ +} + +template +void ISimulation::run() +{ + pNbMaxPerformedYearsInParallel = study.maxNbYearsInParallel; + + // Initialize all data + ImplementationType::variables.initializeFromStudy(study); + // Computing the max number columns a report of any kind can contain. + study.parameters.variablesPrintInfo.computeMaxColumnsCountInReports(); + + logs.info() << "Allocating resources..."; + + // Memory usage + { + logs.info() << " Variables: (" + << (uint)(ImplementationType::variables.memoryUsage() / 1024 / 1024) << "Mo)"; + Variable::PrintInfosStdCout c; + ImplementationType::variables.template provideInformations(c); + } + + // Preprocessors + // Determine if we have to use the preprocessors at least one time. + pData.initialize(study.parameters); + + ImplementationType::setNbPerformedYearsInParallel(pNbMaxPerformedYearsInParallel); + + if (settings.tsGeneratorsOnly) + { + // Only the preprocessors can be used + // We only have to regenerate time-series according the settings + // in general data of the study. + logs.info() << " Only the preprocessors are enabled."; + + regenerateTimeSeries(0); + + // Destroy the TS Generators if any + // It will export the time-series into the output in the same time + TSGenerator::DestroyAll(study); + } + else + { + if (not ImplementationType::simulationBegin()) + { + return; + } + // Allocating the memory + ImplementationType::variables.simulationBegin(); + + // For beauty + logs.info(); + + // Launching the simulation for all years + logs.info() << "MC-Years : [" << (study.runtime->rangeLimits.year[Data::rangeBegin] + 1) + << " .. " << (1 + study.runtime->rangeLimits.year[Data::rangeEnd]) + << "], total: " << study.runtime->rangeLimits.year[Data::rangeCount]; + + // Current state + std::vector state(pNbMaxPerformedYearsInParallel, Variable::State(study)); + // Initializing states for parallel actually performed years + for (uint numSpace = 0; numSpace != pNbMaxPerformedYearsInParallel; ++numSpace) + { + ImplementationType::initializeState(state[numSpace], numSpace); + } + + uint finalYear = 1 + study.runtime->rangeLimits.year[Data::rangeEnd]; + { + pDurationCollector("mc_years") + << [finalYear, &state, this] { loopThroughYears(0, finalYear, state); }; + } + // Destroy the TS Generators if any + // It will export the time-series into the output in the same time + TSGenerator::DestroyAll(study); + + // Post operations + pDurationCollector("post_processing") << [this] { ImplementationType::simulationEnd(); }; + + ImplementationType::variables.simulationEnd(); + + // Export ts-numbers into output + TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(study, pResultWriter); + + // Spatial clusters + // Notifying all variables to perform the final spatial clusters. + // This must be done only when all variables have finished to compute their + // own data. + ImplementationType::variables.simulationEndSpatialAggregates(ImplementationType::variables); + } +} + +template +void ISimulation::writeResults(bool synthesis, uint year, uint numSpace) +{ + using namespace Yuni; + + // The writer might need the job queue, after it's been stopped + // this is the case e.g if synthesis == true (writing mc-all) + // Don't restart the queue if the writer doesn't need it + + assert(!settings.noOutput); + assert(!settings.tsGeneratorsOnly); + + if (!pNbYearsReallyPerformed) + { + logs.info(); + logs.info() << "The writing of the output results is disabled."; + logs.info(); + } + else + { + if (synthesis) + { + const auto& parameters = study.parameters; + if (not parameters.synthesis) // disabled by parameters + { + logs.info() << "The simulation synthesis is disabled."; + return; + } + } + + // The target folder + String newPath; + newPath << ImplementationType::Name() << IO::Separator; + if (synthesis) + { + newPath << "mc-all"; + } + else + { + CString<10, false> tmp; + tmp = (year + 1); + newPath << "mc-ind" << IO::Separator << "00000"; + newPath.overwriteRight(tmp); + } + + // Dumping + ImplementationType::variables.exportSurveyResults(synthesis, + newPath, + numSpace, + pResultWriter); + } +} + +template +void ISimulation::regenerateTimeSeries(uint year) +{ + // A preprocessor can be launched for several reasons: + // * The option "Preprocessor" is checked in the interface _and_ year == 0 + // * Both options "Preprocessor" and "Refresh" are checked in the interface + // _and_ the refresh must be done for the given year (always done for the first year). + using namespace TSGenerator; + // Load + if (pData.haveToRefreshTSLoad && (year % pData.refreshIntervalLoad == 0)) + { + pDurationCollector("tsgen_load") + << [year, this] { GenerateTimeSeries(study, year, pResultWriter); }; + } + // Solar + if (pData.haveToRefreshTSSolar && (year % pData.refreshIntervalSolar == 0)) + { + pDurationCollector("tsgen_solar") << [year, this] + { GenerateTimeSeries(study, year, pResultWriter); }; + } + // Wind + if (pData.haveToRefreshTSWind && (year % pData.refreshIntervalWind == 0)) + { + pDurationCollector("tsgen_wind") + << [year, this] { GenerateTimeSeries(study, year, pResultWriter); }; + } + // Hydro + if (pData.haveToRefreshTSHydro && (year % pData.refreshIntervalHydro == 0)) + { + pDurationCollector("tsgen_hydro") << [year, this] + { GenerateTimeSeries(study, year, pResultWriter); }; + } + + // Thermal + const bool refreshTSonCurrentYear = (year % pData.refreshIntervalThermal == 0); + + pDurationCollector("tsgen_thermal") << [refreshTSonCurrentYear, year, this] + { + if (refreshTSonCurrentYear) + { + auto clusters = getAllClustersToGen(study.areas, pData.haveToRefreshTSThermal); +#define SEP Yuni::IO::Separator + const std::string savePath = std::string("ts-generator") + SEP + "thermal" + SEP + "mc-" + + std::to_string(year); +#undef SEP + generateThermalTimeSeries(study, clusters, pResultWriter, savePath); + + // apply the spinning if we generated some in memory clusters + for (auto* cluster: clusters) + cluster->calculationOfSpinning(); + } + }; +} + +template +uint ISimulation::buildSetsOfParallelYears( + uint firstYear, + uint endYear, + std::vector& setsOfParallelYears) +{ + // Filter on the years + const auto& yearsFilter = study.parameters.yearsFilter; + + // number max of years (to be executed or not) in a set of parallel years + uint maxNbYearsPerformed = 0; + + setOfParallelYears* set = nullptr; + bool buildNewSet = true; + bool foundFirstPerformedYearOfCurrentSet = false; + + // Gets information on each parallel years set + for (uint y = firstYear; y < endYear; ++y) + { + unsigned int indexSpace = 999999; + bool performCalculations = yearsFilter[y]; + + // Do we refresh just before this year ? If yes a new set of parallel years has to be + // created + bool refreshing = false; + refreshing = pData.haveToRefreshTSLoad && (y % pData.refreshIntervalLoad == 0); + refreshing = refreshing + || (pData.haveToRefreshTSSolar && (y % pData.refreshIntervalSolar == 0)); + refreshing = refreshing + || (pData.haveToRefreshTSWind && (y % pData.refreshIntervalWind == 0)); + refreshing = refreshing + || (pData.haveToRefreshTSHydro && (y % pData.refreshIntervalHydro == 0)); + + // Some thermal clusters may override the global parameter. + // Therefore, we may want to refresh TS even if pData.haveToRefreshTSThermal == false + bool haveToRefreshTSThermal = pData.haveToRefreshTSThermal + || study.runtime->thermalTSRefresh; + refreshing = refreshing + || (haveToRefreshTSThermal && (y % pData.refreshIntervalThermal == 0)); + + // We build a new set of parallel years if one of these conditions is fulfilled : + // - We have to refresh (or regenerate) some or all time series before running the + // current year + // - This is the first year (to be executed or not) after the previous set is full with + // years to be executed. That is : in the previous set filled, the max number of + // years to be actually run is reached. + buildNewSet = buildNewSet || refreshing; + + if (buildNewSet) + { + setOfParallelYears setToCreate; + setsOfParallelYears.push_back(setToCreate); + set = &(setsOfParallelYears.back()); + + // Initializations + set->nbPerformedYears = 0; + set->nbYears = 0; + set->regenerateTS = false; + set->yearForTSgeneration = 999999; + + // In case we have to regenerate times series before run the current set of parallel + // years + if (refreshing) + { + set->regenerateTS = true; + set->yearForTSgeneration = y; + } + } + + set->yearsIndices.push_back(y); + set->nbYears++; + set->yearFailed[y] = true; + set->isFirstPerformedYearOfASet[y] = false; + + if (performCalculations) + { + // Another year performed + ++pNbYearsReallyPerformed; + + // Number of actually performed years in the current set (up to now). + set->nbPerformedYears++; + // Index of the MC year's space (useful if this year is actually run) + indexSpace = set->nbPerformedYears - 1; + + set->isYearPerformed[y] = true; + set->performedYearToSpace[y] = indexSpace; + set->spaceToPerformedYear[indexSpace] = y; + + if (!foundFirstPerformedYearOfCurrentSet) + { + set->isFirstPerformedYearOfASet[y] = true; + foundFirstPerformedYearOfCurrentSet = true; + } + } + else + { + set->isYearPerformed[y] = false; + } + + // Do we build a new set at next iteration (for years to be executed or not) ? + if (indexSpace == pNbMaxPerformedYearsInParallel - 1 || y == endYear - 1) + { + buildNewSet = true; + foundFirstPerformedYearOfCurrentSet = false; + if (set->nbPerformedYears > maxNbYearsPerformed) + { + maxNbYearsPerformed = set->nbPerformedYears; + } + } + else + { + buildNewSet = false; + } + + } // End of loop over years + + return maxNbYearsPerformed; +} + +template +void ISimulation::allocateMemoryForRandomNumbers( + randomNumbers& randomForParallelYears) +{ + uint maxNbPerformedYears = randomForParallelYears.pMaxNbPerformedYears; + uint nbAreas = study.areas.size(); + + for (uint y = 0; y < maxNbPerformedYears; y++) + { + // General : + randomForParallelYears.pYears[y].setNbAreas(nbAreas); + randomForParallelYears.pYears[y].pNbClustersByArea = new size_t[nbAreas]; + + // Thermal noises : + randomForParallelYears.pYears[y].pThermalNoisesByArea = new double*[nbAreas]; + + for (uint a = 0; a != nbAreas; ++a) + { + // logs.info() << " area : " << a << " :"; + auto& area = *(study.areas.byIndex[a]); + size_t nbClusters = area.thermal.list.allClustersCount(); + randomForParallelYears.pYears[y].pThermalNoisesByArea[a] = new double[nbClusters]; + randomForParallelYears.pYears[y].pNbClustersByArea[a] = nbClusters; + } + + // Reservoir levels + randomForParallelYears.pYears[y].pReservoirLevels = new double[nbAreas]; + + // Noises on unsupplied and spilled energy + randomForParallelYears.pYears[y].pUnsuppliedEnergy = new double[nbAreas]; + randomForParallelYears.pYears[y].pSpilledEnergy = new double[nbAreas]; + + // Hydro costs noises + switch (study.parameters.power.fluctuations) + { + case Data::lssFreeModulations: + { + randomForParallelYears.pYears[y].pHydroCostsByArea_freeMod = new double*[nbAreas]; + for (uint a = 0; a != nbAreas; ++a) + { + randomForParallelYears.pYears[y].pHydroCostsByArea_freeMod[a] = new double[8784]; + } + break; + } + case Data::lssMinimizeRamping: + case Data::lssMinimizeExcursions: + { + randomForParallelYears.pYears[y].pHydroCosts_rampingOrExcursion = new double[nbAreas]; + break; + } + case Data::lssUnknown: + { + logs.error() << "Power fluctuation unknown"; + break; + } + } + } // End loop over years +} + +template +void ISimulation::computeRandomNumbers( + randomNumbers& randomForYears, + std::vector& years, + std::map& isYearPerformed, + MersenneTwister& randomHydroGenerator) +{ + auto& runtime = *study.runtime; + + uint indexYear = 0; + std::vector::iterator ity; + + for (ity = years.begin(); ity != years.end(); ++ity) + { + uint y = *ity; + bool isPerformed = isYearPerformed[y]; + if (isPerformed) + { + randomForYears.yearNumberToIndex[y] = indexYear; + } + + // General + const unsigned int nbAreas = study.areas.size(); + + // ... Thermal noise ... + for (unsigned int a = 0; a != nbAreas; ++a) + { + // logs.info() << " area : " << a << " :"; + const auto& area = *(study.areas.byIndex[a]); + + for (auto& cluster: area.thermal.list.all()) + { + uint clusterIndex = cluster->areaWideIndex; + double thermalNoise = runtime.random[Data::seedThermalCosts].next(); + if (isPerformed) + { + randomForYears.pYears[indexYear].pThermalNoisesByArea[a][clusterIndex] + = thermalNoise; + } + } + } + + // ... Reservoir levels ... + uint areaIndex = 0; + study.areas.each( + [&areaIndex, &indexYear, &randomForYears, &randomHydroGenerator, &y, &isPerformed, this]( + Data::Area& area) + { + // looking for the initial reservoir level (begining of the year) + auto& min = area.hydro.reservoirLevel[Data::PartHydro::minimum]; + auto& avg = area.hydro.reservoirLevel[Data::PartHydro::average]; + auto& max = area.hydro.reservoirLevel[Data::PartHydro::maximum]; + + // Month the reservoir level is initialized according to. + // This month number is given in the civil calendar, from january to december (0 is + // january). + int initResLevelOnMonth = area.hydro.initializeReservoirLevelDate; + + // Conversion of the previous month into simulation calendar + int initResLevelOnSimMonth = study.calendar.mapping.months[initResLevelOnMonth]; + + // Previous month's first day in the year + int firstDayOfMonth = study.calendar.months[initResLevelOnSimMonth].daysYear.first; + + double randomLevel = randomReservoirLevel(min[firstDayOfMonth], + avg[firstDayOfMonth], + max[firstDayOfMonth], + randomHydroGenerator); + + // Possibly update the intial level from scenario builder + if (study.parameters.useCustomScenario) + { + double levelFromScenarioBuilder = study.scenarioInitialHydroLevels[areaIndex][y]; + if (levelFromScenarioBuilder >= 0.) + { + randomLevel = levelFromScenarioBuilder; + } + } + + // Current area's hydro starting (or initial) level computation + // (no matter if the year is performed or not, we always draw a random initial + // reservoir level to ensure the same results) + if (isPerformed) + { + randomForYears.pYears[indexYear].pReservoirLevels[areaIndex] = randomLevel; + } + + areaIndex++; + }); // each area + + // ... Unsupplied and spilled energy costs noises (french : bruits sur la defaillance + // positive et negatives) ... references to the random number generators + auto& randomUnsupplied = study.runtime->random[Data::seedUnsuppliedEnergyCosts]; + auto& randomSpilled = study.runtime->random[Data::seedSpilledEnergyCosts]; + + int currentSpilledEnergySeed = study.parameters.seed[Data::seedSpilledEnergyCosts]; + int defaultSpilledEnergySeed = Data::antaresSeedDefaultValue + + Data::seedSpilledEnergyCosts * Data::antaresSeedIncrement; + bool SpilledEnergySeedIsDefault = (currentSpilledEnergySeed == defaultSpilledEnergySeed); + areaIndex = 0; + study.areas.each( + [&isPerformed, + &areaIndex, + &randomUnsupplied, + &randomSpilled, + &randomForYears, + &indexYear, + &SpilledEnergySeedIsDefault](Data::Area& area) + { + (void)area; // Avoiding warnings at compilation (unused variable) on linux + if (isPerformed) + { + double randomNumber = randomUnsupplied(); + randomForYears.pYears[indexYear].pUnsuppliedEnergy[areaIndex] = randomNumber; + randomForYears.pYears[indexYear].pSpilledEnergy[areaIndex] = randomNumber; + if (!SpilledEnergySeedIsDefault) + { + randomForYears.pYears[indexYear].pSpilledEnergy[areaIndex] = randomSpilled(); + } + } + else + { + randomUnsupplied(); + if (!SpilledEnergySeedIsDefault) + { + randomSpilled(); + } + } + + areaIndex++; + }); // each area + + // ... Hydro costs noises ... + auto& randomHydro = study.runtime->random[Data::seedHydroCosts]; + + Data::PowerFluctuations powerFluctuations = study.parameters.power.fluctuations; + switch (powerFluctuations) + { + case Data::lssFreeModulations: + { + areaIndex = 0; + auto end = study.areas.end(); + + // Computing hourly hydro costs noises so that they are homogeneously spread into : + // [-1.e-3, -5*1.e-4] U [+5*1.e-4, +1.e-3] + if (isPerformed) + { + for (auto i = study.areas.begin(); i != end; ++i) + { + double* noise = randomForYears.pYears[indexYear] + .pHydroCostsByArea_freeMod[areaIndex]; + std::set setHydroCostsNoises; + for (uint j = 0; j != 8784; ++j) + { + noise[j] = randomHydro(); + noise[j] -= 0.5; // Now we have : -0.5 < noise[j] < +0.5 + + // This std::set naturally sorts the hydro costs noises into increasing + // absolute values order + setHydroCostsNoises.insert(hydroCostNoise(noise[j], j)); + } + + uint rank = 0; + std::set::iterator it; + for (it = setHydroCostsNoises.begin(); it != setHydroCostsNoises.end(); it++) + { + uint index = it->getIndex(); + double value = it->getValue(); + + if (value < 0.) + { + noise[index] = -5 * 1.e-4 * (1 + rank / 8784.); + } + else + { + noise[index] = 5 * 1.e-4 * (1 + rank / 8784.); + } + + rank++; + } + + areaIndex++; + } + } + else + { + for (auto i = study.areas.begin(); i != end; ++i) + { + for (uint j = 0; j != 8784; ++j) + { + randomHydro(); + } + } + } + + break; + } + + case Data::lssMinimizeRamping: + case Data::lssMinimizeExcursions: + { + areaIndex = 0; + auto end = study.areas.end(); + for (auto i = study.areas.begin(); i != end; ++i) + { + if (isPerformed) + { + randomForYears.pYears[indexYear].pHydroCosts_rampingOrExcursion[areaIndex] + = randomHydro(); + } + else + { + randomHydro(); + } + + areaIndex++; + } + break; + } + + case Data::lssUnknown: + { + logs.error() << "Power fluctuation unknown"; + break; + } + + } // end of switch + + if (isPerformed) + { + indexYear++; + } + + } // End loop over years +} // End function + +template +void ISimulation::computeAnnualCostsStatistics( + std::vector& state, + setOfParallelYears& batch) +{ + // Loop over years contained in the set + for (auto y: batch.yearsIndices) + { + if (batch.isYearPerformed[y]) + { + // Get space number associated to the performed year + uint numSpace = batch.performedYearToSpace[y]; + const Variable::State& s = state[numSpace]; + pAnnualStatistics.systemCost.addCost(s.annualSystemCost); + pAnnualStatistics.criterionCost1.addCost(s.optimalSolutionCost1); + pAnnualStatistics.criterionCost2.addCost(s.optimalSolutionCost2); + pAnnualStatistics.optimizationTime1.addCost(s.averageOptimizationTime1); + pAnnualStatistics.optimizationTime2.addCost(s.averageOptimizationTime2); + pAnnualStatistics.updateTime.addCost(s.averageUpdateTime); + } + } +} + +static inline void logPerformedYearsInAset(setOfParallelYears& set) +{ + logs.info() << "parallel batch size : " << set.nbYears << " (" << set.nbPerformedYears + << " perfomed)"; + + std::string performedYearsToLog = ""; + + std::ranges::for_each(set.yearsIndices, + [&set, &performedYearsToLog](const uint& y) + { + if (set.isYearPerformed[y]) + { + performedYearsToLog += std::to_string(y + 1) + " "; + } + }); + + logs.info() << "Year(s) " << performedYearsToLog; +} + +template +void ISimulation::loopThroughYears(uint firstYear, + uint endYear, + std::vector& state) +{ + assert(endYear <= study.parameters.nbYears); + + // Init random hydro + MersenneTwister randomHydroGenerator; + randomHydroGenerator.reset(study.parameters.seed[Data::seedHydroManagement]); + + // List of parallel years sets + std::vector setsOfParallelYears; + + // Gets information on each set of parallel years and returns the max number of years performed + // in a set The variable "maxNbYearsPerformedInAset" is the maximum numbers of years to be + // actually executed in a set. A set contains some years to be actually executed (at most + // "pNbMaxPerformedYearsInParallel" years) and some others to skip. + uint maxNbYearsPerformedInAset = buildSetsOfParallelYears(firstYear, + endYear, + setsOfParallelYears); + // Related to annual costs statistics (printed in output into separate files) + pAnnualStatistics.setNbPerformedYears(pNbYearsReallyPerformed); + + // Container for random numbers of parallel years (to be executed or not) + randomNumbers randomForParallelYears(maxNbYearsPerformedInAset, + study.parameters.power.fluctuations); + + // Allocating memory to store random numbers of all parallel years + allocateMemoryForRandomNumbers(randomForParallelYears); + + // Number of threads to perform the jobs waiting in the queue + pQueueService->maximumThreadCount(pNbMaxPerformedYearsInParallel); + HydroInputsChecker hydroInputsChecker(study); + + logs.info() << " Doing hydro validation"; + + // Loop over sets of parallel years to check hydro inputs + for (const auto& batch: setsOfParallelYears) + { + if (batch.regenerateTS) + { + break; + } + for (auto year: batch.yearsIndices) + { + hydroInputsChecker.Execute(year); + } + } + + logs.info() << " Starting the simulation"; + + // Loop over sets of parallel years to run the simulation + for (auto& batch: setsOfParallelYears) + { + // 1 - We may want to regenerate the time-series this year. + // This is the case when the preprocessors are enabled from the + // interface and/or the refresh is enabled. + if (batch.regenerateTS) + { + regenerateTimeSeries(batch.yearForTSgeneration); + } + computeRandomNumbers(randomForParallelYears, + batch.yearsIndices, + batch.isYearPerformed, + randomHydroGenerator); + + bool yearPerformed = false; + Concurrency::FutureSet results; + for (auto y: batch.yearsIndices) + { + // for each year not handled earlier + hydroInputsChecker.Execute(y); + bool performCalculations = batch.isYearPerformed[y]; + unsigned int numSpace = 999999; + if (performCalculations) + { + yearPerformed = true; + numSpace = batch.performedYearToSpace[y]; + } + + // If the year has not to be rerun, we skip the computation of the year. + // Note that, when we enter for the first time in the "for" loop, all years of the set + // have to be rerun (meaning : they must be run once). if(!batch.yearFailed[y]) + // continue; + + auto task = std::make_shared>( + this, + y, + batch.yearFailed, + batch.isFirstPerformedYearOfASet, + pFirstSetParallelWithAPerformedYearWasRun, + numSpace, + randomForParallelYears, + performCalculations, + study, + state[numSpace], + pYearByYear, + pDurationCollector, + pResultWriter, + simulationObserver_.get()); + results.add(Concurrency::AddTask(*pQueueService, task)); + } // End loop over years of the current set of parallel years + + logPerformedYearsInAset(batch); + + pQueueService->start(); + + pQueueService->wait(Yuni::qseIdle); + pQueueService->stop(); + results.join(); + pResultWriter.flush(); + + // At this point, the first set of parallel year(s) was run with at least one year + // performed + if (!pFirstSetParallelWithAPerformedYearWasRun && yearPerformed) + { + pFirstSetParallelWithAPerformedYearWasRun = true; + } + + // On regarde si au moins une année du lot n'a pas trouvé de solution + for (auto& [year, failed]: batch.yearFailed) + { + // Si une année du lot d'années n'a pas trouvé de solution, on arrête tout + if (failed) + { + std::ostringstream msg; + msg << "Year " << year + 1 << " has failed in the previous set of parallel year."; + throw FatalError(msg.str()); + } + } + // Computing the summary : adding the contribution of MC years + // previously computed in parallel + ImplementationType::variables.computeSummary(batch.spaceToPerformedYear, + batch.nbPerformedYears); + + // Computing summary of spatial aggregations + ImplementationType::variables.computeSpatialAggregatesSummary(ImplementationType::variables, + batch.spaceToPerformedYear, + batch.nbPerformedYears); + + // Computes statistics on annual (system and solution) costs, to be printed in output into + // separate files + computeAnnualCostsStatistics(state, batch); + + // Set to zero the random numbers of all parallel years + randomForParallelYears.reset(); + + } // End loop over sets of parallel years + + // Writing annual costs statistics + pAnnualStatistics.endStandardDeviations(); + pAnnualStatistics.writeToOutput(pResultWriter); +} + +} // namespace Antares::Solver::Simulation + +#endif // __SOLVER_SIMULATION_SOLVER_HXX__ diff --git a/src/solver/simulation/include/antares/solver/simulation/solver_utils.h b/src/solver/simulation/include/antares/solver/simulation/solver_utils.h new file mode 100644 index 0000000000..363b7839f8 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/solver_utils.h @@ -0,0 +1,316 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_SIMULATION_SOLVER_UTILS_H__ +#define __SOLVER_SIMULATION_SOLVER_UTILS_H__ + +#include // For setprecision +#include // For std numeric_limits +#include +#include // For ostringstream +#include + +#include + +#include +#include + +namespace Antares::Solver::Simulation +{ +struct setOfParallelYears +{ + // Un lot d'année à exécuter en parallèle. + // En fonction d'une éventuelle play-list, certaines seront jouées et d'autres non. + +public: + // Numeros des annees en parallele pour ce lot (certaines ne seront pas jouées en cas de + // play-list "trouée") + std::vector yearsIndices; + + // Une annee doit-elle être rejouée ? + std::map yearFailed; + + // Associe le numero d'une année jouée à l'indice de l'espace + std::map performedYearToSpace; + + // L'inverse : pour une année jouée, associe l'indice de l'espace au numero de l'année + std::map spaceToPerformedYear; + + // Pour chaque année, est-elle la première à devoir être jouée dans son lot d'années ? + std::map isFirstPerformedYearOfASet; + + // Pour chaque année du lot, est-elle jouée ou non ? + std::map isYearPerformed; + + // Nbre d'années en parallele vraiment jouées pour ce lot + unsigned int nbPerformedYears; + + // Nbre d'années en parallele jouées ou non pour ce lot + unsigned int nbYears; + + // Regenere-t-on des times series avant de jouer les annees du lot courant + bool regenerateTS; + + // Annee a passer a la fonction "regenerateTimeSeries(y)" (si regenerateTS is "true") + unsigned int yearForTSgeneration; +}; + +class costStatistics +{ +public: + void setNbPerformedYears(uint n); + void addCost(const double cost); + void endStandardDeviation(); + + // System costs statistics + double costAverage = 0.; + double costStdDeviation = 0.; + double costMin = std::numeric_limits::max(); + double costMax = 0.; + +private: + // Total number of performed years in the study + uint nbPerformedYears = 0.; +}; + +class annualCostsStatistics +{ +public: + // Costs + costStatistics systemCost; + costStatistics criterionCost1; + costStatistics criterionCost2; + costStatistics optimizationTime1; + costStatistics optimizationTime2; + costStatistics updateTime; + + annualCostsStatistics(); + void setNbPerformedYears(uint n); + void endStandardDeviations(); + void writeToOutput(IResultWriter& writer); + +private: + void writeSystemCostToOutput(IResultWriter& writer); + void writeCriterionCostsToOutput(IResultWriter& writer) const; + void writeUpdateTimes(IResultWriter& writer) const; + void writeOptimizationTimeToOutput(IResultWriter& writer) const; +}; + +class yearRandomNumbers +{ +public: + yearRandomNumbers() + { + pThermalNoisesByArea = nullptr; + pNbClustersByArea = nullptr; + pNbAreas = 0; + } + + ~yearRandomNumbers() + { + // General + delete[] pNbClustersByArea; + + // Thermal noises + for (uint a = 0; a != pNbAreas; a++) + { + delete[] pThermalNoisesByArea[a]; + } + delete[] pThermalNoisesByArea; + + // Reservoir levels, spilled and unsupplied energy + delete[] pReservoirLevels; + delete[] pUnsuppliedEnergy; + delete[] pSpilledEnergy; + + // Hydro costs noises + switch (pPowerFluctuations) + { + case Data::lssFreeModulations: + { + for (uint a = 0; a != pNbAreas; a++) + { + delete[] pHydroCostsByArea_freeMod[a]; + } + delete[] pHydroCostsByArea_freeMod; + break; + } + + case Data::lssMinimizeRamping: + case Data::lssMinimizeExcursions: + { + delete[] pHydroCosts_rampingOrExcursion; + break; + } + + case Data::lssUnknown: + break; + } + } + + void setNbAreas(uint nbAreas) + { + pNbAreas = nbAreas; + } + + void setPowerFluctuations(Data::PowerFluctuations powerFluctuations) + { + pPowerFluctuations = powerFluctuations; + } + + void reset() + { + // General + memset(pNbClustersByArea, 0, pNbAreas * sizeof(size_t)); + + // Thermal noises + for (uint a = 0; a != pNbAreas; a++) + { + memset(pThermalNoisesByArea[a], 0, pNbClustersByArea[a] * sizeof(double)); + } + + // Reservoir levels, spilled and unsupplied energy costs + memset(pReservoirLevels, 0, pNbAreas * sizeof(double)); + memset(pUnsuppliedEnergy, 0, pNbAreas * sizeof(double)); + memset(pSpilledEnergy, 0, pNbAreas * sizeof(double)); + + // Hydro costs noises + switch (pPowerFluctuations) + { + case Data::lssFreeModulations: + { + for (uint a = 0; a != pNbAreas; a++) + { + memset(pHydroCostsByArea_freeMod[a], 0, 8784 * sizeof(double)); + } + break; + } + + case Data::lssMinimizeRamping: + case Data::lssMinimizeExcursions: + { + memset(pHydroCosts_rampingOrExcursion, 0, pNbAreas * sizeof(double)); + break; + } + + case Data::lssUnknown: + break; + } + } + + // General data + uint pNbAreas; + Data::PowerFluctuations pPowerFluctuations; + + // Data for thermal noises + double** pThermalNoisesByArea; + size_t* pNbClustersByArea; + + // Data for reservoir levels + double* pReservoirLevels; + + // Data for unsupplied and spilled energy costs + double* pUnsuppliedEnergy; + double* pSpilledEnergy; + + // Hydro costs noises + double** pHydroCostsByArea_freeMod; + double* pHydroCosts_rampingOrExcursion; +}; + +class randomNumbers +{ +public: + randomNumbers(uint maxNbPerformedYearsInAset, Data::PowerFluctuations powerFluctuations): + pMaxNbPerformedYears(maxNbPerformedYearsInAset) + { + // Allocate a table of parallel years structures + pYears = new yearRandomNumbers[maxNbPerformedYearsInAset]; + + // Tells these structures their power fluctuations mode + for (uint y = 0; y < maxNbPerformedYearsInAset; ++y) + { + pYears[y].setPowerFluctuations(powerFluctuations); + } + } + + ~randomNumbers() + { + delete[] pYears; + } + + void reset() + { + for (uint i = 0; i < pMaxNbPerformedYears; i++) + { + pYears[i].reset(); + } + + yearNumberToIndex.clear(); + } + + uint pMaxNbPerformedYears; + yearRandomNumbers* pYears; + + // Associates : + // year number (0, ..., total nb of years to compute - 1) --> index of the year's space + //(0, + //..., max nb of parallel years - 1) + std::map yearNumberToIndex; +}; + +// Class representing a hydro cost noise. +// This class allows sorting hydro costs noises into increasing absolute values order +// when instances are contained in a : +// std::set +class hydroCostNoise +{ +public: + hydroCostNoise(double v, uint i): + value(v), + index(i) + { + } + + inline double getValue() const + { + return value; + } + + inline uint getIndex() const + { + return index; + } + + double value; + uint index; +}; + +// Used to sort the hydro costs noises into increasing absolute values order in a std::set +struct compareHydroCostsNoises +{ + inline bool operator()(const hydroCostNoise& hcnr1, const hydroCostNoise& hcnr2) const + { + return std::abs(hcnr1.getValue()) < std::abs(hcnr2.getValue()); + } +}; +} // namespace Antares::Solver::Simulation + +#endif // __SOLVER_SIMULATION_SOLVER_H__ diff --git a/src/solver/simulation/include/antares/solver/simulation/timeseries-numbers.h b/src/solver/simulation/include/antares/solver/simulation/timeseries-numbers.h new file mode 100644 index 0000000000..2b087b65e6 --- /dev/null +++ b/src/solver/simulation/include/antares/solver/simulation/timeseries-numbers.h @@ -0,0 +1,48 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_SIMULATION_GENERATE_TIMESERIES_H__ +#define __SOLVER_SIMULATION_GENERATE_TIMESERIES_H__ + +#include + +#include + +#include + +#include "ITimeSeriesNumbersWriter.h" + +namespace Antares::Solver::TimeSeriesNumbers +{ +bool CheckNumberOfColumns(const Data::AreaList& areas); + +/*! +** \brief Generate all time-series numbers for a given set +*/ +bool Generate(Data::Study& study); + +void StoreTimeSeriesNumbersIntoOuput(Data::Study& study, IResultWriter& resultWriter); + +// Exported for unit-tests +bool checkAllElementsIdenticalOrOne(std::vector w); + +} // namespace Antares::Solver::TimeSeriesNumbers + +#endif // __SOLVER_SIMULATION_GENERATE_TIMESERIES_H__ diff --git a/src/solver/simulation/opt_time_writer.cpp b/src/solver/simulation/opt_time_writer.cpp index 2b2ab14b54..a09f3feaa8 100644 --- a/src/solver/simulation/opt_time_writer.cpp +++ b/src/solver/simulation/opt_time_writer.cpp @@ -1,53 +1,51 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "opt_time_writer.h" +#include "antares/solver/simulation/opt_time_writer.h" + +#include -OptimizationStatisticsWriter::OptimizationStatisticsWriter( - Antares::Solver::IResultWriter& writer, - uint year) : - pWriter(writer) +OptimizationStatisticsWriter::OptimizationStatisticsWriter(Antares::Solver::IResultWriter& writer, + uint year): + pYear(year), + pWriter(writer) { printHeader(); -#define SEP Yuni::IO::Separator - pFilename << "debug" << SEP << "solver" << SEP << "weeksSolveTimes_" << year << ".txt"; -#undef SEP } void OptimizationStatisticsWriter::printHeader() { - pBuffer << "# Week Optimization_1_ms Optimization_2_ms\n"; + pBuffer << "# Week Optimization_1_ms Optimization_2_ms Update_ms1 Update_ms2\n"; } -void OptimizationStatisticsWriter::addTime(uint week, double opt_1_ms, double opt_2_ms) +void OptimizationStatisticsWriter::addTime(uint week, const TIME_MEASURES& timeMeasure) { - pBuffer << week << " " << opt_1_ms << " " << opt_2_ms << "\n"; + pBuffer << week << " " << timeMeasure[0].solveTime << " " << timeMeasure[1].solveTime << " " + << timeMeasure[0].updateTime << " " << timeMeasure[1].updateTime << "\n"; } void OptimizationStatisticsWriter::finalize() { - pWriter.addEntryFromBuffer(pFilename.c_str(), pBuffer); + using path = std::filesystem::path; + const path filename = path("optimization") / "week-by-week" + / ("year_" + std::to_string(pYear) + ".txt"); + std::string s = pBuffer.str(); + pWriter.addEntryFromBuffer(filename.string(), s); } diff --git a/src/solver/simulation/opt_time_writer.h b/src/solver/simulation/opt_time_writer.h deleted file mode 100644 index f6468334e8..0000000000 --- a/src/solver/simulation/opt_time_writer.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once -#include -#include - -#include "simulation.h" - -class OptimizationStatisticsWriter -{ -public: - OptimizationStatisticsWriter(Antares::Solver::IResultWriter& writer, uint year); - void addTime(uint week, double opt_1_ms, double opt_2_ms); - void finalize(); - -private: - void printHeader(); - Yuni::Clob pBuffer; - Yuni::String pFilename; - Antares::Solver::IResultWriter& pWriter; -}; diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index c4da3fbc36..03126fa752 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -1,39 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include +#include "antares/solver/simulation/sim_alloc_probleme_hebdo.h" -#include "../optimisation/opt_structure_probleme_a_resoudre.h" +#include -#include "simulation.h" -#include "sim_structure_donnees.h" -#include "sim_structure_probleme_economique.h" -#include "sim_alloc_probleme_hebdo.h" -#include "sim_extern_variables_globales.h" +#include +#include "antares/solver/optimisation/opt_structure_probleme_a_resoudre.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/study/simulation.h" using namespace Antares; @@ -49,7 +43,7 @@ void SIM_AllocationProblemeHebdo(const Data::Study& study, SIM_AllocationConstraints(problem, study, NombreDePasDeTemps); SIM_AllocateAreas(problem, study, NombreDePasDeTemps); } - catch(const std::bad_alloc& e) + catch (const std::bad_alloc& e) { logs.error() << "Memory allocation failed, aborting (" << e.what() << ")"; } @@ -116,7 +110,7 @@ void SIM_AllocationProblemeDonneesGenerales(PROBLEME_HEBDO& problem, problem.CorrespondanceCntNativesCntOptim.resize(NombreDePasDeTemps); problem.VariablesDualesDesContraintesDeNTC.resize(NombreDePasDeTemps); - auto activeConstraints = study.bindingConstraints.activeContraints(); + auto activeConstraints = study.bindingConstraints.activeConstraints(); problem.NombreDeContraintesCouplantes = activeConstraints.size(); problem.MatriceDesContraintesCouplantes.resize(activeConstraints.size()); problem.PaliersThermiquesDuPays.resize(nbPays); @@ -125,28 +119,11 @@ void SIM_AllocationProblemeDonneesGenerales(PROBLEME_HEBDO& problem, problem.ShortTermStorage.resize(nbPays); - problem.previousYearFinalLevels.resize(0); - if (problem.hydroHotStart) - { - for (uint i = 0; i <= nbPays; i++) - { - auto& area = *(study.areas[i]); - if (area.hydro.reservoirManagement) - { - problem.previousYearFinalLevels.assign(nbPays, 0.); - break; - } - } - } - problem.ReserveJMoins1.resize(nbPays); problem.ResultatsHoraires.resize(nbPays); problem.coutOptimalSolution1.assign(7, 0.); problem.coutOptimalSolution2.assign(7, 0.); - - problem.tempsResolution1.assign(7, 0.); - problem.tempsResolution2.assign(7, 0.); } void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, @@ -158,7 +135,7 @@ void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, const uint linkCount = study.runtime->interconnectionsCount(); const uint shortTermStorageCount = study.runtime->shortTermStorageCount; - auto activeConstraints = study.bindingConstraints.activeContraints(); + auto activeConstraints = study.bindingConstraints.activeConstraints(); for (uint k = 0; k < NombreDePasDeTemps; k++) { @@ -175,34 +152,24 @@ void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, problem.SoldeMoyenHoraire[k].SoldeMoyenDuPays.assign(nbPays, 0.); auto& variablesMapping = problem.CorrespondanceVarNativesVarOptim[k]; - variablesMapping.NumeroDeVariableDeLInterconnexion - .assign(linkCount, 0); - variablesMapping - .NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion - .assign(linkCount, 0); - variablesMapping.NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion - .assign(linkCount, 0); + variablesMapping.NumeroDeVariableDeLInterconnexion.assign(linkCount, 0); + variablesMapping.NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion.assign(linkCount, + 0); + variablesMapping.NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion.assign(linkCount, + 0); variablesMapping.NumeroDeVariableDuPalierThermique .assign(study.runtime->thermalPlantTotalCount, 0); - variablesMapping.NumeroDeVariablesDeLaProdHyd - .assign(nbPays, 0); - variablesMapping.NumeroDeVariablesDePompage - .assign(nbPays, 0); - variablesMapping.NumeroDeVariablesDeNiveau - .assign(nbPays, 0); - variablesMapping.NumeroDeVariablesDeDebordement - .assign(nbPays, 0); - variablesMapping.NumeroDeVariableDefaillancePositive - .assign(nbPays, 0); - variablesMapping.NumeroDeVariableDefaillanceNegative - .assign(nbPays, 0); - - variablesMapping.NumeroDeVariablesVariationHydALaBaisse - .assign(nbPays, 0); - - variablesMapping.NumeroDeVariablesVariationHydALaHausse - .assign(nbPays, 0); + variablesMapping.NumeroDeVariablesDeLaProdHyd.assign(nbPays, 0); + variablesMapping.NumeroDeVariablesDePompage.assign(nbPays, 0); + variablesMapping.NumeroDeVariablesDeNiveau.assign(nbPays, 0); + variablesMapping.NumeroDeVariablesDeDebordement.assign(nbPays, 0); + variablesMapping.NumeroDeVariableDefaillancePositive.assign(nbPays, 0); + variablesMapping.NumeroDeVariableDefaillanceNegative.assign(nbPays, 0); + + variablesMapping.NumeroDeVariablesVariationHydALaBaisse.assign(nbPays, 0); + + variablesMapping.NumeroDeVariablesVariationHydALaHausse.assign(nbPays, 0); variablesMapping.NumeroDeVariableDuNombreDeGroupesEnMarcheDuPalierThermique .assign(study.runtime->thermalPlantTotalCount, 0); @@ -213,31 +180,28 @@ void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, variablesMapping.NumeroDeVariableDuNombreDeGroupesQuiTombentEnPanneDuPalierThermique .assign(study.runtime->thermalPlantTotalCount, 0); - variablesMapping.SIM_ShortTermStorage.InjectionVariable - .assign(shortTermStorageCount, 0); - variablesMapping.SIM_ShortTermStorage.WithdrawalVariable - .assign(shortTermStorageCount, 0); - variablesMapping.SIM_ShortTermStorage.LevelVariable - .assign(shortTermStorageCount, 0); - - problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContrainteDesBilansPays - .assign(nbPays, 0); - problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContraintePourEviterLesChargesFictives - .assign(nbPays, 0); - problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContrainteDesNiveauxPays - .assign(nbPays, 0); - - problem.CorrespondanceCntNativesCntOptim[k].ShortTermStorageLevelConstraint - .assign(shortTermStorageCount, 0); - - problem.CorrespondanceCntNativesCntOptim[k].NumeroPremiereContrainteDeReserveParZone - .assign(nbPays, 0); - problem.CorrespondanceCntNativesCntOptim[k].NumeroDeuxiemeContrainteDeReserveParZone - .assign(nbPays, 0); - problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContrainteDeDissociationDeFlux - .assign(linkCount, 0); - problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContrainteDesContraintesCouplantes - .assign(activeConstraints.size(), 0); + variablesMapping.SIM_ShortTermStorage.InjectionVariable.assign(shortTermStorageCount, 0); + variablesMapping.SIM_ShortTermStorage.WithdrawalVariable.assign(shortTermStorageCount, 0); + variablesMapping.SIM_ShortTermStorage.LevelVariable.assign(shortTermStorageCount, 0); + + problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContrainteDesBilansPays.assign(nbPays, + 0); + problem.CorrespondanceCntNativesCntOptim[k] + .NumeroDeContraintePourEviterLesChargesFictives.assign(nbPays, 0); + problem.CorrespondanceCntNativesCntOptim[k].NumeroDeContrainteDesNiveauxPays.assign(nbPays, + 0); + + problem.CorrespondanceCntNativesCntOptim[k] + .ShortTermStorageLevelConstraint.assign(shortTermStorageCount, 0); + + problem.CorrespondanceCntNativesCntOptim[k] + .NumeroPremiereContrainteDeReserveParZone.assign(nbPays, 0); + problem.CorrespondanceCntNativesCntOptim[k] + .NumeroDeuxiemeContrainteDeReserveParZone.assign(nbPays, 0); + problem.CorrespondanceCntNativesCntOptim[k] + .NumeroDeContrainteDeDissociationDeFlux.assign(linkCount, 0); + problem.CorrespondanceCntNativesCntOptim[k] + .NumeroDeContrainteDesContraintesCouplantes.assign(activeConstraints.size(), 0); problem.CorrespondanceCntNativesCntOptim[k] .NumeroDeContrainteDesContraintesDeDureeMinDeMarche @@ -250,26 +214,24 @@ void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, .NumeroDeLaDeuxiemeContrainteDesContraintesDesGroupesQuiTombentEnPanne .assign(study.runtime->thermalPlantTotalCount, 0); - problem.VariablesDualesDesContraintesDeNTC[k].VariableDualeParInterconnexion - .assign(linkCount, 0.); + problem.VariablesDualesDesContraintesDeNTC[k] + .VariableDualeParInterconnexion.assign(linkCount, 0.); } } -void SIM_AllocationLinks(PROBLEME_HEBDO& problem, - const uint linkCount, - unsigned NombreDePasDeTemps) +void SIM_AllocationLinks(PROBLEME_HEBDO& problem, const uint linkCount, unsigned NombreDePasDeTemps) { for (unsigned k = 0; k < linkCount; ++k) { problem.CoutDeTransport[k].IntercoGereeAvecDesCouts = false; - problem.CoutDeTransport[k].CoutDeTransportOrigineVersExtremite - .assign(NombreDePasDeTemps, 0.); - problem.CoutDeTransport[k].CoutDeTransportExtremiteVersOrigine - .assign(NombreDePasDeTemps, 0.); - problem.CoutDeTransport[k].CoutDeTransportOrigineVersExtremiteRef - .assign(NombreDePasDeTemps, 0.); - problem.CoutDeTransport[k].CoutDeTransportExtremiteVersOrigineRef - .assign(NombreDePasDeTemps, 0.); + problem.CoutDeTransport[k].CoutDeTransportOrigineVersExtremite.assign(NombreDePasDeTemps, + 0.); + problem.CoutDeTransport[k].CoutDeTransportExtremiteVersOrigine.assign(NombreDePasDeTemps, + 0.); + problem.CoutDeTransport[k].CoutDeTransportOrigineVersExtremiteRef.assign(NombreDePasDeTemps, + 0.); + problem.CoutDeTransport[k].CoutDeTransportExtremiteVersOrigineRef.assign(NombreDePasDeTemps, + 0.); } } @@ -277,52 +239,48 @@ void SIM_AllocationConstraints(PROBLEME_HEBDO& problem, const Antares::Data::Study& study, unsigned NombreDePasDeTemps) { - auto activeConstraints = study.bindingConstraints.activeContraints(); + auto activeConstraints = study.bindingConstraints.activeConstraints(); problem.CorrespondanceCntNativesCntOptimJournalieres.resize(7); for (uint k = 0; k < 7; k++) { problem.CorrespondanceCntNativesCntOptimJournalieres[k] - .NumeroDeContrainteDesContraintesCouplantes - .assign(activeConstraints.size(), 0); + .NumeroDeContrainteDesContraintesCouplantes.assign(activeConstraints.size(), 0); } - problem.CorrespondanceCntNativesCntOptimHebdomadaires - .NumeroDeContrainteDesContraintesCouplantes - .assign(activeConstraints.size(), 0); + problem.CorrespondanceCntNativesCntOptimHebdomadaires.NumeroDeContrainteDesContraintesCouplantes + .assign(activeConstraints.size(), 0); const auto& bindingConstraintCount = activeConstraints.size(); - problem.ResultatsContraintesCouplantes.resize(bindingConstraintCount); - for (unsigned k = 0; k < bindingConstraintCount; k++) + for (unsigned constraintIndex = 0; constraintIndex != bindingConstraintCount; ++constraintIndex) { - assert(k < activeConstraints.size()); - assert(activeConstraints[k]->linkCount() < 50000000); - assert(activeConstraints[k]->clusterCount() < 50000000); - - problem.MatriceDesContraintesCouplantes[k].SecondMembreDeLaContrainteCouplante - .assign(NombreDePasDeTemps, 0.); - - problem.MatriceDesContraintesCouplantes[k].NumeroDeLInterconnexion - .assign(activeConstraints[k]->linkCount(), 0); - problem.MatriceDesContraintesCouplantes[k].PoidsDeLInterconnexion - .assign(activeConstraints[k]->linkCount(), 0.); - problem.MatriceDesContraintesCouplantes[k].OffsetTemporelSurLInterco - .assign(activeConstraints[k]->linkCount(), 0); - - problem.MatriceDesContraintesCouplantes[k].NumeroDuPalierDispatch - .assign(activeConstraints[k]->clusterCount(), 0); - problem.MatriceDesContraintesCouplantes[k].PoidsDuPalierDispatch - .assign(activeConstraints[k]->clusterCount(), 0.); - problem.MatriceDesContraintesCouplantes[k].OffsetTemporelSurLePalierDispatch - .assign(activeConstraints[k]->clusterCount(), 0); - problem.MatriceDesContraintesCouplantes[k].PaysDuPalierDispatch - .assign(activeConstraints[k]->clusterCount(), 0); + assert(constraintIndex < bindingConstraintCount); + auto bc = activeConstraints[constraintIndex]; + + problem.MatriceDesContraintesCouplantes[constraintIndex] + .SecondMembreDeLaContrainteCouplante.assign(NombreDePasDeTemps, 0.); + + problem.MatriceDesContraintesCouplantes[constraintIndex] + .NumeroDeLInterconnexion.assign(bc->linkCount(), 0); + problem.MatriceDesContraintesCouplantes[constraintIndex] + .PoidsDeLInterconnexion.assign(bc->linkCount(), 0.); + problem.MatriceDesContraintesCouplantes[constraintIndex] + .OffsetTemporelSurLInterco.assign(bc->linkCount(), 0); + + problem.MatriceDesContraintesCouplantes[constraintIndex] + .NumeroDuPalierDispatch.assign(bc->clusterCount(), 0); + problem.MatriceDesContraintesCouplantes[constraintIndex] + .PoidsDuPalierDispatch.assign(bc->clusterCount(), 0.); + problem.MatriceDesContraintesCouplantes[constraintIndex] + .OffsetTemporelSurLePalierDispatch.assign(bc->clusterCount(), 0); + problem.MatriceDesContraintesCouplantes[constraintIndex] + .PaysDuPalierDispatch.assign(bc->clusterCount(), 0); // TODO : create a numberOfTimeSteps method in class of runtime->bindingConstraint unsigned int nbTimeSteps; - switch (activeConstraints[k]->type()) + switch (bc->type()) { using namespace Antares::Data; case BindingConstraint::typeHourly: @@ -339,176 +297,136 @@ void SIM_AllocationConstraints(PROBLEME_HEBDO& problem, break; } if (nbTimeSteps > 0) - problem.ResultatsContraintesCouplantes[k].variablesDuales.assign(nbTimeSteps, 0.); + { + problem.ResultatsContraintesCouplantes.emplace(std::piecewise_construct, + std::forward_as_tuple(bc), + std::forward_as_tuple(nbTimeSteps, 0.)); + } } } void SIM_AllocateAreas(PROBLEME_HEBDO& problem, - const Antares::Data::Study& study, - unsigned NombreDePasDeTemps) + const Antares::Data::Study& study, + unsigned NombreDePasDeTemps) { - uint nbPays = study.areas.size(); for (unsigned k = 0; k < nbPays; k++) { - const uint nbPaliers = study.areas.byIndex[k]->thermal.list.size(); + const uint nbPaliers = study.areas.byIndex[k]->thermal.list.enabledAndNotMustRunCount(); problem.PaliersThermiquesDuPays[k].minUpDownTime.assign(nbPaliers, 0); - problem.PaliersThermiquesDuPays[k].PminDuPalierThermiquePendantUneHeure - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].PminDuPalierThermiquePendantUnJour - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].TailleUnitaireDUnGroupeDuPalierThermique - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].NumeroDuPalierDansLEnsembleDesPaliersThermiques - .assign(nbPaliers, 0); - - problem.PaliersThermiquesDuPays[k].CoutDeDemarrageDUnGroupeDuPalierThermique - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].CoutDArretDUnGroupeDuPalierThermique - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].CoutFixeDeMarcheDUnGroupeDuPalierThermique - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].pminDUnGroupeDuPalierThermique - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].PmaxDUnGroupeDuPalierThermique - .assign(nbPaliers, 0.); - problem.PaliersThermiquesDuPays[k].DureeMinimaleDeMarcheDUnGroupeDuPalierThermique - .assign(nbPaliers, 0); - problem.PaliersThermiquesDuPays[k].DureeMinimaleDArretDUnGroupeDuPalierThermique - .assign(nbPaliers, 0); + problem.PaliersThermiquesDuPays[k].PminDuPalierThermiquePendantUneHeure.assign(nbPaliers, + 0.); + problem.PaliersThermiquesDuPays[k].PminDuPalierThermiquePendantUnJour.assign(nbPaliers, 0.); + problem.PaliersThermiquesDuPays[k] + .TailleUnitaireDUnGroupeDuPalierThermique.assign(nbPaliers, 0.); + problem.PaliersThermiquesDuPays[k] + .NumeroDuPalierDansLEnsembleDesPaliersThermiques.assign(nbPaliers, 0); + + problem.PaliersThermiquesDuPays[k] + .CoutDeDemarrageDUnGroupeDuPalierThermique.assign(nbPaliers, 0.); + problem.PaliersThermiquesDuPays[k].CoutDArretDUnGroupeDuPalierThermique.assign(nbPaliers, + 0.); + problem.PaliersThermiquesDuPays[k] + .CoutFixeDeMarcheDUnGroupeDuPalierThermique.assign(nbPaliers, 0.); + problem.PaliersThermiquesDuPays[k].pminDUnGroupeDuPalierThermique.assign(nbPaliers, 0.); + problem.PaliersThermiquesDuPays[k].PmaxDUnGroupeDuPalierThermique.assign(nbPaliers, 0.); + problem.PaliersThermiquesDuPays[k] + .DureeMinimaleDeMarcheDUnGroupeDuPalierThermique.assign(nbPaliers, 0); + problem.PaliersThermiquesDuPays[k] + .DureeMinimaleDArretDUnGroupeDuPalierThermique.assign(nbPaliers, 0); problem.PaliersThermiquesDuPays[k].NomsDesPaliersThermiques.resize(nbPaliers); - problem.CaracteristiquesHydrauliques[k].CntEnergieH2OParIntervalleOptimise - .assign(7, 0.); - problem.CaracteristiquesHydrauliques[k].CntEnergieH2OParJour - .assign(7, 0.); - problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxHydrauliqueHoraire - .assign(NombreDePasDeTemps, 0.); - problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxHydrauliqueHoraireRef - .assign(NombreDePasDeTemps, 0.); - - problem.CaracteristiquesHydrauliques[k].MaxEnergieHydrauParIntervalleOptimise - .assign(7, 0.); - problem.CaracteristiquesHydrauliques[k].MinEnergieHydrauParIntervalleOptimise - .assign(7, 0.); - - problem.CaracteristiquesHydrauliques[k].NiveauHoraireSup - .assign(NombreDePasDeTemps, 0.); - problem.CaracteristiquesHydrauliques[k].NiveauHoraireInf - .assign(NombreDePasDeTemps, 0.); - problem.CaracteristiquesHydrauliques[k].ApportNaturelHoraire - .assign(NombreDePasDeTemps, 0.); - problem.CaracteristiquesHydrauliques[k].MingenHoraire - .assign(NombreDePasDeTemps, 0.); - - problem.CaracteristiquesHydrauliques[k].WaterLayerValues - .assign(100, 0.); - problem.CaracteristiquesHydrauliques[k].InflowForTimeInterval - .assign(100, 0.); - - problem.CaracteristiquesHydrauliques[k].MaxEnergiePompageParIntervalleOptimise - .assign(7, 0.); - problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxPompageHoraire - .assign(NombreDePasDeTemps, 0.); - - problem.ReserveJMoins1[k].ReserveHoraireJMoins1 - .assign(NombreDePasDeTemps, 0.); - - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillancePositive - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDENS - .assign(NombreDePasDeTemps, 0.); // adq patch - problem.ResultatsHoraires[k].ValeursHorairesLmrViolations - .assign(NombreDePasDeTemps, 0); // adq patch - problem.ResultatsHoraires[k].ValeursHorairesSpilledEnergyAfterCSR - .assign(NombreDePasDeTemps, 0.); // adq patch - problem.ResultatsHoraires[k].ValeursHorairesDtgMrgCsr - .assign(NombreDePasDeTemps, 0.); // adq patch - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillancePositiveUp - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillancePositiveDown - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillancePositiveAny - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillanceNegative - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillanceNegativeUp - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillanceNegativeDown - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillanceNegativeAny - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].ValeursHorairesDeDefaillanceEnReserve - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].TurbinageHoraire - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].PompageHoraire - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].TurbinageHoraireUp - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].TurbinageHoraireDown - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].CoutsMarginauxHoraires - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].niveauxHoraires - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].valeurH2oHoraire - .assign(NombreDePasDeTemps, 0.); - problem.ResultatsHoraires[k].debordementsHoraires - .assign(NombreDePasDeTemps, 0.); + problem.CaracteristiquesHydrauliques[k].CntEnergieH2OParIntervalleOptimise.assign(7, 0.); + problem.CaracteristiquesHydrauliques[k].CntEnergieH2OParJour.assign(7, 0.); + problem.CaracteristiquesHydrauliques[k] + .ContrainteDePmaxHydrauliqueHoraire.assign(NombreDePasDeTemps, 0.); + problem.CaracteristiquesHydrauliques[k] + .ContrainteDePmaxHydrauliqueHoraireRef.assign(NombreDePasDeTemps, 0.); + + problem.CaracteristiquesHydrauliques[k].MaxEnergieHydrauParIntervalleOptimise.assign(7, 0.); + problem.CaracteristiquesHydrauliques[k].MinEnergieHydrauParIntervalleOptimise.assign(7, 0.); + + problem.CaracteristiquesHydrauliques[k].NiveauHoraireSup.assign(NombreDePasDeTemps, 0.); + problem.CaracteristiquesHydrauliques[k].NiveauHoraireInf.assign(NombreDePasDeTemps, 0.); + problem.CaracteristiquesHydrauliques[k].ApportNaturelHoraire.assign(NombreDePasDeTemps, 0.); + problem.CaracteristiquesHydrauliques[k].MingenHoraire.assign(NombreDePasDeTemps, 0.); + + problem.CaracteristiquesHydrauliques[k].WaterLayerValues.assign(100, 0.); + problem.CaracteristiquesHydrauliques[k].InflowForTimeInterval.assign(100, 0.); + + problem.CaracteristiquesHydrauliques[k].MaxEnergiePompageParIntervalleOptimise.assign(7, + 0.); + problem.CaracteristiquesHydrauliques[k] + .ContrainteDePmaxPompageHoraire.assign(NombreDePasDeTemps, 0.); + + problem.ReserveJMoins1[k].ReserveHoraireJMoins1.assign(NombreDePasDeTemps, 0.); + + problem.ResultatsHoraires[k].ValeursHorairesDeDefaillancePositive.assign(NombreDePasDeTemps, + 0.); + problem.ResultatsHoraires[k].ValeursHorairesDENS.assign(NombreDePasDeTemps, + 0.); // adq patch + problem.ResultatsHoraires[k].ValeursHorairesLmrViolations.assign(NombreDePasDeTemps, + 0); // adq patch + problem.ResultatsHoraires[k].ValeursHorairesSpilledEnergyAfterCSR.assign(NombreDePasDeTemps, + 0.); // adq patch + problem.ResultatsHoraires[k].ValeursHorairesDtgMrgCsr.assign(NombreDePasDeTemps, + 0.); // adq patch + + problem.ResultatsHoraires[k].ValeursHorairesDeDefaillanceNegative.assign(NombreDePasDeTemps, + 0.); + problem.ResultatsHoraires[k].TurbinageHoraire.assign(NombreDePasDeTemps, 0.); + problem.ResultatsHoraires[k].PompageHoraire.assign(NombreDePasDeTemps, 0.); + problem.ResultatsHoraires[k].CoutsMarginauxHoraires.assign(NombreDePasDeTemps, 0.); + problem.ResultatsHoraires[k].niveauxHoraires.assign(NombreDePasDeTemps, 0.); + problem.ResultatsHoraires[k].valeurH2oHoraire.assign(NombreDePasDeTemps, 0.); + problem.ResultatsHoraires[k].debordementsHoraires.assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout.resize(nbPaliers); problem.ResultatsHoraires[k].ProductionThermique.resize(NombreDePasDeTemps); for (unsigned j = 0; j < nbPaliers; ++j) { - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .CoutHoraireDeProductionDuPalierThermique - .assign(NombreDePasDeTemps, 0.); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .PuissanceDisponibleDuPalierThermique - .assign(NombreDePasDeTemps, 0.); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .PuissanceDisponibleDuPalierThermiqueRef - .assign(NombreDePasDeTemps, 0.); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .PuissanceMinDuPalierThermique - .assign(NombreDePasDeTemps, 0.); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .PuissanceMinDuPalierThermiqueRef - .assign(NombreDePasDeTemps, 0.); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .NombreMaxDeGroupesEnMarcheDuPalierThermique - .assign(NombreDePasDeTemps, 0); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .NombreMinDeGroupesEnMarcheDuPalierThermique - .assign(NombreDePasDeTemps, 0); - - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .CoutHoraireDuPalierThermiqueUp - .assign(NombreDePasDeTemps, 0.); - problem.PaliersThermiquesDuPays[k].PuissanceDisponibleEtCout[j] - .CoutHoraireDuPalierThermiqueDown - .assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .CoutHoraireDeProductionDuPalierThermique.assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .PuissanceDisponibleDuPalierThermique.assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .PuissanceDisponibleDuPalierThermiqueRef.assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .PuissanceMinDuPalierThermique.assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .PuissanceMinDuPalierThermiqueRef.assign(NombreDePasDeTemps, 0.); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .NombreMaxDeGroupesEnMarcheDuPalierThermique.assign(NombreDePasDeTemps, 0); + problem.PaliersThermiquesDuPays[k] + .PuissanceDisponibleEtCout[j] + .NombreMinDeGroupesEnMarcheDuPalierThermique.assign(NombreDePasDeTemps, 0); } for (unsigned j = 0; j < NombreDePasDeTemps; j++) { - problem.ResultatsHoraires[k].ProductionThermique[j].ProductionThermiqueDuPalier - .assign(nbPaliers, 0.); - problem.ResultatsHoraires[k].ProductionThermique[j].ProductionThermiqueDuPalierUp - .assign(nbPaliers, 0.); - problem.ResultatsHoraires[k].ProductionThermique[j].ProductionThermiqueDuPalierDown - .assign(nbPaliers, 0.); - problem.ResultatsHoraires[k].ProductionThermique[j].NombreDeGroupesEnMarcheDuPalier - .assign(nbPaliers, 0.); - problem.ResultatsHoraires[k].ProductionThermique[j].NombreDeGroupesQuiDemarrentDuPalier - .assign(nbPaliers, 0.); - problem.ResultatsHoraires[k].ProductionThermique[j].NombreDeGroupesQuiSArretentDuPalier - .assign(nbPaliers, 0.); - problem.ResultatsHoraires[k].ProductionThermique[j] - .NombreDeGroupesQuiTombentEnPanneDuPalier - .assign(nbPaliers, 0.); + problem.ResultatsHoraires[k].ProductionThermique[j].ProductionThermiqueDuPalier.assign( + nbPaliers, + 0.); + problem.ResultatsHoraires[k] + .ProductionThermique[j] + .NombreDeGroupesEnMarcheDuPalier.assign(nbPaliers, 0.); + problem.ResultatsHoraires[k] + .ProductionThermique[j] + .NombreDeGroupesQuiDemarrentDuPalier.assign(nbPaliers, 0.); + problem.ResultatsHoraires[k] + .ProductionThermique[j] + .NombreDeGroupesQuiSArretentDuPalier.assign(nbPaliers, 0.); + problem.ResultatsHoraires[k] + .ProductionThermique[j] + .NombreDeGroupesQuiTombentEnPanneDuPalier.assign(nbPaliers, 0.); } // Short term storage results const unsigned long nbShortTermStorage = study.areas.byIndex[k]->shortTermStorage.count(); @@ -522,4 +440,3 @@ void SIM_AllocateAreas(PROBLEME_HEBDO& problem, } } } - diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.h b/src/solver/simulation/sim_alloc_probleme_hebdo.h deleted file mode 100644 index 7f836b38fc..0000000000 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../config.h" -#include - -void SIM_AllocationProblemeDonneesGenerales(PROBLEME_HEBDO& problem, - const Antares::Data::Study& study, - unsigned NombreDePasDeTemps); - -void SIM_AllocationProblemePasDeTemps(PROBLEME_HEBDO& problem, - const Antares::Data::Study& study, - unsigned NombreDePasDeTemps); - -void SIM_AllocationLinks(PROBLEME_HEBDO& problem, - const uint linkCount, - unsigned NombreDePasDeTemps); - -void SIM_AllocationConstraints(PROBLEME_HEBDO& problem, - const Antares::Data::Study& study, - unsigned NombreDePasDeTemps); - -void SIM_AllocateAreas(PROBLEME_HEBDO& problem, - const Antares::Data::Study& study, - unsigned NombreDePasDeTemps); diff --git a/src/solver/simulation/sim_allocation_tableaux.cpp b/src/solver/simulation/sim_allocation_tableaux.cpp index 3967b0fbd5..4b8674639d 100644 --- a/src/solver/simulation/sim_allocation_tableaux.cpp +++ b/src/solver/simulation/sim_allocation_tableaux.cpp @@ -1,55 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include + #include -#include "simulation.h" -#include "sim_structure_donnees.h" -#include "sim_structure_probleme_economique.h" -#include "sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/study/simulation.h" using namespace Antares; -static void AllocateResultsForEconomicMode(const Data::Study& study) +void SIM_AllocationTableaux(const Data::Study& study) { transitMoyenInterconnexionsRecalculQuadratique.resize(study.runtime->interconnectionsCount()); for (uint i = 0; i != study.runtime->interconnectionsCount(); i++) + { transitMoyenInterconnexionsRecalculQuadratique[i].assign(HOURS_PER_YEAR, 0.); -} - -void SIM_AllocationTableaux(const Data::Study& study) -{ - NumeroChroniquesTireesParInterconnexion.resize(study.maxNbYearsInParallel); - - const uint intercoCount = study.areas.areaLinkCount(); - for (uint numSpace = 0; numSpace < study.maxNbYearsInParallel; numSpace++) - NumeroChroniquesTireesParInterconnexion[numSpace].resize(intercoCount); - - NumeroChroniquesTireesParGroup.resize(study.maxNbYearsInParallel); - AllocateResultsForEconomicMode(study); + } } diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 60fe4aa9cd..7fb3336599 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -1,46 +1,41 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include #include -#include +#include #include #include - +#include +#include +#include "antares/solver/simulation/adequacy_patch_runtime_data.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" +#include "antares/solver/simulation/simulation.h" #include "antares/study/fwd.h" -#include "simulation.h" -#include "sim_structure_probleme_economique.h" -#include "sim_extern_variables_globales.h" -#include "adequacy_patch_runtime_data.h" -#include +#include "antares/study/simulation.h" using namespace Antares; using namespace Antares::Data; -using namespace Yuni; static void importShortTermStorages( const AreaList& areas, @@ -51,21 +46,21 @@ static void importShortTermStorages( { ShortTermStorageOut[areaIndex].resize(areas[areaIndex]->shortTermStorage.count()); int storageIndex = 0; - for (auto st : areas[areaIndex]->shortTermStorage.storagesByIndex) + for (const auto& st: areas[areaIndex]->shortTermStorage.storagesByIndex) { ::ShortTermStorage::PROPERTIES& toInsert = ShortTermStorageOut[areaIndex][storageIndex]; toInsert.clusterGlobalIndex = clusterGlobalIndex; // Properties - toInsert.reservoirCapacity = st->properties.reservoirCapacity.value(); - toInsert.efficiency = st->properties.efficiencyFactor; - toInsert.injectionNominalCapacity = st->properties.injectionNominalCapacity.value(); - toInsert.withdrawalNominalCapacity = st->properties.withdrawalNominalCapacity.value(); - toInsert.initialLevel = st->properties.initialLevel; - toInsert.initialLevelOptim = st->properties.initialLevelOptim; - toInsert.name = st->properties.name; + toInsert.reservoirCapacity = st.properties.reservoirCapacity.value(); + toInsert.efficiency = st.properties.efficiencyFactor; + toInsert.injectionNominalCapacity = st.properties.injectionNominalCapacity.value(); + toInsert.withdrawalNominalCapacity = st.properties.withdrawalNominalCapacity.value(); + toInsert.initialLevel = st.properties.initialLevel; + toInsert.initialLevelOptim = st.properties.initialLevelOptim; + toInsert.name = st.properties.name; - toInsert.series = st->series; + toInsert.series = st.series; // TODO add missing properties, or use the same struct storageIndex++; @@ -76,28 +71,26 @@ static void importShortTermStorages( void SIM_InitialisationProblemeHebdo(Data::Study& study, PROBLEME_HEBDO& problem, - int NombreDePasDeTemps, - uint numSpace) + unsigned int NombreDePasDeTemps, + uint numspace) { int NombrePaliers; auto& parameters = study.parameters; - problem.Expansion = parameters.expansion; + problem.Expansion = (parameters.mode == Data::SimulationMode::Expansion); problem.firstWeekOfSimulation = false; - problem.hydroHotStart - = (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart); - // gp adq : to be removed if (parameters.adqPatchParams.enabled) { - problem.adequacyPatchRuntimeData - = std::make_shared(study.areas, study.runtime->areaLink); + problem.adequacyPatchRuntimeData = std::make_shared( + study.areas, + study.runtime->areaLink); } - problem.WaterValueAccurate - = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP); + problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode + == Antares::Data::HydroPricingMode::hpMILP); SIM_AllocationProblemeHebdo(study, problem, NombreDePasDeTemps); @@ -111,19 +104,22 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.NumberOfShortTermStorages = study.runtime->shortTermStorageCount; - auto activeContraints = study.bindingConstraints.activeContraints(); - problem.NombreDeContraintesCouplantes = activeContraints.size(); + auto activeConstraints = study.bindingConstraints.activeConstraints(); + problem.NombreDeContraintesCouplantes = activeConstraints.size(); problem.ExportMPS = study.parameters.include.exportMPS; problem.ExportStructure = study.parameters.include.exportStructure; problem.NamedProblems = study.parameters.namedProblems; problem.exportMPSOnError = Data::exportMPS(parameters.include.unfeasibleProblemBehavior); - problem.OptimisationAvecCoutsDeDemarrage - = (study.parameters.unitCommitment.ucMode == Antares::Data::UnitCommitmentMode::ucMILP); + problem.OptimisationAvecCoutsDeDemarrage = (study.parameters.unitCommitment.ucMode + != Antares::Data::UnitCommitmentMode:: + ucHeuristicFast); + + problem.OptimisationAvecVariablesEntieres = (study.parameters.unitCommitment.ucMode + == Antares::Data::UnitCommitmentMode::ucMILP); - problem.OptimisationAuPasHebdomadaire - = (parameters.simplexOptimizationRange == Data::sorWeek); + problem.OptimisationAuPasHebdomadaire = (parameters.simplexOptimizationRange == Data::sorWeek); switch (parameters.power.fluctuations) { @@ -142,9 +138,12 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, break; } + Antares::Data::Area::ScratchMap scratchmap = study.areas.buildScratchMap(numspace); + for (uint i = 0; i != study.areas.size(); i++) { - auto& area = *(study.areas[i]); + const auto& area = *(study.areas[i]); + const auto& scratchpad = scratchmap.at(&area); problem.NomsDesPays[i] = area.id.c_str(); @@ -154,30 +153,34 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.CoutDeDefaillanceEnReserve[i] = area.thermal.unsuppliedEnergyCost; - problem.DefaillanceNegativeUtiliserPMinThermique[i] - = (anoOtherDispatchPower & area.nodalOptimization) != 0; - problem.DefaillanceNegativeUtiliserHydro[i] - = (anoDispatchHydroPower & area.nodalOptimization) != 0; - problem.DefaillanceNegativeUtiliserConsoAbattue[i] - = (anoNonDispatchPower & area.nodalOptimization) != 0; + problem.DefaillanceNegativeUtiliserPMinThermique[i] = (anoOtherDispatchPower + & area.nodalOptimization) + != 0; + problem.DefaillanceNegativeUtiliserHydro[i] = (anoDispatchHydroPower + & area.nodalOptimization) + != 0; + problem.DefaillanceNegativeUtiliserConsoAbattue[i] = (anoNonDispatchPower + & area.nodalOptimization) + != 0; - problem.CaracteristiquesHydrauliques[i].PresenceDHydrauliqueModulable - = area.scratchpad[numSpace].hydroHasMod; + problem.CaracteristiquesHydrauliques[i].PresenceDHydrauliqueModulable = scratchpad + .hydroHasMod; problem.CaracteristiquesHydrauliques[i].PresenceDePompageModulable - = area.hydro.reservoirManagement && area.scratchpad[numSpace].pumpHasMod - && area.hydro.pumpingEfficiency > 0. - && problem.CaracteristiquesHydrauliques[i].PresenceDHydrauliqueModulable; + = area.hydro.reservoirManagement && scratchpad.pumpHasMod + && area.hydro.pumpingEfficiency > 0. + && problem.CaracteristiquesHydrauliques[i].PresenceDHydrauliqueModulable; problem.CaracteristiquesHydrauliques[i].PumpingRatio = area.hydro.pumpingEfficiency; - problem.CaracteristiquesHydrauliques[i].SansHeuristique - = area.hydro.reservoirManagement && !area.hydro.useHeuristicTarget; - - problem.CaracteristiquesHydrauliques[i].TurbinageEntreBornes - = area.hydro.reservoirManagement - && (!area.hydro.useHeuristicTarget || area.hydro.useLeeway); + problem.CaracteristiquesHydrauliques[i].SansHeuristique = area.hydro.reservoirManagement + && !area.hydro.useHeuristicTarget; + problem.CaracteristiquesHydrauliques[i].TurbinageEntreBornes = area.hydro + .reservoirManagement + && (!area.hydro + .useHeuristicTarget + || area.hydro.useLeeway); problem.CaracteristiquesHydrauliques[i].SuiviNiveauHoraire = area.hydro.reservoirManagement && (problem.OptimisationAuPasHebdomadaire) @@ -195,7 +198,7 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.CaracteristiquesHydrauliques[i].TailleReservoir = area.hydro.reservoirCapacity; - for (int pdt = 0; pdt < NombreDePasDeTemps; pdt++) + for (unsigned pdt = 0; pdt < NombreDePasDeTemps; pdt++) { problem.CaracteristiquesHydrauliques[i].NiveauHoraireInf[pdt] = 0; problem.CaracteristiquesHydrauliques[i].NiveauHoraireSup[pdt] @@ -204,9 +207,6 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.previousSimulationFinalLevel[i] = -1.; - if (!problem.previousYearFinalLevels.empty()) - problem.previousYearFinalLevels[i] = -1.; - problem.CaracteristiquesHydrauliques[i].WeeklyWaterValueStateRegular = 0.; problem.CaracteristiquesHydrauliques[i].WeeklyGeneratingModulation = 1.; @@ -225,10 +225,12 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.PaysExtremiteDeLInterconnexion[i] = link.with->index; } - for (uint i = 0; i < activeContraints.size(); ++i) + for (unsigned constraintIndex = 0; constraintIndex < activeConstraints.size(); + constraintIndex++) { - auto bc = activeContraints[i]; - CONTRAINTES_COUPLANTES& PtMat = problem.MatriceDesContraintesCouplantes[i]; + auto bc = activeConstraints[constraintIndex]; + CONTRAINTES_COUPLANTES& PtMat = problem.MatriceDesContraintesCouplantes[constraintIndex]; + PtMat.bindingConstraint = bc; PtMat.NombreDInterconnexionsDansLaContrainteCouplante = bc->linkCount(); PtMat.NombreDePaliersDispatchDansLaContrainteCouplante = bc->clusterCount(); PtMat.NombreDElementsDansLaContrainteCouplante = bc->linkCount() + bc->clusterCount(); @@ -249,7 +251,8 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, assert(false && "Invalid constraint"); break; } - PtMat.SensDeLaContrainteCouplante = *Antares::Data::BindingConstraint::MathOperatorToCString(bc->operatorType()); + PtMat.SensDeLaContrainteCouplante = *Antares::Data::BindingConstraint:: + MathOperatorToCString(bc->operatorType()); BindingConstraintStructures bindingConstraintStructures = bc->initLinkArrays(); for (uint j = 0; j < bc->linkCount(); ++j) @@ -266,47 +269,51 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, PtMat.PaysDuPalierDispatch[j] = bindingConstraintStructures.clustersAreaIndex[j]; PtMat.PoidsDuPalierDispatch[j] = bindingConstraintStructures.clusterWeight[j]; - PtMat.OffsetTemporelSurLePalierDispatch[j] = bindingConstraintStructures.clusterOffset[j]; + PtMat.OffsetTemporelSurLePalierDispatch[j] = bindingConstraintStructures + .clusterOffset[j]; } } NombrePaliers = 0; for (uint i = 0; i < study.areas.size(); ++i) { - auto& area = *(study.areas.byIndex[i]); + const auto& area = *(study.areas.byIndex[i]); auto& pbPalier = problem.PaliersThermiquesDuPays[i]; - pbPalier.NombreDePaliersThermiques = area.thermal.list.size(); + unsigned int clusterCount = area.thermal.list.enabledAndNotMustRunCount(); + pbPalier.NombreDePaliersThermiques = clusterCount; - for (uint clusterIndex = 0; clusterIndex != area.thermal.list.size(); ++clusterIndex) + for (const auto& cluster: area.thermal.list.each_enabled_and_not_mustrun()) { - auto& cluster = *(area.thermal.list.byIndex[clusterIndex]); - pbPalier.NumeroDuPalierDansLEnsembleDesPaliersThermiques[clusterIndex] - = NombrePaliers + clusterIndex; - pbPalier.TailleUnitaireDUnGroupeDuPalierThermique[clusterIndex] - = cluster.nominalCapacityWithSpinning; - pbPalier.PminDuPalierThermiquePendantUneHeure[clusterIndex] = cluster.minStablePower; - pbPalier.PminDuPalierThermiquePendantUnJour[clusterIndex] = 0; - pbPalier.minUpDownTime[clusterIndex] = cluster.minUpDownTime; - - pbPalier.CoutDeDemarrageDUnGroupeDuPalierThermique[clusterIndex] = cluster.startupCost; - pbPalier.CoutDArretDUnGroupeDuPalierThermique[clusterIndex] = 0; - pbPalier.CoutFixeDeMarcheDUnGroupeDuPalierThermique[clusterIndex] = cluster.fixedCost; - pbPalier.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[clusterIndex] - = cluster.minUpTime; - pbPalier.DureeMinimaleDArretDUnGroupeDuPalierThermique[clusterIndex] - = cluster.minDownTime; - - pbPalier.PmaxDUnGroupeDuPalierThermique[clusterIndex] - = cluster.nominalCapacityWithSpinning; - pbPalier.pminDUnGroupeDuPalierThermique[clusterIndex] - = (pbPalier.PmaxDUnGroupeDuPalierThermique[clusterIndex] < cluster.minStablePower) - ? pbPalier.PmaxDUnGroupeDuPalierThermique[clusterIndex] - : cluster.minStablePower; - pbPalier.NomsDesPaliersThermiques[clusterIndex] = cluster.name().c_str(); + pbPalier.NumeroDuPalierDansLEnsembleDesPaliersThermiques[cluster->index] = NombrePaliers + + cluster + ->index; + pbPalier.TailleUnitaireDUnGroupeDuPalierThermique[cluster->index] + = cluster->nominalCapacityWithSpinning; + pbPalier.PminDuPalierThermiquePendantUneHeure[cluster->index] = cluster->minStablePower; + pbPalier.PminDuPalierThermiquePendantUnJour[cluster->index] = 0; + pbPalier.minUpDownTime[cluster->index] = cluster->minUpDownTime; + + pbPalier.CoutDeDemarrageDUnGroupeDuPalierThermique[cluster->index] = cluster + ->startupCost; + pbPalier.CoutDArretDUnGroupeDuPalierThermique[cluster->index] = 0; + pbPalier.CoutFixeDeMarcheDUnGroupeDuPalierThermique[cluster->index] = cluster + ->fixedCost; + pbPalier.DureeMinimaleDeMarcheDUnGroupeDuPalierThermique[cluster->index] + = cluster->minUpTime; + pbPalier.DureeMinimaleDArretDUnGroupeDuPalierThermique[cluster->index] + = cluster->minDownTime; + + pbPalier.PmaxDUnGroupeDuPalierThermique[cluster->index] + = cluster->nominalCapacityWithSpinning; + pbPalier.pminDUnGroupeDuPalierThermique[cluster->index] + = (pbPalier.PmaxDUnGroupeDuPalierThermique[cluster->index] < cluster->minStablePower) + ? pbPalier.PmaxDUnGroupeDuPalierThermique[cluster->index] + : cluster->minStablePower; + pbPalier.NomsDesPaliersThermiques[cluster->index] = cluster->name().c_str(); } - NombrePaliers += area.thermal.list.size(); + NombrePaliers += clusterCount; } problem.NombreDePaliersThermiques = NombrePaliers; @@ -314,64 +321,82 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.LeProblemeADejaEteInstancie = false; } -void preparerBindingConstraint(const PROBLEME_HEBDO &problem, uint numSpace, int PasDeTempsDebut, - const BindingConstraintsRepository &bindingConstraints, const uint weekFirstDay, int pasDeTemps) +static void prepareBindingConstraint(PROBLEME_HEBDO& problem, + int PasDeTempsDebut, + const BindingConstraintsRepository& bindingConstraints, + const BindingConstraintGroupRepository& bcgroups, + const uint weekFirstDay, + int pasDeTemps) { - auto activeContraints = bindingConstraints.activeContraints(); - const auto constraintCount = activeContraints.size(); + auto activeConstraints = bindingConstraints.activeConstraints(); + const auto constraintCount = activeConstraints.size(); + for (unsigned constraintIndex = 0; constraintIndex != constraintCount; ++constraintIndex) { - auto bc = activeContraints[constraintIndex]; + auto bc = activeConstraints[constraintIndex]; assert(bc->RHSTimeSeries().width && "Invalid constraint data width"); - //If there is only one TS, always select it. - const auto ts_number = bc->RHSTimeSeries().width == 1 ? 0 : NumeroChroniquesTireesParGroup[numSpace][bc->group()]; + + uint tsIndexForBc = 0; + auto* group = bcgroups[bc->group()]; + if (group) + { + tsIndexForBc = group->timeseriesNumbers[problem.year]; + } + + // If there is only one TS, always select it. + const auto ts_number = bc->RHSTimeSeries().width == 1 ? 0 : tsIndexForBc; + auto& timeSeries = bc->RHSTimeSeries(); - double const* column = timeSeries[ts_number]; + const double* column = timeSeries[ts_number]; switch (bc->type()) { - case BindingConstraint::typeHourly: - { - problem.MatriceDesContraintesCouplantes[constraintIndex] - .SecondMembreDeLaContrainteCouplante[pasDeTemps] - = column[PasDeTempsDebut + pasDeTemps]; - break; - } - case BindingConstraint::typeDaily: - { - assert(timeSeries.width && "Invalid constraint data width"); - assert(weekFirstDay + 6 < timeSeries.height && "Invalid constraint data height"); - - std::vector& sndMember - = problem.MatriceDesContraintesCouplantes[constraintIndex] - .SecondMembreDeLaContrainteCouplante; + case BindingConstraint::typeHourly: + { + problem.MatriceDesContraintesCouplantes[constraintIndex] + .SecondMembreDeLaContrainteCouplante[pasDeTemps] + = column[PasDeTempsDebut + pasDeTemps]; + break; + } + case BindingConstraint::typeDaily: + { + assert(timeSeries.width && "Invalid constraint data width"); + assert(weekFirstDay + 6 < timeSeries.height && "Invalid constraint data height"); - for (unsigned day = 0; day != 7; ++day) - sndMember[day] = column[weekFirstDay + day]; + std::vector& sndMember = problem + .MatriceDesContraintesCouplantes[constraintIndex] + .SecondMembreDeLaContrainteCouplante; - break; - } - case BindingConstraint::typeWeekly: + for (unsigned day = 0; day != 7; ++day) { - assert(timeSeries.width && "Invalid constraint data width"); - assert(weekFirstDay + 6 < timeSeries.height && "Invalid constraint data height"); + sndMember[day] = column[weekFirstDay + day]; + } - double sum = 0; - for (unsigned day = 0; day != 7; ++day) - sum += column[weekFirstDay + day]; + break; + } + case BindingConstraint::typeWeekly: + { + assert(timeSeries.width && "Invalid constraint data width"); + assert(weekFirstDay + 6 < timeSeries.height && "Invalid constraint data height"); - problem.MatriceDesContraintesCouplantes[constraintIndex] - .SecondMembreDeLaContrainteCouplante[0] - = sum; - break; - } - case BindingConstraint::typeUnknown: - case BindingConstraint::typeMax: - default: + double sum = 0; + for (unsigned day = 0; day != 7; ++day) { - assert(false && "invalid constraint type"); - logs.error() << "internal error. Please submit a full bug report"; - break; + sum += column[weekFirstDay + day]; } + + problem.MatriceDesContraintesCouplantes[constraintIndex] + .SecondMembreDeLaContrainteCouplante[0] + = sum; + break; + } + case BindingConstraint::typeUnknown: + case BindingConstraint::typeMax: + default: + { + assert(false && "invalid constraint type"); + logs.error() << "internal error. Please submit a full bug report"; + break; + } } } } @@ -379,9 +404,10 @@ void preparerBindingConstraint(const PROBLEME_HEBDO &problem, uint numSpace, int void SIM_RenseignementProblemeHebdo(const Study& study, PROBLEME_HEBDO& problem, uint weekInTheYear, - uint numSpace, const int PasDeTempsDebut, - const ALL_HYDRO_VENTILATION_RESULTS& hydroVentilationResults) + const HYDRO_VENTILATION_RESULTS& hydroVentilationResults, + const Antares::Data::Area::ScratchMap& scratchmap) + { const auto& parameters = study.parameters; auto& studyruntime = *study.runtime; @@ -394,8 +420,6 @@ void SIM_RenseignementProblemeHebdo(const Study& study, { problem.coutOptimalSolution1[opt] = 0.; problem.coutOptimalSolution2[opt] = 0.; - problem.tempsResolution1[opt] = 0.; - problem.tempsResolution2[opt] = 0.; } for (uint k = 0; k < studyruntime.interconnectionsCount(); ++k) @@ -406,29 +430,38 @@ void SIM_RenseignementProblemeHebdo(const Study& study, { COUTS_DE_TRANSPORT& couts = problem.CoutDeTransport[k]; couts.IntercoGereeAvecDesCouts = true; - const double* direct - = ((const double*)((void*)lnk->parameters[fhlHurdlesCostDirect])) + PasDeTempsDebut; - const double* indirect - = ((const double*)((void*)lnk->parameters[fhlHurdlesCostIndirect])) + PasDeTempsDebut; + const double* direct = ((const double*)((void*)lnk->parameters[fhlHurdlesCostDirect])) + + PasDeTempsDebut; + const double* indirect = ((const double*)((void*) + lnk->parameters[fhlHurdlesCostIndirect])) + + PasDeTempsDebut; memcpy(&couts.CoutDeTransportOrigineVersExtremite[0], direct, pasDeTempsSizeDouble); memcpy(&couts.CoutDeTransportOrigineVersExtremiteRef[0], direct, pasDeTempsSizeDouble); memcpy(&couts.CoutDeTransportExtremiteVersOrigine[0], indirect, pasDeTempsSizeDouble); - memcpy(&couts.CoutDeTransportExtremiteVersOrigineRef[0], indirect, pasDeTempsSizeDouble); + memcpy(&couts.CoutDeTransportExtremiteVersOrigineRef[0], + indirect, + pasDeTempsSizeDouble); } else + { problem.CoutDeTransport[k].IntercoGereeAvecDesCouts = false; + } if (lnk->useLoopFlow) { problem.CoutDeTransport[k].IntercoGereeAvecLoopFlow = true; } else + { problem.CoutDeTransport[k].IntercoGereeAvecLoopFlow = false; + } } int weekDayIndex[8]; for (int day = 0; day < 8; day++) + { weekDayIndex[day] = study.calendar.hours[PasDeTempsDebut + day * 24].dayYear; + } double levelInterpolBeg; double levelInterpolEnd; @@ -465,26 +498,26 @@ void SIM_RenseignementProblemeHebdo(const Study& study, if (area.hydro.powerToLevel) { - problem.CaracteristiquesHydrauliques[k].WeeklyGeneratingModulation - = Antares::Data::getWeeklyModulation( - problem.previousSimulationFinalLevel[k] * 100 / area.hydro.reservoirCapacity, - area.hydro.creditModulation, - Data::PartHydro::genMod); - - problem.CaracteristiquesHydrauliques[k].WeeklyPumpingModulation - = Antares::Data::getWeeklyModulation( - problem.previousSimulationFinalLevel[k] * 100 / area.hydro.reservoirCapacity, - area.hydro.creditModulation, - Data::PartHydro::pumpMod); + problem.CaracteristiquesHydrauliques[k].WeeklyGeneratingModulation = Antares::Data:: + getWeeklyModulation(problem.previousSimulationFinalLevel[k] * 100 + / area.hydro.reservoirCapacity, + area.hydro.creditModulation, + Data::PartHydro::genMod); + + problem.CaracteristiquesHydrauliques[k].WeeklyPumpingModulation = Antares::Data:: + getWeeklyModulation(problem.previousSimulationFinalLevel[k] * 100 + / area.hydro.reservoirCapacity, + area.hydro.creditModulation, + Data::PartHydro::pumpMod); } if (area.hydro.useWaterValue) { - Antares::Data::getWaterValue( - problem.previousSimulationFinalLevel[k] * 100 / area.hydro.reservoirCapacity, - area.hydro.waterValues, - weekFirstDay, - problem.CaracteristiquesHydrauliques[k].WeeklyWaterValueStateRegular); + problem.CaracteristiquesHydrauliques[k].WeeklyWaterValueStateRegular + = getWaterValue(problem.previousSimulationFinalLevel[k] * 100 + / area.hydro.reservoirCapacity, + area.hydro.waterValues, + weekFirstDay); } if (problem.CaracteristiquesHydrauliques[k].PresenceDHydrauliqueModulable > 0) @@ -497,31 +530,35 @@ void SIM_RenseignementProblemeHebdo(const Study& study, for (int day = 0; day < 7; day++) { - levelInterpolBeg - = minLvl[weekDayIndex[day]] - * problem.CaracteristiquesHydrauliques[k].TailleReservoir; - levelInterpolEnd - = minLvl[weekDayIndex[day + 1]] - * problem.CaracteristiquesHydrauliques[k].TailleReservoir; + levelInterpolBeg = minLvl[weekDayIndex[day]] + * problem.CaracteristiquesHydrauliques[k] + .TailleReservoir; + levelInterpolEnd = minLvl[weekDayIndex[day + 1]] + * problem.CaracteristiquesHydrauliques[k] + .TailleReservoir; delta = (levelInterpolEnd - levelInterpolBeg) / 24.; for (int hour = 0; hour < 24; hour++) + { problem.CaracteristiquesHydrauliques[k] .NiveauHoraireInf[24 * day + hour] = levelInterpolBeg + hour * delta; + } - levelInterpolBeg - = maxLvl[weekDayIndex[day]] - * problem.CaracteristiquesHydrauliques[k].TailleReservoir; - levelInterpolEnd - = maxLvl[weekDayIndex[day + 1]] - * problem.CaracteristiquesHydrauliques[k].TailleReservoir; + levelInterpolBeg = maxLvl[weekDayIndex[day]] + * problem.CaracteristiquesHydrauliques[k] + .TailleReservoir; + levelInterpolEnd = maxLvl[weekDayIndex[day + 1]] + * problem.CaracteristiquesHydrauliques[k] + .TailleReservoir; delta = (levelInterpolEnd - levelInterpolBeg) / 24.; for (int hour = 0; hour < 24; hour++) + { problem.CaracteristiquesHydrauliques[k] .NiveauHoraireSup[24 * day + hour] = levelInterpolBeg + hour * delta; + } } } } @@ -538,91 +575,97 @@ void SIM_RenseignementProblemeHebdo(const Study& study, } } - int hourInYear = PasDeTempsDebut; unsigned int year = problem.year; - for (unsigned hourInWeek = 0; hourInWeek < problem.NombreDePasDeTemps; ++hourInWeek, ++hourInYear) + uint linkCount = studyruntime.interconnectionsCount(); + for (uint k = 0; k != linkCount; ++k) { - VALEURS_DE_NTC_ET_RESISTANCES& ntc = problem.ValeursDeNTC[hourInWeek]; + int hourInYear = PasDeTempsDebut; + auto& lnk = *(studyruntime.areaLink[k]); + const double* directCapacities = lnk.directCapacities.getColumn(year); + const double* indirectCapacities = lnk.indirectCapacities.getColumn(year); + for (unsigned hourInWeek = 0; hourInWeek < problem.NombreDePasDeTemps; + ++hourInWeek, ++hourInYear) { - uint linkCount = studyruntime.interconnectionsCount(); - for (uint k = 0; k != linkCount; ++k) - { - auto& lnk = *(studyruntime.areaLink[k]); - const int tsIndex - = NumeroChroniquesTireesParInterconnexion[numSpace][k].TransmissionCapacities; + VALEURS_DE_NTC_ET_RESISTANCES& ntc = problem.ValeursDeNTC[hourInWeek]; - assert((uint)hourInYear < lnk.directCapacities.height); - assert((uint)tsIndex < lnk.directCapacities.width); - assert((uint)tsIndex < lnk.indirectCapacities.width); - - ntc.ValeurDeNTCOrigineVersExtremite[k] = lnk.directCapacities[tsIndex][hourInYear]; - ntc.ValeurDeNTCExtremiteVersOrigine[k] = lnk.indirectCapacities[tsIndex][hourInYear]; - ntc.ValeurDeLoopFlowOrigineVersExtremite[k] = lnk.parameters[fhlLoopFlow][hourInYear]; - } + ntc.ValeurDeNTCOrigineVersExtremite[k] = directCapacities[hourInYear]; + ntc.ValeurDeNTCExtremiteVersOrigine[k] = indirectCapacities[hourInYear]; + ntc.ValeurDeLoopFlowOrigineVersExtremite[k] = lnk.parameters[fhlLoopFlow][hourInYear]; } - preparerBindingConstraint(problem, numSpace, PasDeTempsDebut, study.bindingConstraints, weekFirstDay, hourInWeek); + } - const uint dayInTheYear = study.calendar.hours[hourInYear].dayYear; + int hourInYear = PasDeTempsDebut; + for (unsigned hourInWeek = 0; hourInWeek < problem.NombreDePasDeTemps; + ++hourInWeek, ++hourInYear) + { + prepareBindingConstraint(problem, + PasDeTempsDebut, + study.bindingConstraints, + study.bindingConstraintsGroups, + weekFirstDay, + hourInWeek); for (uint k = 0; k < nbPays; ++k) { auto& area = *(study.areas.byIndex[k]); - auto& scratchpad = area.scratchpad[numSpace]; - auto& ror = area.hydro.series->ror; - auto loadSeries = area.load.series->getCoefficient(year, hourInYear); - auto windSeries = area.wind.series->getCoefficient(year, hourInYear); - auto solarSeries = area.solar.series->getCoefficient(year, hourInYear); - auto hydroSeriesIndex = area.hydro.series->getIndex(year); - - assert(&scratchpad); - - uint tsFatalIndex = hydroSeriesIndex < ror.width ? hydroSeriesIndex : 0; - double& mustRunGen = problem.AllMustRunGeneration[hourInWeek].AllMustRunGenerationOfArea[k]; + const auto& scratchpad = scratchmap.at(&area); + const double hourlyLoad = area.load.series.getCoefficient(year, hourInYear); + const double hourlyWind = area.wind.series.getCoefficient(year, hourInYear); + const double hourlySolar = area.solar.series.getCoefficient(year, hourInYear); + const double hourlyROR = area.hydro.series->ror.getCoefficient(year, hourInYear); + const double hourlyHydroGenPower = area.hydro.series->maxHourlyGenPower + .getCoefficient(year, hourInYear); + const double hourlyHydroPumpPower = area.hydro.series->maxHourlyPumpPower + .getCoefficient(year, hourInYear); + + double& mustRunGen = problem.AllMustRunGeneration[hourInWeek] + .AllMustRunGenerationOfArea[k]; if (parameters.renewableGeneration.isAggregated()) { - mustRunGen = windSeries - + solarSeries - + scratchpad.miscGenSum[hourInYear] + ror[tsFatalIndex][hourInYear] - + scratchpad.mustrunSum[hourInYear]; + mustRunGen = hourlyWind + hourlySolar + scratchpad.miscGenSum[hourInYear] + + hourlyROR + scratchpad.mustrunSum[hourInYear]; } // Renewable if (parameters.renewableGeneration.isClusters()) { - mustRunGen = scratchpad.miscGenSum[hourInYear] + ror[tsFatalIndex][hourInYear] + mustRunGen = scratchpad.miscGenSum[hourInYear] + hourlyROR + scratchpad.mustrunSum[hourInYear]; - area.renewable.list.each([&](const RenewableCluster& cluster) { - assert(cluster.series->timeSeries.jit == NULL && "No JIT data from the solver"); - mustRunGen += cluster.valueAtTimeStep((uint)hourInYear, year); - }); + for (const auto& c: area.renewable.list.each_enabled()) + { + mustRunGen += c->valueAtTimeStep(year, hourInYear); + } } assert( - !Math::NaN(problem.AllMustRunGeneration[hourInWeek].AllMustRunGenerationOfArea[k]) + !std::isnan(problem.AllMustRunGeneration[hourInWeek].AllMustRunGenerationOfArea[k]) && "NaN detected for 'AllMustRunGeneration', probably from miscGenSum/mustrunSum"); problem.ConsommationsAbattues[hourInWeek].ConsommationAbattueDuPays[k] - = +loadSeries + = +hourlyLoad - problem.AllMustRunGeneration[hourInWeek].AllMustRunGenerationOfArea[k]; if (problem.CaracteristiquesHydrauliques[k].PresenceDHydrauliqueModulable > 0) { - problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxHydrauliqueHoraire[hourInWeek] - = scratchpad.optimalMaxPower[dayInTheYear] + problem.CaracteristiquesHydrauliques[k] + .ContrainteDePmaxHydrauliqueHoraire[hourInWeek] + = hourlyHydroGenPower * problem.CaracteristiquesHydrauliques[k].WeeklyGeneratingModulation; } if (problem.CaracteristiquesHydrauliques[k].PresenceDePompageModulable) { problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxPompageHoraire[hourInWeek] - = scratchpad.pumpingMaxPower[dayInTheYear] + = hourlyHydroPumpPower * problem.CaracteristiquesHydrauliques[k].WeeklyPumpingModulation; } - problem.ReserveJMoins1[k].ReserveHoraireJMoins1[hourInWeek] - = area.reserves[fhrDayBefore][PasDeTempsDebut + hourInWeek]; + problem.ReserveJMoins1[k].ReserveHoraireJMoins1[hourInWeek] = area.reserves + [fhrDayBefore] + [PasDeTempsDebut + + hourInWeek]; } } @@ -632,17 +675,19 @@ void SIM_RenseignementProblemeHebdo(const Study& study, if (problem.CaracteristiquesHydrauliques[k].PresenceDHydrauliqueModulable > 0) { auto& area = *study.areas.byIndex[k]; + const auto& scratchpad = scratchmap.at(&area); auto& hydroSeries = area.hydro.series; - uint tsIndex = hydroSeries->getIndex(year); - auto& inflowsmatrix = hydroSeries->storage; - auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; - auto& mingenmatrix = hydroSeries->mingen; - auto const& srcmingen = mingenmatrix[tsIndex < mingenmatrix.width ? tsIndex : 0]; + const auto& dailyMeanMaxGenPower = scratchpad.meanMaxDailyGenPower.getColumn(year); + const auto& dailyMeanMaxPumpPower = scratchpad.meanMaxDailyPumpPower.getColumn( + year); + const auto& srcinflows = hydroSeries->storage.getColumn(year); + const auto& srcmingen = hydroSeries->mingen.getColumn(year); + for (uint j = 0; j < problem.NombreDePasDeTemps; ++j) { - problem.CaracteristiquesHydrauliques[k].MingenHoraire[j] - = srcmingen[PasDeTempsDebut + j]; + problem.CaracteristiquesHydrauliques[k].MingenHoraire[j] = srcmingen + [PasDeTempsDebut + j]; } if (area.hydro.reservoirManagement) @@ -660,8 +705,7 @@ void SIM_RenseignementProblemeHebdo(const Study& study, = 0.; problem.CaracteristiquesHydrauliques[k] .MaxEnergieHydrauParIntervalleOptimise[j] - = area.hydro.maxPower[area.hydro.genMaxP][day] - * area.hydro.maxPower[area.hydro.genMaxE][day] + = dailyMeanMaxGenPower[day] * area.hydro.dailyNbHoursAtGenPmax[0][day] * problem.CaracteristiquesHydrauliques[k] .WeeklyGeneratingModulation; } @@ -673,25 +717,28 @@ void SIM_RenseignementProblemeHebdo(const Study& study, && !problem.OptimisationAuPasHebdomadaire))) { std::vector& DGU = problem.CaracteristiquesHydrauliques[k] - .MaxEnergieHydrauParIntervalleOptimise; + .MaxEnergieHydrauParIntervalleOptimise; std::vector& DGL = problem.CaracteristiquesHydrauliques[k] - .MinEnergieHydrauParIntervalleOptimise; + .MinEnergieHydrauParIntervalleOptimise; - const std::vector& DNT - = hydroVentilationResults[numSpace][k].HydrauliqueModulableQuotidien; + const std::vector& DNT = hydroVentilationResults[k] + .HydrauliqueModulableQuotidien; - double WSL - = problem.CaracteristiquesHydrauliques[k].NiveauInitialReservoir; + double WSL = problem.CaracteristiquesHydrauliques[k].NiveauInitialReservoir; double LUB = area.hydro.leewayUpperBound; if (!area.hydro.useLeeway) + { LUB = 1; + } double LLB = area.hydro.leewayLowerBound; if (!area.hydro.useLeeway) + { LLB = 1; - double DGM - = problem.CaracteristiquesHydrauliques[k].WeeklyGeneratingModulation; + } + double DGM = problem.CaracteristiquesHydrauliques[k] + .WeeklyGeneratingModulation; double rc = area.hydro.reservoirCapacity; @@ -711,8 +758,8 @@ void SIM_RenseignementProblemeHebdo(const Study& study, { uint day = study.calendar.hours[PasDeTempsDebut + j * 24].dayYear; - double DGC = area.hydro.maxPower[area.hydro.genMaxP][day] - * area.hydro.maxPower[area.hydro.genMaxE][day]; + double DGC = dailyMeanMaxGenPower[day] + * area.hydro.dailyNbHoursAtGenPmax[0][day]; DGU_tmp[j] = DNT[day] * LUB; DGL_tmp[j] = DNT[day] * LLB; @@ -725,7 +772,9 @@ void SIM_RenseignementProblemeHebdo(const Study& study, } if (DGCxDGM > DGL_tmp[j] && DGCxDGM < DGU_tmp[j]) + { DGU_tmp[j] = DGCxDGM; + } WGU += DGU_tmp[j]; } @@ -734,26 +783,35 @@ void SIM_RenseignementProblemeHebdo(const Study& study, { if (not area.hydro.hardBoundsOnRuleCurves) { - if (Math::Zero(WGU)) + if (Utils::isZero(WGU)) + { DGU[j] = 0.; + } else - DGU[j] = DGU_tmp[j] * Math::Min(WGU, WSL + WNI) / WGU; + { + DGU[j] = DGU_tmp[j] * std::min(WGU, WSL + WNI) / WGU; + } } else { - const uint nextWeekFirstDay - = study.calendar.hours[PasDeTempsDebut + 7 * 24].dayYear; + const uint nextWeekFirstDay = study.calendar + .hours[PasDeTempsDebut + 7 * 24] + .dayYear; auto& minLvl = area.hydro.reservoirLevel[Data::PartHydro::minimum]; - double V = Math::Max(0., WSL - minLvl[nextWeekFirstDay] * rc + WNI); + double V = std::max(0., WSL - minLvl[nextWeekFirstDay] * rc + WNI); - if (Math::Zero(WGU)) + if (Utils::isZero(WGU)) + { DGU[j] = 0.; + } else - DGU[j] = DGU_tmp[j] * Math::Min(WGU, V) / WGU; + { + DGU[j] = DGU_tmp[j] * std::min(WGU, V) / WGU; + } } - DGL[j] = Math::Min(DGU[j], DGL_tmp[j]); + DGL[j] = std::min(DGU[j], DGL_tmp[j]); } } } @@ -768,18 +826,22 @@ void SIM_RenseignementProblemeHebdo(const Study& study, for (uint j = 0; j < 7; ++j) { uint day = study.calendar.hours[PasDeTempsDebut + j * 24].dayYear; - weekTarget_tmp += hydroVentilationResults[numSpace][k] + weekTarget_tmp += hydroVentilationResults[k] .HydrauliqueModulableQuotidien[day]; } if (weekTarget_tmp != 0.) + { weekGenerationTarget = weekTarget_tmp; + } marginGen = weekGenerationTarget; if (problem.CaracteristiquesHydrauliques[k].NiveauInitialReservoir < weekTarget_tmp) + { marginGen = problem.CaracteristiquesHydrauliques[k].NiveauInitialReservoir; + } } if (not problem.CaracteristiquesHydrauliques[k].TurbinageEntreBornes) @@ -789,7 +851,7 @@ void SIM_RenseignementProblemeHebdo(const Study& study, uint day = study.calendar.hours[PasDeTempsDebut + j * 24].dayYear; problem.CaracteristiquesHydrauliques[k] .CntEnergieH2OParIntervalleOptimise[j] - = hydroVentilationResults[numSpace][k].HydrauliqueModulableQuotidien[day] + = hydroVentilationResults[k].HydrauliqueModulableQuotidien[day] * problem.CaracteristiquesHydrauliques[k].WeeklyGeneratingModulation * marginGen / weekGenerationTarget; } @@ -798,8 +860,8 @@ void SIM_RenseignementProblemeHebdo(const Study& study, for (uint j = 0; j < 7; ++j) { uint day = study.calendar.hours[PasDeTempsDebut + j * 24].dayYear; - problem.CaracteristiquesHydrauliques[k].InflowForTimeInterval[j] - = srcinflows[day]; + problem.CaracteristiquesHydrauliques[k].InflowForTimeInterval[j] = srcinflows + [day]; for (int h = 0; h < 24; h++) { problem.CaracteristiquesHydrauliques[k].ApportNaturelHoraire[j * 24 + h] @@ -820,8 +882,8 @@ void SIM_RenseignementProblemeHebdo(const Study& study, problem.CaracteristiquesHydrauliques[k] .MaxEnergiePompageParIntervalleOptimise[j] - = area.hydro.maxPower[area.hydro.pumpMaxP][day] - * area.hydro.maxPower[area.hydro.pumpMaxE][day] + = dailyMeanMaxPumpPower[day] + * area.hydro.dailyNbHoursAtPumpPmax[0][day] * problem.CaracteristiquesHydrauliques[k] .WeeklyPumpingModulation; } @@ -837,13 +899,13 @@ void SIM_RenseignementProblemeHebdo(const Study& study, } std::vector& DPU = problem.CaracteristiquesHydrauliques[k] - .MaxEnergiePompageParIntervalleOptimise; + .MaxEnergiePompageParIntervalleOptimise; - double WSL - = problem.CaracteristiquesHydrauliques[k].NiveauInitialReservoir; + double WSL = problem.CaracteristiquesHydrauliques[k] + .NiveauInitialReservoir; - double DPM - = problem.CaracteristiquesHydrauliques[k].WeeklyPumpingModulation; + double DPM = problem.CaracteristiquesHydrauliques[k] + .WeeklyPumpingModulation; double pumping_ratio = area.hydro.pumpingEfficiency; @@ -853,8 +915,8 @@ void SIM_RenseignementProblemeHebdo(const Study& study, { uint day = study.calendar.hours[PasDeTempsDebut + j * 24].dayYear; - double DPC = area.hydro.maxPower[area.hydro.pumpMaxP][day] - * area.hydro.maxPower[area.hydro.pumpMaxE][day]; + double DPC = dailyMeanMaxPumpPower[day] + * area.hydro.dailyNbHoursAtPumpPmax[0][day]; WPU += DPC; } @@ -864,34 +926,45 @@ void SIM_RenseignementProblemeHebdo(const Study& study, for (uint j = 0; j < 7; ++j) { uint day = study.calendar.hours[PasDeTempsDebut + j * 24].dayYear; - double DPC = area.hydro.maxPower[area.hydro.pumpMaxP][day] - * area.hydro.maxPower[area.hydro.pumpMaxE][day]; + + double DPC = dailyMeanMaxPumpPower[day] + * area.hydro.dailyNbHoursAtPumpPmax[0][day]; double rc = area.hydro.reservoirCapacity; if (not area.hydro.hardBoundsOnRuleCurves) { - double V = Math::Max(0., rc - (WNI + WSL)); + double V = std::max(0., rc - (WNI + WSL)); - if (Math::Zero(U)) + if (Utils::isZero(U)) + { DPU[j] = 0.; + } else - DPU[j] = DPC * DPM * Math::Min(U, V) / U; + { + DPU[j] = DPC * DPM * std::min(U, V) / U; + } } else { - const uint nextWeekFirstDay - = study.calendar.hours[PasDeTempsDebut + 7 * 24].dayYear; - auto& maxLvl - = area.hydro.reservoirLevel[Data::PartHydro::maximum]; - - double V - = Math::Max(0., maxLvl[nextWeekFirstDay] * rc - (WNI + WSL)); - - if (Math::Zero(U)) + const uint nextWeekFirstDay = study.calendar + .hours[PasDeTempsDebut + 7 * 24] + .dayYear; + auto& maxLvl = area.hydro + .reservoirLevel[Data::PartHydro::maximum]; + + double V = std::max(0., + maxLvl[nextWeekFirstDay] * rc + - (WNI + WSL)); + + if (Utils::isZero(U)) + { DPU[j] = 0.; + } else - DPU[j] = DPC * DPM * Math::Min(U, V) / U; + { + DPU[j] = DPC * DPM * std::min(U, V) / U; + } } } } @@ -904,6 +977,6 @@ void SIM_RenseignementProblemeHebdo(const Study& study, for (uint k = 0; k < nbPays; ++k) { problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxHydrauliqueHoraireRef - = problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxHydrauliqueHoraire; + = problem.CaracteristiquesHydrauliques[k].ContrainteDePmaxHydrauliqueHoraire; } } diff --git a/src/solver/simulation/sim_constants.h b/src/solver/simulation/sim_constants.h deleted file mode 100644 index 70c09dcc67..0000000000 --- a/src/solver/simulation/sim_constants.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -constexpr double LINFINI_ANTARES = 1.e+80; -constexpr int LINFINI_ENTIER = 20000000; - -constexpr char OPTIMISATION_LINEAIRE = 1; -constexpr char OPTIMISATION_QUADRATIQUE = 2; - -constexpr double ZERO_RESERVE_J_MOINS1 = 1.e-2; diff --git a/src/solver/simulation/sim_extern_variables_globales.h b/src/solver/simulation/sim_extern_variables_globales.h deleted file mode 100644 index 421e8db76e..0000000000 --- a/src/solver/simulation/sim_extern_variables_globales.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_EXTERN_H__ -#define __SOLVER_SIMULATION_EXTERN_H__ - -#include "sim_structure_donnees.h" -#include "sim_structure_probleme_economique.h" - -/* Valeurs generees de maniere aleatoire */ -extern std::vector> NumeroChroniquesTireesParInterconnexion; -extern std::vector> NumeroChroniquesTireesParGroup; - -/* Resultats */ -/*-Economique-*/ -extern std::vector> transitMoyenInterconnexionsRecalculQuadratique; - -#endif /* __SOLVER_SIMULATION_EXTERN_H__ */ diff --git a/src/solver/simulation/sim_spread_generator.cpp b/src/solver/simulation/sim_spread_generator.cpp index 1240670df5..734cb92da6 100644 --- a/src/solver/simulation/sim_spread_generator.cpp +++ b/src/solver/simulation/sim_spread_generator.cpp @@ -1,36 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ - -#include "sim_spread_generator.h" +#include "antares/solver/simulation/sim_spread_generator.h" namespace SIM { -SpreadGenerator::SpreadGenerator(double range) : range_(range) +SpreadGenerator::SpreadGenerator(double range): + range_(range) { } diff --git a/src/solver/simulation/sim_spread_generator.h b/src/solver/simulation/sim_spread_generator.h deleted file mode 100644 index 4860179bcf..0000000000 --- a/src/solver/simulation/sim_spread_generator.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include - -namespace SIM -{ -class SpreadGenerator -{ - static constexpr double rangeDefault = 1.e-3; -public: - explicit SpreadGenerator(double range = rangeDefault); - void reset(unsigned int seed); - double generate(); - -private: - Antares::MersenneTwister mt_; - const double range_; -}; -} // namespace SIM diff --git a/src/solver/simulation/sim_structure_donnees.h b/src/solver/simulation/sim_structure_donnees.h deleted file mode 100644 index 6b3431a735..0000000000 --- a/src/solver/simulation/sim_structure_donnees.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_DATA_STRUCTS_H__ -#define __SOLVER_SIMULATION_DATA_STRUCTS_H__ - -#include - -typedef struct -{ - int TransmissionCapacities; -} NUMERO_CHRONIQUES_TIREES_PAR_INTERCONNEXION; - -typedef struct -{ - double* Horaire; -} PRODUCTION_THERMIQUE; - -typedef struct -{ - double* ParLigne; -} MATRICE_2D; - -/* Old define */ -#define DEFINITION_STRUCTURES_DONNEES - -#endif /* __SOLVER_SIMULATION_DATA_STRUCTS_H__ */ diff --git a/src/solver/simulation/sim_variables_globales.cpp b/src/solver/simulation/sim_variables_globales.cpp index e5fe936dc6..252c937631 100644 --- a/src/solver/simulation/sim_variables_globales.cpp +++ b/src/solver/simulation/sim_variables_globales.cpp @@ -1,35 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "sim_structure_donnees.h" -#include "sim_structure_probleme_economique.h" - -std::vector> NumeroChroniquesTireesParInterconnexion; +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" std::vector> transitMoyenInterconnexionsRecalculQuadratique; - -std::vector> NumeroChroniquesTireesParGroup; //Vector size = num_parallel_year diff --git a/src/solver/simulation/simulation.h b/src/solver/simulation/simulation.h deleted file mode 100644 index b105059bc3..0000000000 --- a/src/solver/simulation/simulation.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_H__ -#define __SOLVER_SIMULATION_H__ - -#include "../config.h" -#include "sim_structure_donnees.h" -#include -#include "../solver/hydro/management.h" - -struct PROBLEME_HEBDO; - -void SIM_AllocationTableaux(const Antares::Data::Study& study); - -/*! -** \brief Alloue toutes les donnees d'un probleme hebdo -*/ -void SIM_AllocationProblemeHebdo(const Antares::Data::Study& study, - PROBLEME_HEBDO& problem, - uint NombreDePasDeTemps); - -/*! -** \brief Alloue et initialise un probleme hebdo -*/ -void SIM_InitialisationProblemeHebdo(Antares::Data::Study& study, - PROBLEME_HEBDO& problem, - int NombreDePasDeTemps, - uint numSpace); - -void SIM_PreallocationTableaux(void); - -void SIM_RenseignementProblemeHebdo(const Antares::Data::Study& study, - PROBLEME_HEBDO& problem, - uint weekInTheYear, - uint numSpace, - const int, - const ALL_HYDRO_VENTILATION_RESULTS&); - -void SIM_RenseignementProblemeHoraireAdequation(uint); - -void SIM_CalculFlotHoraireAdequation(void); - -void SIM_InitialisationProblemeHoraireAdequation(void); - -void SIM_AllocationProblemeHoraireAdequation(void); - -void SIM_InitialisationChainagePourAdequation(void); - -void SIM_DesallocationProblemeHoraireAdequation(void); - -#endif /* __SOLVER_SIMULATION_H__ */ diff --git a/src/solver/simulation/solver.data.cpp b/src/solver/simulation/solver.data.cpp index e8ef266450..80c4f6ee9f 100644 --- a/src/solver/simulation/solver.data.cpp +++ b/src/solver/simulation/solver.data.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "solver.data.h" +#include "antares/solver/simulation/solver.data.h" + #include namespace Antares::Solver::Private::Simulation diff --git a/src/solver/simulation/solver.data.h b/src/solver/simulation/solver.data.h deleted file mode 100644 index d044822fa2..0000000000 --- a/src/solver/simulation/solver.data.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_SOLVER_DATA_H__ -#define __SOLVER_SIMULATION_SOLVER_DATA_H__ - -#include -#include - -namespace Antares::Solver::Private::Simulation -{ -class CacheData -{ -public: - /*! - ** \brief Re-Initialize the inner variables - */ - void initialize(const Antares::Data::Parameters& parameters); - -public: - //! True if the prepro `load` must be used - bool haveToRefreshTSLoad; - //! True if the prepro `solar` must be used - bool haveToRefreshTSSolar; - //! True if the prepro `wind` must be used - bool haveToRefreshTSWind; - //! True if the prepro `hydro` must be used - bool haveToRefreshTSHydro; - //! True if the prepro `thermal` must be used - bool haveToRefreshTSThermal; - - //! Refresh time interval for Load - unsigned int refreshIntervalLoad; - //! Refresh time interval for Solar - unsigned int refreshIntervalSolar; - //! Refresh time interval for Hydro - unsigned int refreshIntervalHydro; - //! Refresh time interval for wind - unsigned int refreshIntervalWind; - //! Refresh time interval for thermal - unsigned int refreshIntervalThermal; - -}; // class CacheData - -} // namespace Antares::Solver::Private::Simulation - -#endif // __SOLVER_SIMULATION_SOLVER_H__ diff --git a/src/solver/simulation/solver.h b/src/solver/simulation/solver.h deleted file mode 100644 index 45bf02ac47..0000000000 --- a/src/solver/simulation/solver.h +++ /dev/null @@ -1,184 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_SOLVER_H__ -#define __SOLVER_SIMULATION_SOLVER_H__ - -#include -#include -#include // PowerFluctuations -#include - -#include -#include -#include "../variable/state.h" -#include "../misc/options.h" -#include "solver.data.h" -#include "solver.utils.h" -#include "../hydro/management/management.h" - -#include - -namespace Antares::Solver::Simulation -{ - -template -class yearJob; - -template -class ISimulation : public Impl -{ - friend class yearJob; - -public: - //! The real implementation for the simulation - typedef Impl ImplementationType; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Constructor (with a given study) - */ - ISimulation(Data::Study& study, - const ::Settings& settings, - Benchmarking::IDurationCollector& duration_collector, - IResultWriter& resultWriter); - //! Destructor - ~ISimulation(); - //@} - - // Check that the writer is valid - void checkWriter() const; - - /*! - ** \brief Run the simulation - */ - void run(); - - /*! - ** \brief Export the results to disk - ** - ** \tparam ResultsForYearByYear False to write down the rglobal esults of the simulation, - ** true for the results of the current year (year-by-year mode) - ** \param year The current year, if applicable - */ - void writeResults(bool synthesis, uint year = 0, uint numSpace = 9999); - -public: - //! Reference to the current study - Data::Study& study; - //! The global settings - const ::Settings& settings; - -private: - /*! - ** \brief Regenerate time-series if required for a given year - */ - void regenerateTimeSeries(uint year); - - /*! - ** \brief Builds sets of parallel years - ** - ** \return The max number of years in a set of parallel years (to be executed or not) - */ - uint buildSetsOfParallelYears(uint firstYear, - uint endYear, - std::vector& setsOfParallelYears); - - /*! - ** \brief Allocate storage for random numbers of parallel years - ** - ** \param randomParallelYears ... to be finished ... - */ - void allocateMemoryForRandomNumbers(randomNumbers& randomForParallelYears); - - /*! - ** \brief Computes random numbers for each years of a list - ** - ** \param randomForYears Storage for random numbers for years in the list - ** \param years List of years - */ - void computeRandomNumbers(randomNumbers& randomForYears, - std::vector& years, - std::map& isYearPerformed); - - /*! - ** \brief Computes statistics on annual (system and solution) costs, to be printed in output - *into separate files - ** - ** Adds the contributions of each performed year contained in the current set to annual system - *and solution costs averages over all years. - ** These average costs are meant to be printed in output into separate files. - ** Same thing for min and max costs over all years. - ** Storing these costs to compute std deviation later. - */ - void computeAnnualCostsStatistics(std::vector& state, - std::vector::iterator& set_it); - - /*! - ** \brief Iterate through all MC years - ** - ** \param firstYear The first real MC year - ** \param endYear The last MC year - */ - void loopThroughYears(uint firstYear, uint endYear, std::vector& state); - - -private: - //! Some temporary to avoid performing useless complex checks - Solver::Private::Simulation::CacheData pData; - //! - uint pNbYearsReallyPerformed; - //! Max number of years performed in parallel - uint pNbMaxPerformedYearsInParallel; - //! Year by year output results - bool pYearByYear; - //! Hydro management - HydroManagement hydroManagement; - //! Hydro hot start - bool pHydroHotStart; - //! The first set of parallel year(s) with a performed year was already run ? - bool pFirstSetParallelWithAPerformedYearWasRun; - - //! Statistics about annual (system and solution) costs - annualCostsStatistics pAnnualCostsStatistics; - - // Collecting durations inside the simulation - Benchmarking::IDurationCollector& pDurationCollector; - -public: - //! The queue service that runs every set of parallel years - std::shared_ptr pQueueService = nullptr; - //! Result writer - Antares::Solver::IResultWriter& pResultWriter; - -}; // class ISimulation -} // namespace Antares::Solver::Simulation - -#include "solver.hxx" - -#endif // __SOLVER_SIMULATION_SOLVER_H__ diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx deleted file mode 100644 index 9b9e268077..0000000000 --- a/src/solver/simulation/solver.hxx +++ /dev/null @@ -1,1049 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_SOLVER_HXX__ -#define __SOLVER_SIMULATION_SOLVER_HXX__ - -#include "../variable/constants.h" -#include -#include -#include -#include -#include "../variable/print.h" -#include -#include "../aleatoire/alea_fonctions.h" -#include "timeseries-numbers.h" -#include "apply-scenario.h" -#include -#include "../ts-generator/generator.h" -#include "opt_time_writer.h" -#include "../hydro/management.h" // Added for use of randomReservoirLevel(...) - -#include -#include - -#include "antares/concurrency/concurrency.h" - -namespace Antares::Solver::Simulation -{ - -template -class yearJob -{ -public: - yearJob(ISimulation* simulation, - unsigned int pY, - std::map& pYearFailed, - std::map& pIsFirstPerformedYearOfASet, - bool pFirstSetParallelWithAPerformedYearWasRun, - unsigned int pNumSpace, - randomNumbers& pRandomForParallelYears, - bool pPerformCalculations, - Data::Study& pStudy, - std::vector& pState, - bool pYearByYear, - Benchmarking::IDurationCollector& durationCollector, - IResultWriter& resultWriter) : - simulation_(simulation), - y(pY), - yearFailed(pYearFailed), - isFirstPerformedYearOfASet(pIsFirstPerformedYearOfASet), - firstSetParallelWithAPerformedYearWasRun(pFirstSetParallelWithAPerformedYearWasRun), - numSpace(pNumSpace), - randomForParallelYears(pRandomForParallelYears), - performCalculations(pPerformCalculations), - study(pStudy), - state(pState), - yearByYear(pYearByYear), - pDurationCollector(durationCollector), - pResultWriter(resultWriter) - { - hydroHotStart = (study.parameters.initialReservoirLevels.iniLevels == Data::irlHotStart); - } - -private: - ISimulation* simulation_; - unsigned int y; - std::map& yearFailed; - std::map& isFirstPerformedYearOfASet; - bool firstSetParallelWithAPerformedYearWasRun; - unsigned int numSpace; - randomNumbers& randomForParallelYears; - bool performCalculations; - Data::Study& study; - std::vector& state; - bool yearByYear; - bool hydroHotStart; - Benchmarking::IDurationCollector& pDurationCollector; - IResultWriter& pResultWriter; -private: - /* - ** \brief Log failed week - ** - ** \param y MC Year - ** \param study The Antares study - ** \param failedWeek List of failing week - */ - void logFailedWeek(int y, const Data::Study& study, const std::list& failedWeekList) - { - if (failedWeekList.size() != 0) - { - std::stringstream failedWeekStr; - std::copy(failedWeekList.begin(), - failedWeekList.end(), - std::ostream_iterator(failedWeekStr, " ")); - - std::string s = failedWeekStr.str(); - s = s.substr(0, s.length() - 1); // get rid of the trailing space - - std::string failedStr - = failedWeekList.size() != 1 ? " failed at weeks " : " failed at week "; - - logs.info(); // empty line - - if (Data::stopSimulation(study.parameters.include.unfeasibleProblemBehavior)) - { - logs.fatal() << "Year " << y + 1 << failedStr << s << "."; - } - else - { - logs.warning() << "Year " << y + 1 << failedStr << s << "."; - } - } - } - -public: - void operator()() - { - Progression::Task progression(study, y, Solver::Progression::sectYear); - - if (performCalculations) - { - // Index of the current year in the list of structures - uint indexYear = randomForParallelYears.yearNumberToIndex[y]; - - // Getting random tables for this year - yearRandomNumbers& randomForCurrentYear = randomForParallelYears.pYears[indexYear]; - double* randomReservoirLevel = nullptr; - - // 1 - Applying random levels for current year - if (hydroHotStart && firstSetParallelWithAPerformedYearWasRun) - randomReservoirLevel = state[numSpace].problemeHebdo->previousYearFinalLevels.data(); - else - randomReservoirLevel = randomForCurrentYear.pReservoirLevels; - - // 2 - Preparing the Time-series numbers - // We want to draw lots of numbers for time-series - ApplyRandomTSnumbers(study, y, numSpace); - - // 3 - Preparing data related to Clusters in 'must-run' mode - simulation_->prepareClustersInMustRunMode(numSpace, y); - - // 4 - Hydraulic ventilation - { - Benchmarking::Timer timer; - simulation_->hydroManagement.makeVentilation(randomReservoirLevel, - state[numSpace], - y, - numSpace); - timer.stop(); - pDurationCollector.addDuration("hydro_ventilation", timer.get_duration()); - } - - // Updating the state - state[numSpace].year = y; - - // 5 - Resetting all variables for the output - simulation_->variables.yearBegin(y, numSpace); - - // 6 - The Solver itself - bool isFirstPerformedYearOfSimulation - = isFirstPerformedYearOfASet[y] && not firstSetParallelWithAPerformedYearWasRun; - std::list failedWeekList; - - OptimizationStatisticsWriter optWriter(pResultWriter, y); - yearFailed[y] = !simulation_->year(progression, - state[numSpace], - numSpace, - randomForCurrentYear, - failedWeekList, - isFirstPerformedYearOfSimulation, - simulation_->hydroManagement.ventilationResults(), - optWriter); - - // Log failing weeks - logFailedWeek(y, study, failedWeekList); - - simulation_->variables.yearEndBuild(state[numSpace], y, numSpace); - - // 7 - End of the year, this is the last stade where the variables can retrieve - // their data for this year. - simulation_->variables.yearEnd(y, numSpace); - - // 8 - Spatial clusters - // Notifying all variables to perform spatial aggregates. - // This must be done only when all variables have finished to compute their - // data for the year. - simulation_->variables.yearEndSpatialAggregates(simulation_->variables, y, numSpace); - - // 9 - Write results for the current year - if (yearByYear) - { - Benchmarking::Timer timerYear; - // Before writing, some variable may require minor modifications - simulation_->variables.beforeYearByYearExport(y, numSpace); - // writing the results for the current year into the output - simulation_->writeResults(false, y, numSpace); // false for synthesis - timerYear.stop(); - pDurationCollector.addDuration("yby_export", timerYear.get_duration()); - } - } - else - { - simulation_->incrementProgression(progression); - - logs.info() << " playlist: ignoring the year " << (y + 1); - - yearFailed[y] = false; - - } // End if(performCalculations) - - } // End of onExecute() method -}; - -template -inline ISimulation::ISimulation(Data::Study& study, - const ::Settings& settings, - Benchmarking::IDurationCollector& duration_collector, - IResultWriter& resultWriter) : - ImplementationType(study, resultWriter), - study(study), - settings(settings), - pNbYearsReallyPerformed(0), - pNbMaxPerformedYearsInParallel(0), - pYearByYear(study.parameters.yearByYear), - hydroManagement(study.areas, - study.parameters, - study.calendar, - study.maxNbYearsInParallel, - resultWriter), - pFirstSetParallelWithAPerformedYearWasRun(false), - pDurationCollector(duration_collector), - pQueueService(study.pQueueService), - pResultWriter(resultWriter) -{ - // Ask to the interface to show the messages - logs.info(); - logs.info() << LOG_UI_DISPLAY_MESSAGES_ON; - - // Running ! - logs.checkpoint() << "Running the simulation (" << ImplementationType::Name() << ')'; - logs.info() << "Allocating resources..."; - - if (pYearByYear && (settings.noOutput || settings.tsGeneratorsOnly)) - pYearByYear = false; - - pHydroHotStart = (study.parameters.initialReservoirLevels.iniLevels == Data::irlHotStart); -} - -template -inline void ISimulation::checkWriter() const -{ - // The zip writer needs a queue service (async mutexed write) - if (!pQueueService && pResultWriter.needsTheJobQueue()) - { - throw Solver::Initialization::Error::NoQueueService(); - } -} - -template -inline ISimulation::~ISimulation() -{ -} - -template -void ISimulation::run() -{ - pNbMaxPerformedYearsInParallel = study.maxNbYearsInParallel; - - // Initialize all data - ImplementationType::variables.initializeFromStudy(study); - // Computing the max number columns a report of any kind can contain. - study.parameters.variablesPrintInfo.computeMaxColumnsCountInReports(); - - logs.info() << "Allocating resources..."; - - // Memory usage - { - logs.info() << " Variables: (" - << (uint)(ImplementationType::variables.memoryUsage() / 1024 / 1024) << "Mo)"; - Variable::PrintInfosStdCout c; - ImplementationType::variables.template provideInformations(c); - } - - // Preprocessors - // Determine if we have to use the preprocessors at least one time. - pData.initialize(study.parameters); - - // Prepro only ? - ImplementationType::preproOnly = settings.tsGeneratorsOnly; - - ImplementationType::setNbPerformedYearsInParallel(pNbMaxPerformedYearsInParallel); - - if (settings.tsGeneratorsOnly) - { - // Only the preprocessors can be used - // We only have to regenerate time-series according the settings - // in general data of the study. - logs.info() << " Only the preprocessors are enabled."; - - regenerateTimeSeries(0); - - // Destroy the TS Generators if any - // It will export the time-series into the output in the same time - Solver::TSGenerator::DestroyAll(study); - } - else - { - if (not ImplementationType::simulationBegin()) - return; - // Allocating the memory - ImplementationType::variables.simulationBegin(); - - // For beauty - logs.info(); - - // Sampled time-series Numbers - // We will resize all matrix related to the time-series numbers - // This operation can be done once since the number of years is constant - // for a single simulation - study.resizeAllTimeseriesNumbers(1 + study.runtime->rangeLimits.year[Data::rangeEnd]); - // Now, we will prepare the time-series numbers - if (not TimeSeriesNumbers::Generate(study)) - { - throw FatalError("An unrecoverable error has occured. Can not continue."); - } - - if (study.parameters.useCustomScenario) - ApplyCustomScenario(study); - - // Launching the simulation for all years - logs.info() << "MC-Years : [" << (study.runtime->rangeLimits.year[Data::rangeBegin] + 1) - << " .. " << (1 + study.runtime->rangeLimits.year[Data::rangeEnd]) - << "], total: " << study.runtime->rangeLimits.year[Data::rangeCount]; - - // Current state - std::vector state(pNbMaxPerformedYearsInParallel, Variable::State(study)); - // Initializing states for parallel actually performed years - for (uint numSpace = 0; numSpace != pNbMaxPerformedYearsInParallel; ++numSpace) - ImplementationType::initializeState(state[numSpace], numSpace); - - logs.info() << " Starting the simulation"; - uint finalYear = 1 + study.runtime->rangeLimits.year[Data::rangeEnd]; - { - Benchmarking::Timer timer; - loopThroughYears(0, finalYear, state); - timer.stop(); - pDurationCollector.addDuration("mc_years", timer.get_duration()); - } - // Destroy the TS Generators if any - // It will export the time-series into the output in the same time - Solver::TSGenerator::DestroyAll(study); - - // Post operations - { - Benchmarking::Timer timer; - ImplementationType::simulationEnd(); - timer.stop(); - pDurationCollector.addDuration("post_processing", timer.get_duration()); - } - - ImplementationType::variables.simulationEnd(); - - // Export ts-numbers into output - TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(study, pResultWriter); - - // Spatial clusters - // Notifying all variables to perform the final spatial clusters. - // This must be done only when all variables have finished to compute their - // own data. - ImplementationType::variables.simulationEndSpatialAggregates(ImplementationType::variables); - } -} - -template -void ISimulation::writeResults(bool synthesis, uint year, uint numSpace) -{ - using namespace Yuni; - - // The writer might need the job queue, after it's been stopped - // this is the case e.g if synthesis == true (writing mc-all) - // Don't restart the queue if the writer doesn't need it - - assert(!settings.noOutput); - assert(!settings.tsGeneratorsOnly); - - if (!pNbYearsReallyPerformed) - { - logs.info(); - logs.info() << "The writing of the output results is disabled."; - logs.info(); - } - else - { - if (synthesis) - { - const auto& parameters = study.parameters; - if (not parameters.synthesis) // disabled by parameters - { - logs.info() << "The simulation synthesis is disabled."; - return; - } - } - - // The target folder - String newPath; - newPath << ImplementationType::Name() << IO::Separator; - if (synthesis) - newPath << "mc-all"; - else - { - CString<10, false> tmp; - tmp = (year + 1); - newPath << "mc-ind" << IO::Separator << "00000"; - newPath.overwriteRight(tmp); - } - - // Dumping - ImplementationType::variables.exportSurveyResults( - synthesis, newPath, numSpace, pResultWriter); - } -} - -template -void ISimulation::regenerateTimeSeries(uint year) -{ - // A preprocessor can be launched for several reasons: - // * The option "Preprocessor" is checked in the interface _and_ year == 0 - // * Both options "Preprocessor" and "Refresh" are checked in the interface - // _and_ the refresh must be done for the given year (always done for the first year). - using namespace Solver::TSGenerator; - // Load - if (pData.haveToRefreshTSLoad && (year % pData.refreshIntervalLoad == 0)) - { - Benchmarking::Timer timer; - GenerateTimeSeries(study, year, pResultWriter); - timer.stop(); - pDurationCollector.addDuration("tsgen_load", timer.get_duration()); - } - // Solar - if (pData.haveToRefreshTSSolar && (year % pData.refreshIntervalSolar == 0)) - { - Benchmarking::Timer timer; - GenerateTimeSeries(study, year, pResultWriter); - timer.stop(); - pDurationCollector.addDuration("tsgen_solar", timer.get_duration()); - } - // Wind - if (pData.haveToRefreshTSWind && (year % pData.refreshIntervalWind == 0)) - { - Benchmarking::Timer timer; - GenerateTimeSeries(study, year, pResultWriter); - timer.stop(); - pDurationCollector.addDuration("tsgen_wind", timer.get_duration()); - } - // Hydro - if (pData.haveToRefreshTSHydro && (year % pData.refreshIntervalHydro == 0)) - { - Benchmarking::Timer timer; - GenerateTimeSeries(study, year, pResultWriter); - timer.stop(); - pDurationCollector.addDuration("tsgen_hydro", timer.get_duration()); - } - // Thermal - const bool refreshTSonCurrentYear = (year % pData.refreshIntervalThermal == 0); - { - Benchmarking::Timer timer; - GenerateThermalTimeSeries( - study, year, pData.haveToRefreshTSThermal, refreshTSonCurrentYear, pResultWriter); - timer.stop(); - pDurationCollector.addDuration("tsgen_thermal", timer.get_duration()); - } -} - -template -uint ISimulation::buildSetsOfParallelYears( - uint firstYear, - uint endYear, - std::vector& setsOfParallelYears) -{ - // Filter on the years - const auto& yearsFilter = study.parameters.yearsFilter; - - // number max of years (to be executed or not) in a set of parallel years - uint maxNbYearsPerformed = 0; - - setOfParallelYears* set = nullptr; - bool buildNewSet = true; - bool foundFirstPerformedYearOfCurrentSet = false; - - // Gets information on each parallel years set - for (uint y = firstYear; y < endYear; ++y) - { - unsigned int indexSpace = 999999; - bool performCalculations = yearsFilter[y]; - - // Do we refresh just before this year ? If yes a new set of parallel years has to be - // created - bool refreshing = false; - refreshing = pData.haveToRefreshTSLoad && (y % pData.refreshIntervalLoad == 0); - refreshing - = refreshing || (pData.haveToRefreshTSSolar && (y % pData.refreshIntervalSolar == 0)); - refreshing - = refreshing || (pData.haveToRefreshTSWind && (y % pData.refreshIntervalWind == 0)); - refreshing - = refreshing || (pData.haveToRefreshTSHydro && (y % pData.refreshIntervalHydro == 0)); - - // Some thermal clusters may override the global parameter. - // Therefore, we may want to refresh TS even if pData.haveToRefreshTSThermal == false - bool haveToRefreshTSThermal - = pData.haveToRefreshTSThermal || study.runtime->thermalTSRefresh; - refreshing - = refreshing || (haveToRefreshTSThermal && (y % pData.refreshIntervalThermal == 0)); - - // We build a new set of parallel years if one of these conditions is fulfilled : - // - We have to refresh (or regenerate) some or all time series before running the - // current year - // - This is the first year (to be executed or not) after the previous set is full with - // years to be executed. That is : in the previous set filled, the max number of - // years to be actually run is reached. - buildNewSet = buildNewSet || refreshing; - - if (buildNewSet) - { - setOfParallelYears setToCreate; - setsOfParallelYears.push_back(setToCreate); - set = &(setsOfParallelYears.back()); - - // Initializations - set->nbPerformedYears = 0; - set->nbYears = 0; - set->regenerateTS = false; - set->yearForTSgeneration = 999999; - - // In case we have to regenerate times series before run the current set of parallel - // years - if (refreshing) - { - set->regenerateTS = true; - set->yearForTSgeneration = y; - } - } - - set->yearsIndices.push_back(y); - set->nbYears++; - set->yearFailed[y] = true; - set->isFirstPerformedYearOfASet[y] = false; - - if (performCalculations) - { - // Another year performed - ++pNbYearsReallyPerformed; - - // Number of actually performed years in the current set (up to now). - set->nbPerformedYears++; - // Index of the MC year's space (useful if this year is actually run) - indexSpace = set->nbPerformedYears - 1; - - set->isYearPerformed[y] = true; - set->performedYearToSpace[y] = indexSpace; - set->spaceToPerformedYear[indexSpace] = y; - - if (!foundFirstPerformedYearOfCurrentSet) - { - set->isFirstPerformedYearOfASet[y] = true; - foundFirstPerformedYearOfCurrentSet = true; - } - } - else - { - set->isYearPerformed[y] = false; - } - - // Do we build a new set at next iteration (for years to be executed or not) ? - if (indexSpace == pNbMaxPerformedYearsInParallel - 1 || y == endYear - 1) - { - buildNewSet = true; - foundFirstPerformedYearOfCurrentSet = false; - if (set->nbPerformedYears > maxNbYearsPerformed) - maxNbYearsPerformed = set->nbPerformedYears; - } - else - buildNewSet = false; - - } // End of loop over years - - return maxNbYearsPerformed; -} - -template -void ISimulation::allocateMemoryForRandomNumbers(randomNumbers& randomForParallelYears) -{ - uint maxNbPerformedYears = randomForParallelYears.pMaxNbPerformedYears; - uint nbAreas = study.areas.size(); - - for (uint y = 0; y < maxNbPerformedYears; y++) - { - // General : - randomForParallelYears.pYears[y].setNbAreas(nbAreas); - randomForParallelYears.pYears[y].pNbClustersByArea = new size_t[nbAreas]; - - // Thermal noises : - randomForParallelYears.pYears[y].pThermalNoisesByArea = new double*[nbAreas]; - - for (uint a = 0; a != nbAreas; ++a) - { - // logs.info() << " area : " << a << " :"; - auto& area = *(study.areas.byIndex[a]); - size_t nbClusters = area.thermal.list.mapping.size(); - randomForParallelYears.pYears[y].pThermalNoisesByArea[a] = new double[nbClusters]; - randomForParallelYears.pYears[y].pNbClustersByArea[a] = nbClusters; - } - - // Reservoir levels - randomForParallelYears.pYears[y].pReservoirLevels = new double[nbAreas]; - - // Noises on unsupplied and spilled energy - randomForParallelYears.pYears[y].pUnsuppliedEnergy = new double[nbAreas]; - randomForParallelYears.pYears[y].pSpilledEnergy = new double[nbAreas]; - - // Hydro costs noises - switch (study.parameters.power.fluctuations) - { - case Data::lssFreeModulations: - { - randomForParallelYears.pYears[y].pHydroCostsByArea_freeMod = new double*[nbAreas]; - for (uint a = 0; a != nbAreas; ++a) - randomForParallelYears.pYears[y].pHydroCostsByArea_freeMod[a] = new double[8784]; - break; - } - case Data::lssMinimizeRamping: - case Data::lssMinimizeExcursions: - { - randomForParallelYears.pYears[y].pHydroCosts_rampingOrExcursion = new double[nbAreas]; - break; - } - case Data::lssUnknown: - { - logs.error() << "Power fluctuation unknown"; - break; - } - } - } // End loop over years -} - -template -void ISimulation::computeRandomNumbers(randomNumbers& randomForYears, - std::vector& years, - std::map& isYearPerformed) -{ - auto& runtime = *study.runtime; - - uint indexYear = 0; - std::vector::iterator ity; - for (ity = years.begin(); ity != years.end(); ++ity) - { - uint y = *ity; - bool isPerformed = isYearPerformed[y]; - if (isPerformed) - randomForYears.yearNumberToIndex[y] = indexYear; - - // General - const unsigned int nbAreas = study.areas.size(); - - // ... Thermal noise ... - for (unsigned int a = 0; a != nbAreas; ++a) - { - // logs.info() << " area : " << a << " :"; - auto& area = *(study.areas.byIndex[a]); - - auto end = area.thermal.list.mapping.end(); - for (auto it = area.thermal.list.mapping.begin(); it != end; ++it) - { - uint clusterIndex = it->second->areaWideIndex; - double thermalNoise = runtime.random[Data::seedThermalCosts].next(); - if (isPerformed) - randomForYears.pYears[indexYear].pThermalNoisesByArea[a][clusterIndex] = thermalNoise; - } - } - - // ... Reservoir levels ... - uint areaIndex = 0; - study.areas.each([&](Data::Area& area) { - // looking for the initial reservoir level (begining of the year) - auto& min = area.hydro.reservoirLevel[Data::PartHydro::minimum]; - auto& avg = area.hydro.reservoirLevel[Data::PartHydro::average]; - auto& max = area.hydro.reservoirLevel[Data::PartHydro::maximum]; - - // Month the reservoir level is initialized according to. - // This month number is given in the civil calendar, from january to december (0 is - // january). - int initResLevelOnMonth = area.hydro.initializeReservoirLevelDate; - - // Conversion of the previous month into simulation calendar - int initResLevelOnSimMonth = study.calendar.mapping.months[initResLevelOnMonth]; - - // Previous month's first day in the year - int firstDayOfMonth = study.calendar.months[initResLevelOnSimMonth].daysYear.first; - - double randomLevel = hydroManagement.randomReservoirLevel(min[firstDayOfMonth], - avg[firstDayOfMonth], - max[firstDayOfMonth]); - - // Possibly update the intial level from scenario builder - if (study.parameters.useCustomScenario) - { - double levelFromScenarioBuilder = study.scenarioHydroLevels[areaIndex][y]; - if (levelFromScenarioBuilder >= 0.) - randomLevel = levelFromScenarioBuilder; - } - - if (pHydroHotStart) - { - if (!isPerformed || !area.hydro.reservoirManagement) - { - // This initial level should be unused, so -1, as impossible value, is suitable. - randomForYears.pYears[indexYear].pReservoirLevels[areaIndex] = -1.; - areaIndex++; - return; // Skipping the current area - } - - if (!pFirstSetParallelWithAPerformedYearWasRun) - randomForYears.pYears[indexYear].pReservoirLevels[areaIndex] = randomLevel; - // Else : means the start levels (multiple areas are affected) of a year are - // retrieved from a previous year and - // these levels are updated inside the year job (see year job). - } - else - { - // Current area's hydro starting (or initial) level computation - // (no matter if the year is performed or not, we always draw a random initial - // reservoir level to ensure the same results) - if (isPerformed) - randomForYears.pYears[indexYear].pReservoirLevels[areaIndex] = randomLevel; - } - - areaIndex++; - }); // each area - - // ... Unsupplied and spilled energy costs noises (french : bruits sur la defaillance - // positive et negatives) ... references to the random number generators - auto& randomUnsupplied = study.runtime->random[Data::seedUnsuppliedEnergyCosts]; - auto& randomSpilled = study.runtime->random[Data::seedSpilledEnergyCosts]; - - int currentSpilledEnergySeed = study.parameters.seed[Data::seedSpilledEnergyCosts]; - int defaultSpilledEnergySeed = Data::antaresSeedDefaultValue - + Data::seedSpilledEnergyCosts * Data::antaresSeedIncrement; - bool SpilledEnergySeedIsDefault = (currentSpilledEnergySeed == defaultSpilledEnergySeed); - areaIndex = 0; - study.areas.each([&](Data::Area& area) { - (void)area; // Avoiding warnings at compilation (unused variable) on linux - if (isPerformed) - { - double randomNumber = randomUnsupplied(); - randomForYears.pYears[indexYear].pUnsuppliedEnergy[areaIndex] = randomNumber; - randomForYears.pYears[indexYear].pSpilledEnergy[areaIndex] = randomNumber; - if (!SpilledEnergySeedIsDefault) - randomForYears.pYears[indexYear].pSpilledEnergy[areaIndex] = randomSpilled(); - } - else - { - randomUnsupplied(); - if (!SpilledEnergySeedIsDefault) - randomSpilled(); - } - - areaIndex++; - }); // each area - - // ... Hydro costs noises ... - auto& randomHydro = study.runtime->random[Data::seedHydroCosts]; - - Data::PowerFluctuations powerFluctuations = study.parameters.power.fluctuations; - switch (powerFluctuations) - { - case Data::lssFreeModulations: - { - areaIndex = 0; - auto end = study.areas.end(); - - // Computing hourly hydro costs noises so that they are homogeneously spread into : - // [-1.e-3, -5*1.e-4] U [+5*1.e-4, +1.e-3] - if (isPerformed) - { - for (auto i = study.areas.begin(); i != end; ++i) - { - double* noise - = randomForYears.pYears[indexYear].pHydroCostsByArea_freeMod[areaIndex]; - std::set setHydroCostsNoises; - for (uint j = 0; j != 8784; ++j) - { - noise[j] = randomHydro(); - noise[j] -= 0.5; // Now we have : -0.5 < noise[j] < +0.5 - - // This std::set naturally sorts the hydro costs noises into increasing - // absolute values order - setHydroCostsNoises.insert(hydroCostNoise(noise[j], j)); - } - - uint rank = 0; - std::set::iterator it; - for (it = setHydroCostsNoises.begin(); it != setHydroCostsNoises.end(); it++) - { - uint index = it->getIndex(); - double value = it->getValue(); - - if (value < 0.) - noise[index] = -5 * 1.e-4 * (1 + rank / 8784.); - else - noise[index] = 5 * 1.e-4 * (1 + rank / 8784.); - - rank++; - } - - areaIndex++; - } - } - else - for (auto i = study.areas.begin(); i != end; ++i) - for (uint j = 0; j != 8784; ++j) - randomHydro(); - - break; - } - - case Data::lssMinimizeRamping: - case Data::lssMinimizeExcursions: - { - areaIndex = 0; - auto end = study.areas.end(); - for (auto i = study.areas.begin(); i != end; ++i) - { - if (isPerformed) - randomForYears.pYears[indexYear].pHydroCosts_rampingOrExcursion[areaIndex] - = randomHydro(); - else - randomHydro(); - - areaIndex++; - } - break; - } - - case Data::lssUnknown: - { - logs.error() << "Power fluctuation unknown"; - break; - } - - } // end of switch - - if (isPerformed) - indexYear++; - - } // End loop over years -} // End function - -template -void ISimulation::computeAnnualCostsStatistics( - std::vector& state, - std::vector::iterator& set_it) -{ - // Loop over years contained in the set - std::vector::iterator year_it; - for (year_it = set_it->yearsIndices.begin(); year_it != set_it->yearsIndices.end(); ++year_it) - { - // Get the index of the year - unsigned int y = *year_it; - if (set_it->isYearPerformed[y]) - { - // Get space number associated to the performed year - uint numSpace = set_it->performedYearToSpace[y]; - pAnnualCostsStatistics.systemCost.addCost(state[numSpace].annualSystemCost); - pAnnualCostsStatistics.criterionCost1.addCost(state[numSpace].optimalSolutionCost1); - pAnnualCostsStatistics.criterionCost2.addCost(state[numSpace].optimalSolutionCost2); - pAnnualCostsStatistics.optimizationTime1.addCost( - state[numSpace].averageOptimizationTime1); - pAnnualCostsStatistics.optimizationTime2.addCost( - state[numSpace].averageOptimizationTime2); - } - } -} - -static void logPerformedYearsInAset(setOfParallelYears& set) -{ - logs.info() << "parallel batch size : " << set.nbYears << " (" << set.nbPerformedYears - << " perfomed)"; - - std::string performedYearsToLog = ""; - std::for_each(std::begin(set.yearsIndices), std::end(set.yearsIndices), [&](uint const& y) { - if (set.isYearPerformed[y]) - performedYearsToLog += std::to_string(y + 1) + " "; - }); - - logs.info() << "Year(s) " << performedYearsToLog; -} - -template -void ISimulation::loopThroughYears(uint firstYear, - uint endYear, - std::vector& state) -{ - assert(endYear <= study.parameters.nbYears); - - // List of parallel years sets - std::vector setsOfParallelYears; - - // Gets information on each set of parallel years and returns the max number of years performed - // in a set The variable "maxNbYearsPerformedInAset" is the maximum numbers of years to be - // actually executed in a set. A set contains some years to be actually executed (at most - // "pNbMaxPerformedYearsInParallel" years) and some others to skip. - uint maxNbYearsPerformedInAset - = buildSetsOfParallelYears(firstYear, endYear, setsOfParallelYears); - // Related to annual costs statistics (printed in output into separate files) - pAnnualCostsStatistics.setNbPerformedYears(pNbYearsReallyPerformed); - - // Container for random numbers of parallel years (to be executed or not) - randomNumbers randomForParallelYears(maxNbYearsPerformedInAset, - study.parameters.power.fluctuations); - - // Allocating memory to store random numbers of all parallel years - allocateMemoryForRandomNumbers(randomForParallelYears); - - // Number of threads to perform the jobs waiting in the queue - pQueueService->maximumThreadCount(pNbMaxPerformedYearsInParallel); - - // Loop over sets of parallel years - std::vector::iterator set_it; - for (set_it = setsOfParallelYears.begin(); set_it != setsOfParallelYears.end(); ++set_it) - { - // 1 - We may want to regenerate the time-series this year. - // This is the case when the preprocessors are enabled from the - // interface and/or the refresh is enabled. - if (set_it->regenerateTS) - regenerateTimeSeries(set_it->yearForTSgeneration); - - computeRandomNumbers(randomForParallelYears, set_it->yearsIndices, set_it->isYearPerformed); - - std::vector::iterator year_it; - - bool yearPerformed = false; - Concurrency::FutureSet results; - for (year_it = set_it->yearsIndices.begin(); year_it != set_it->yearsIndices.end(); - ++year_it) - { - // Get the index of the year - unsigned int y = *year_it; - - bool performCalculations = set_it->isYearPerformed[y]; - unsigned int numSpace = 999999; - if (performCalculations) - { - yearPerformed = true; - numSpace = set_it->performedYearToSpace[y]; - } - - // If the year has not to be rerun, we skip the computation of the year. - // Note that, when we enter for the first time in the "for" loop, all years of the set - // have to be rerun (meaning : they must be run once). if(!set_it->yearFailed[y]) - // continue; - - Concurrency::Task task = yearJob(this, - y, - set_it->yearFailed, - set_it->isFirstPerformedYearOfASet, - pFirstSetParallelWithAPerformedYearWasRun, - numSpace, - randomForParallelYears, - performCalculations, - study, - state, - pYearByYear, - pDurationCollector, - pResultWriter); - results.add(Concurrency::AddTask(*pQueueService, task)); - } // End loop over years of the current set of parallel years - - logPerformedYearsInAset(*set_it); - - pQueueService->start(); - - pQueueService->wait(Yuni::qseIdle); - pQueueService->stop(); - results.join(); - pResultWriter.flush(); - - // At this point, the first set of parallel year(s) was run with at least one year performed - if (!pFirstSetParallelWithAPerformedYearWasRun && yearPerformed) - pFirstSetParallelWithAPerformedYearWasRun = true; - - // On regarde si au moins une année du lot n'a pas trouvé de solution - for (auto& [year, failed] : set_it->yearFailed) - { - // Si une année du lot d'années n'a pas trouvé de solution, on arrête tout - if (failed) - { - std::ostringstream msg; - msg << "Year " << year + 1 << " has failed in the previous set of parallel year."; - throw FatalError(msg.str()); - } - } - // Computing the summary : adding the contribution of MC years - // previously computed in parallel - ImplementationType::variables.computeSummary(set_it->spaceToPerformedYear, - set_it->nbPerformedYears); - - // Computing summary of spatial aggregations - ImplementationType::variables.computeSpatialAggregatesSummary( - ImplementationType::variables, set_it->spaceToPerformedYear, set_it->nbPerformedYears); - - // Computes statistics on annual (system and solution) costs, to be printed in output into - // separate files - computeAnnualCostsStatistics(state, set_it); - - // Set to zero the random numbers of all parallel years - randomForParallelYears.reset(); - - } // End loop over sets of parallel years - - // Writing annual costs statistics - pAnnualCostsStatistics.endStandardDeviations(); - pAnnualCostsStatistics.writeToOutput(pResultWriter); -} - -} // namespace Antares::Solver::Simulation - -#endif // __SOLVER_SIMULATION_SOLVER_HXX__ diff --git a/src/solver/simulation/solver.utils.h b/src/solver/simulation/solver.utils.h deleted file mode 100644 index a581f04dbf..0000000000 --- a/src/solver/simulation/solver.utils.h +++ /dev/null @@ -1,436 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_SOLVER_UTILS_H__ -#define __SOLVER_SIMULATION_SOLVER_UTILS_H__ - -#include -#include // For std namespace -#include // For std numeric_limits -#include // For ostringstream -#include // For setprecision -// #include -#include - -#include - -#define SEP Yuni::IO::Separator - -namespace Antares::Solver::Simulation -{ -struct setOfParallelYears -{ - // Un lot d'année à exécuter en parallèle. - // En fonction d'une éventuelle play-list, certaines seront jouées et d'autres non. - -public: - // Numeros des annees en parallele pour ce lot (certaines ne seront pas jouées en cas de - // play-list "trouée") - std::vector yearsIndices; - - // Une annee doit-elle être rejouée ? - std::map yearFailed; - - // Associe le numero d'une année jouée à l'indice de l'espace - std::map performedYearToSpace; - - // L'inverse : pour une année jouée, associe l'indice de l'espace au numero de l'année - std::map spaceToPerformedYear; - - // Pour chaque année, est-elle la première à devoir être jouée dans son lot d'années ? - std::map isFirstPerformedYearOfASet; - - // Pour chaque année du lot, est-elle jouée ou non ? - std::map isYearPerformed; - - // Nbre d'années en parallele vraiment jouées pour ce lot - unsigned int nbPerformedYears; - - // Nbre d'années en parallele jouées ou non pour ce lot - unsigned int nbYears; - - // Regenere-t-on des times series avant de jouer les annees du lot courant - bool regenerateTS; - - // Annee a passer a la fonction "regenerateTimeSeries(y)" (si regenerateTS is "true") - unsigned int yearForTSgeneration; -}; - -class costStatistics -{ -public: - costStatistics() : - costAverage(0.), - costStdDeviation(0.), - costMin(std::numeric_limits::max()), - costMax(0.), - nbPerformedYears(0) - { - } - - void setNbPerformedYears(uint n) - { - assert(n); - nbPerformedYears = n; - } - - void addCost(const double cost) - { - // Average - costAverage += cost / nbPerformedYears; - - // Standard deviation - costStdDeviation += cost * cost / nbPerformedYears; - - // Min and Max - if (cost < costMin) - costMin = cost; - if (cost > costMax) - costMax = cost; - } - - void endStandardDeviation() - { - costStdDeviation = Yuni::Math::SquareRoot(costStdDeviation - costAverage * costAverage); - } - -public: - // System costs statistics - double costAverage; - double costStdDeviation; - double costMin; - double costMax; - -private: - // Total number of performed years in the study - uint nbPerformedYears; -}; - -class annualCostsStatistics -{ -public: - annualCostsStatistics() : - systemCostFilename("annualSystemCost.txt"), - criterionsCostsFilename("checkIntegrity.txt"), - optimizationTimeFilename("timeStatistics.txt") - { - } - - void setNbPerformedYears(uint n) - { - systemCost.setNbPerformedYears(n); - criterionCost1.setNbPerformedYears(n); - criterionCost2.setNbPerformedYears(n); - optimizationTime1.setNbPerformedYears(n); - optimizationTime2.setNbPerformedYears(n); - }; - - void endStandardDeviations() - { - systemCost.endStandardDeviation(); - criterionCost1.endStandardDeviation(); - criterionCost2.endStandardDeviation(); - optimizationTime1.endStandardDeviation(); - optimizationTime2.endStandardDeviation(); - }; - - void writeToOutput(IResultWriter& writer) - { - writeSystemCostToOutput(writer); - writeCriterionCostsToOutput(writer); - writeOptimizationTimeToOutput(writer); - } - - std::string to_scientific(const double d) - { - std::ostringstream stream; - stream << std::scientific; - stream << std::setprecision(14); - stream << d; - - return stream.str(); - } - - std::string round_to_closer_int(const double d) - { -#ifdef YUNI_OS_MSVC - ::sprintf_s(conversionBuffer, sizeof(conversionBuffer), "%.0f", d); -#else - ::snprintf(conversionBuffer, sizeof(conversionBuffer), "%.0f", d); -#endif - std::string rnd(conversionBuffer); - return rnd; - } - -private: - void writeSystemCostToOutput(IResultWriter& writer) - { - Yuni::Clob buffer; - buffer << "EXP : " << round_to_closer_int(systemCost.costAverage) << "\n"; - buffer << "STD : " << round_to_closer_int(systemCost.costStdDeviation) << "\n"; - buffer << "MIN : " << round_to_closer_int(systemCost.costMin) << "\n"; - buffer << "MAX : " << round_to_closer_int(systemCost.costMax) << "\n"; - - writer.addEntryFromBuffer(systemCostFilename, buffer); - } - - void writeCriterionCostsToOutput(IResultWriter& writer) - { - Yuni::Clob buffer; - buffer << to_scientific(criterionCost1.costAverage) << "\n"; - buffer << to_scientific(criterionCost1.costStdDeviation) << "\n"; - buffer << to_scientific(criterionCost1.costMin) << "\n"; - buffer << to_scientific(criterionCost1.costMax) << "\n"; - - buffer << to_scientific(criterionCost2.costAverage) << "\n"; - buffer << to_scientific(criterionCost2.costStdDeviation) << "\n"; - buffer << to_scientific(criterionCost2.costMin) << "\n"; - buffer << to_scientific(criterionCost2.costMax) << "\n"; - - writer.addEntryFromBuffer(criterionsCostsFilename, buffer); - } - - void writeOptimizationTimeToOutput(IResultWriter& writer) - { - Yuni::Clob buffer; - buffer << "First optimization :\n"; - buffer << "EXP (ms) : " << optimizationTime1.costAverage << "\n"; - buffer << "STD (ms) : " << optimizationTime1.costStdDeviation << "\n"; - buffer << "MIN (ms) : " << optimizationTime1.costMin << "\n"; - buffer << "MAX (ms) : " << optimizationTime1.costMax << "\n"; - - buffer << "Second optimization :\n"; - buffer << "EXP (ms) : " << optimizationTime2.costAverage << "\n"; - buffer << "STD (ms) : " << optimizationTime2.costStdDeviation << "\n"; - buffer << "MIN (ms) : " << optimizationTime2.costMin << "\n"; - buffer << "MAX (ms) : " << optimizationTime2.costMax << "\n"; - - writer.addEntryFromBuffer(optimizationTimeFilename, buffer); - } - -public: - // Costs - costStatistics systemCost; - costStatistics criterionCost1; - costStatistics criterionCost2; - costStatistics optimizationTime1; - costStatistics optimizationTime2; - -private: - const std::string systemCostFilename; - const std::string criterionsCostsFilename; - const std::string optimizationTimeFilename; - char conversionBuffer[256]; // Used to round a double to the closer integer -}; - -class yearRandomNumbers -{ -public: - yearRandomNumbers() - { - pThermalNoisesByArea = nullptr; - pNbClustersByArea = nullptr; - pNbAreas = 0; - } - - ~yearRandomNumbers() - { - // General - delete[] pNbClustersByArea; - - // Thermal noises - for (uint a = 0; a != pNbAreas; a++) - delete[] pThermalNoisesByArea[a]; - delete[] pThermalNoisesByArea; - - // Reservoir levels, spilled and unsupplied energy - delete[] pReservoirLevels; - delete[] pUnsuppliedEnergy; - delete[] pSpilledEnergy; - - // Hydro costs noises - switch (pPowerFluctuations) - { - case Data::lssFreeModulations: - { - for (uint a = 0; a != pNbAreas; a++) - delete[] pHydroCostsByArea_freeMod[a]; - delete[] pHydroCostsByArea_freeMod; - break; - } - - case Data::lssMinimizeRamping: - case Data::lssMinimizeExcursions: - { - delete[] pHydroCosts_rampingOrExcursion; - break; - } - - case Data::lssUnknown: - break; - } - } - - void setNbAreas(uint nbAreas) - { - pNbAreas = nbAreas; - } - - void setPowerFluctuations(Data::PowerFluctuations powerFluctuations) - { - pPowerFluctuations = powerFluctuations; - } - - void reset() - { - // General - memset(pNbClustersByArea, 0, pNbAreas * sizeof(size_t)); - - // Thermal noises - for (uint a = 0; a != pNbAreas; a++) - memset(pThermalNoisesByArea[a], 0, pNbClustersByArea[a] * sizeof(double)); - - // Reservoir levels, spilled and unsupplied energy costs - memset(pReservoirLevels, 0, pNbAreas * sizeof(double)); - memset(pUnsuppliedEnergy, 0, pNbAreas * sizeof(double)); - memset(pSpilledEnergy, 0, pNbAreas * sizeof(double)); - - // Hydro costs noises - switch (pPowerFluctuations) - { - case Data::lssFreeModulations: - { - for (uint a = 0; a != pNbAreas; a++) - memset(pHydroCostsByArea_freeMod[a], 0, 8784 * sizeof(double)); - break; - } - - case Data::lssMinimizeRamping: - case Data::lssMinimizeExcursions: - { - memset(pHydroCosts_rampingOrExcursion, 0, pNbAreas * sizeof(double)); - break; - } - - case Data::lssUnknown: - break; - } - } - -public: - // General data - uint pNbAreas; - Data::PowerFluctuations pPowerFluctuations; - - // Data for thermal noises - double** pThermalNoisesByArea; - size_t* pNbClustersByArea; - - // Data for reservoir levels - double* pReservoirLevels; - - // Data for unsupplied and spilled energy costs - double* pUnsuppliedEnergy; - double* pSpilledEnergy; - - // Hydro costs noises - double** pHydroCostsByArea_freeMod; - double* pHydroCosts_rampingOrExcursion; -}; - -class randomNumbers -{ -public: - randomNumbers(uint maxNbPerformedYearsInAset, Data::PowerFluctuations powerFluctuations) : - pMaxNbPerformedYears(maxNbPerformedYearsInAset) - { - // Allocate a table of parallel years structures - pYears = new yearRandomNumbers[maxNbPerformedYearsInAset]; - - // Tells these structures their power fluctuations mode - for (uint y = 0; y < maxNbPerformedYearsInAset; ++y) - pYears[y].setPowerFluctuations(powerFluctuations); - } - - ~randomNumbers() - { - delete[] pYears; - } - - void reset() - { - for (uint i = 0; i < pMaxNbPerformedYears; i++) - pYears[i].reset(); - - yearNumberToIndex.clear(); - } - -public: - uint pMaxNbPerformedYears; - yearRandomNumbers* pYears; - - // Associates : - // year number (0, ..., total nb of years to compute - 1) --> index of the year's space - //(0, - //..., max nb of parallel years - 1) - std::map yearNumberToIndex; -}; - -// Class representing a hydro cost noise. -// This class allows sorting hydro costs noises into increasing absolute values order -// when instances are contained in a : -// std::set -class hydroCostNoise -{ -public: - hydroCostNoise(double v, uint i) : value(v), index(i) - { - } - inline double getValue() const - { - return value; - } - inline uint getIndex() const - { - return index; - } - -private: - double value; - uint index; -}; - -// Used to sort the hydro costs noises into increasing absolute values order in a std::set -struct compareHydroCostsNoises -{ - inline bool operator()(const hydroCostNoise& hcnr1, const hydroCostNoise& hcnr2) const - { - return (std::abs(hcnr1.getValue()) < std::abs(hcnr2.getValue())) ? true : false; - } -}; -} // namespace Antares::Solver::Simulation - -#endif // __SOLVER_SIMULATION_SOLVER_H__ diff --git a/src/solver/simulation/solver_utils.cpp b/src/solver/simulation/solver_utils.cpp new file mode 100644 index 0000000000..936957a224 --- /dev/null +++ b/src/solver/simulation/solver_utils.cpp @@ -0,0 +1,171 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/simulation/solver_utils.h" + +#include +#include +#include +#include +#include + +#include +#include + +#define SEP Yuni::IO::Separator + +static const std::string systemCostFilename = "annualSystemCost.txt"; +static const std::string criterionsCostsFilename = "checkIntegrity.txt"; +static const std::string optimizationTimeFilename = std::string("optimization") + SEP + + "solve-durations.txt"; +static const std::string updateTimeFilename = std::string("optimization") + SEP + + "update-durations.txt"; + +static std::ostream& toScientific(std::ostream& os) +{ + return os << std::scientific << std::setprecision(14); +} + +namespace Antares::Solver::Simulation +{ + +void costStatistics::setNbPerformedYears(uint n) +{ + assert(n); + nbPerformedYears = n; +} + +void costStatistics::addCost(const double cost) +{ + // Average + costAverage += cost / nbPerformedYears; + + // Standard deviation + costStdDeviation += cost * cost / nbPerformedYears; + + // Min and Max + if (cost < costMin) + { + costMin = cost; + } + if (cost > costMax) + { + costMax = cost; + } +} + +void costStatistics::endStandardDeviation() +{ + costStdDeviation = std::sqrt(costStdDeviation - costAverage * costAverage); +} + +// annualCostsStatistics +annualCostsStatistics::annualCostsStatistics() = default; + +void annualCostsStatistics::setNbPerformedYears(uint n) +{ + systemCost.setNbPerformedYears(n); + criterionCost1.setNbPerformedYears(n); + criterionCost2.setNbPerformedYears(n); + optimizationTime1.setNbPerformedYears(n); + optimizationTime2.setNbPerformedYears(n); + updateTime.setNbPerformedYears(n); +} + +void annualCostsStatistics::endStandardDeviations() +{ + systemCost.endStandardDeviation(); + criterionCost1.endStandardDeviation(); + criterionCost2.endStandardDeviation(); + optimizationTime1.endStandardDeviation(); + optimizationTime2.endStandardDeviation(); + updateTime.endStandardDeviation(); +} + +void annualCostsStatistics::writeToOutput(IResultWriter& writer) +{ + writeSystemCostToOutput(writer); + writeCriterionCostsToOutput(writer); + writeOptimizationTimeToOutput(writer); + writeUpdateTimes(writer); +} + +void annualCostsStatistics::writeSystemCostToOutput(IResultWriter& writer) +{ + std::ostringstream buffer; + buffer << "EXP : " << std::round(systemCost.costAverage) << '\n'; + buffer << "STD : " << std::round(systemCost.costStdDeviation) << '\n'; + buffer << "MIN : " << std::round(systemCost.costMin) << '\n'; + buffer << "MAX : " << std::round(systemCost.costMax) << '\n'; + + std::string s = buffer.str(); + writer.addEntryFromBuffer(systemCostFilename, s); +} + +void annualCostsStatistics::writeCriterionCostsToOutput(IResultWriter& writer) const +{ + using std::endl; + std::ostringstream buffer; + buffer << toScientific << criterionCost1.costAverage << endl + << criterionCost1.costStdDeviation << endl + << criterionCost1.costMin << endl + << criterionCost1.costMax << endl + << criterionCost2.costAverage << endl + << criterionCost2.costStdDeviation << endl + << criterionCost2.costMin << endl + << criterionCost2.costMax << endl; + + std::string s = buffer.str(); // TODO allow std::string&& in addEntryFromBuffer + writer.addEntryFromBuffer(criterionsCostsFilename, s); +} + +void annualCostsStatistics::writeUpdateTimes(IResultWriter& writer) const +{ + std::ostringstream buffer; + buffer << "EXP (ms) : " << updateTime.costAverage << "\n"; + buffer << "STD (ms) : " << updateTime.costStdDeviation << "\n"; + buffer << "MIN (ms) : " << updateTime.costMin << "\n"; + buffer << "MAX (ms) : " << updateTime.costMax << "\n"; + + std::string s = buffer.str(); + writer.addEntryFromBuffer(updateTimeFilename, s); +} + +void annualCostsStatistics::writeOptimizationTimeToOutput(IResultWriter& writer) const +{ + std::ostringstream buffer; + buffer << "First optimization :\n"; + buffer << "EXP (ms) : " << optimizationTime1.costAverage << "\n"; + buffer << "STD (ms) : " << optimizationTime1.costStdDeviation << "\n"; + buffer << "MIN (ms) : " << optimizationTime1.costMin << "\n"; + buffer << "MAX (ms) : " << optimizationTime1.costMax << "\n"; + + buffer << "Second optimization :\n"; + buffer << "EXP (ms) : " << optimizationTime2.costAverage << "\n"; + buffer << "STD (ms) : " << optimizationTime2.costStdDeviation << "\n"; + buffer << "MIN (ms) : " << optimizationTime2.costMin << "\n"; + buffer << "MAX (ms) : " << optimizationTime2.costMax << "\n"; + + std::string s = buffer.str(); + writer.addEntryFromBuffer(optimizationTimeFilename, s); +} + +} // namespace Antares::Solver::Simulation diff --git a/src/solver/simulation/timeseries-numbers.cpp b/src/solver/simulation/timeseries-numbers.cpp index ba8b00e5b5..446a0efa08 100644 --- a/src/solver/simulation/timeseries-numbers.cpp +++ b/src/solver/simulation/timeseries-numbers.cpp @@ -1,64 +1,59 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include // std::adjacent_find -#include // std::back_inserter +#include "antares/solver/simulation/timeseries-numbers.h" + +#include // std::adjacent_find +#include +#include #include // std::not_equal_to +#include // std::back_inserter #include #include -#include -#include #include +#include "antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h" +#include "antares/solver/simulation/ITimeSeriesNumbersWriter.h" #include "antares/study/fwd.h" -#include "timeseries-numbers.h" -#include "ITimeSeriesNumbersWriter.h" -#include "BindingConstraintsTimeSeriesNumbersWriter.h" using namespace Yuni; using namespace Antares::Data; using namespace std; const map ts_to_tsIndex = {{timeSeriesLoad, 0}, - {timeSeriesHydro, 1}, - {timeSeriesWind, 2}, - {timeSeriesThermal, 3}, - {timeSeriesSolar, 4}, - {timeSeriesRenewable, 5}, - {timeSeriesTransmissionCapacities, 6}}; - -const map ts_to_tsTitle - = {{timeSeriesLoad, "load"}, - {timeSeriesHydro, "hydro"}, - {timeSeriesWind, "wind"}, - {timeSeriesThermal, "thermal"}, - {timeSeriesSolar, "solar"}, - {timeSeriesRenewable, "renewable clusters"}, - {timeSeriesTransmissionCapacities, "transmission capacities"}}; + {timeSeriesHydro, 1}, + {timeSeriesWind, 2}, + {timeSeriesThermal, 3}, + {timeSeriesSolar, 4}, + {timeSeriesRenewable, 5}, + {timeSeriesTransmissionCapacities, 6}}; + +const map ts_to_tsTitle = {{timeSeriesLoad, "load"}, + {timeSeriesHydro, "hydro"}, + {timeSeriesWind, "wind"}, + {timeSeriesThermal, "thermal"}, + {timeSeriesSolar, "solar"}, + {timeSeriesRenewable, "renewable clusters"}, + {timeSeriesTransmissionCapacities, + "transmission capacities"}}; void addInterModalTimeSeriesToMessage(const array& isTSintermodal, std::string& interModalTsMsg) @@ -71,7 +66,9 @@ void addInterModalTimeSeriesToMessage(const array& isTSin if (isTSintermodal[it->second]) { if (!isFirstLogged) + { interModalTsMsg.append(", "); + } interModalTsMsg.append(ts_to_tsTitle.at(it->first)); isFirstLogged = false; } @@ -86,162 +83,87 @@ static bool GenerateDeratedMode(Study& study) { logs.info() << " :: using the `derated` mode"; if (study.parameters.useCustomScenario) + { logs.warning() << "The derated mode is enabled. The custom building mode will be ignored"; - - study.areas.each([&](Area& area) { - area.load.series->timeseriesNumbers.zero(); - area.solar.series->timeseriesNumbers.zero(); - area.wind.series->timeseriesNumbers.zero(); - area.hydro.series->timeseriesNumbers.zero(); - - for (uint i = 0; i != area.thermal.clusterCount(); ++i) - { - auto& cluster = *(area.thermal.clusters[i]); - cluster.series->timeseriesNumbers.zero(); - } - - for (uint i = 0; i != area.renewable.clusterCount(); ++i) - { - auto& cluster = *(area.renewable.clusters[i]); - cluster.series->timeseriesNumbers.zero(); - } - }); + } return true; } -class areaNumberOfTSretriever +class AreaNumberOfTSretriever { public: - areaNumberOfTSretriever(Study& study) : study_(study) - { - } + virtual ~AreaNumberOfTSretriever() = default; virtual std::vector getAreaTimeSeriesNumber(const Area& area) = 0; - virtual uint getGeneratedTimeSeriesNumber() = 0; - -protected: - Study& study_; }; -class loadAreaNumberOfTSretriever : public areaNumberOfTSretriever +class LoadAreaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - loadAreaNumberOfTSretriever(Study& study) : areaNumberOfTSretriever(study) - { - } - std::vector getAreaTimeSeriesNumber(const Area& area) - { - std::vector to_return = {area.load.series->timeSeries.width}; - return to_return; - } - uint getGeneratedTimeSeriesNumber() + std::vector getAreaTimeSeriesNumber(const Area& area) override { - return study_.parameters.nbTimeSeriesLoad; + return {area.load.series.timeSeries.width}; } }; -class hydroAreaNumberOfTSretriever : public areaNumberOfTSretriever +class HydroAreaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - hydroAreaNumberOfTSretriever(Study& study) : areaNumberOfTSretriever(study) - { - } - std::vector getAreaTimeSeriesNumber(const Area& area) - { - std::vector to_return = {area.hydro.series->count}; - return to_return; - } - uint getGeneratedTimeSeriesNumber() + std::vector getAreaTimeSeriesNumber(const Area& area) override { - return study_.parameters.nbTimeSeriesHydro; + return {area.hydro.series->TScount()}; } }; -class windAreaNumberOfTSretriever : public areaNumberOfTSretriever +class WindAreaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - windAreaNumberOfTSretriever(Study& study) : areaNumberOfTSretriever(study) - { - } - std::vector getAreaTimeSeriesNumber(const Area& area) - { - std::vector to_return = {area.wind.series->timeSeries.width}; - return to_return; - } - uint getGeneratedTimeSeriesNumber() + std::vector getAreaTimeSeriesNumber(const Area& area) override { - return study_.parameters.nbTimeSeriesWind; + return {area.wind.series.timeSeries.width}; } }; -class solarAreaNumberOfTSretriever : public areaNumberOfTSretriever +class SolarAreaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - solarAreaNumberOfTSretriever(Study& study) : areaNumberOfTSretriever(study) - { - } - std::vector getAreaTimeSeriesNumber(const Area& area) - { - std::vector to_return = {area.solar.series->timeSeries.width}; - return to_return; - } - uint getGeneratedTimeSeriesNumber() + std::vector getAreaTimeSeriesNumber(const Area& area) override { - return study_.parameters.nbTimeSeriesSolar; + return {area.solar.series.timeSeries.width}; } }; -class thermalAreaNumberOfTSretriever : public areaNumberOfTSretriever +class ThermalAreaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - thermalAreaNumberOfTSretriever(Study& study) : areaNumberOfTSretriever(study) - { - } - std::vector getAreaTimeSeriesNumber(const Area& area) + std::vector getAreaTimeSeriesNumber(const Area& area) override { std::vector to_return; - uint clusterCount = (uint)area.thermal.clusterCount(); - for (uint i = 0; i != clusterCount; ++i) + for (auto& cluster: area.thermal.list.each_enabled()) { - auto& cluster = *(area.thermal.clusters[i]); - to_return.push_back(cluster.series->timeSeries.width); + to_return.push_back(cluster->series.timeSeries.width); } return to_return; } - uint getGeneratedTimeSeriesNumber() - { - return study_.parameters.nbTimeSeriesThermal; - } }; -class renewClustersAreaNumberOfTSretriever : public areaNumberOfTSretriever +class RenewClustersAreaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - renewClustersAreaNumberOfTSretriever(Study& study) : areaNumberOfTSretriever(study) - { - } - std::vector getAreaTimeSeriesNumber(const Area& area) + std::vector getAreaTimeSeriesNumber(const Area& area) override { std::vector to_return; - uint clusterCount = (uint)area.renewable.clusterCount(); - for (uint i = 0; i != clusterCount; ++i) + for (const auto& cluster: area.renewable.list.each_enabled()) { - auto& cluster = *(area.renewable.clusters[i]); - to_return.push_back(cluster.series->timeSeries.width); + to_return.push_back(cluster->series.timeSeries.width); } return to_return; } - uint getGeneratedTimeSeriesNumber() - { - return 1; - } }; -class areaLinksTransCapaNumberOfTSretriever : public areaNumberOfTSretriever +class AreaLinksTransCapaNumberOfTSretriever: public AreaNumberOfTSretriever { public: - using areaNumberOfTSretriever::areaNumberOfTSretriever; - virtual ~areaLinksTransCapaNumberOfTSretriever() = default; std::vector getAreaTimeSeriesNumber(const Area& area) override { std::vector to_return; @@ -249,64 +171,39 @@ class areaLinksTransCapaNumberOfTSretriever : public areaNumberOfTSretriever for (auto it = area.links.begin(); it != area.links.end(); ++it) { const auto& link = *(it->second); - to_return.push_back(link.directCapacities.width); - to_return.push_back(link.indirectCapacities.width); + to_return.push_back(link.directCapacities.timeSeries.width); } return to_return; } - uint getGeneratedTimeSeriesNumber() override - { - return 1; - } }; class IntraModalConsistencyChecker { public: IntraModalConsistencyChecker(const TimeSeriesType ts, - const array& isTSintramodal, - const array& isTSgenerated, - areaNumberOfTSretriever* tsCounter, - Study& study) : - tsCounter_(tsCounter), study_(study), nbTimeseries_(0) - { - int indexTS = ts_to_tsIndex.at(ts); - isTSintramodal_ = isTSintramodal[indexTS]; - isTSgenerated_ = isTSgenerated[indexTS]; + AreaNumberOfTSretriever* tsCounter, + Study& study): + tsCounter_(tsCounter), + study_(study) + { tsTitle_ = ts_to_tsTitle.at(ts); } + ~IntraModalConsistencyChecker() = default; - bool check(); + bool checkTSconsistency(); + uint getTimeSeriesNumber() { return nbTimeseries_; } private: - bool checkTSconsistency(); - -private: - bool isTSintramodal_; - bool isTSgenerated_; - areaNumberOfTSretriever* tsCounter_; + AreaNumberOfTSretriever* tsCounter_; Study& study_; - uint nbTimeseries_; + uint nbTimeseries_ = 0; string tsTitle_; }; -bool IntraModalConsistencyChecker::check() -{ - if (isTSintramodal_ && not isTSgenerated_) - { - if (not checkTSconsistency()) - return false; - } - else - nbTimeseries_ = tsCounter_->getGeneratedTimeSeriesNumber(); - - return true; -} - bool IntraModalConsistencyChecker::checkTSconsistency() { logs.info() << "Checking intra-modal correlation: " << tsTitle_; @@ -324,60 +221,53 @@ bool IntraModalConsistencyChecker::checkTSconsistency() << "'s numbers of time-series are not equal for all areas"; return false; } + // At this point, all elements are identical or 1 + nbTimeseries_ = *(std::max_element(listNumberTS.begin(), listNumberTS.end())); - auto result = find_if(listNumberTS.begin(), listNumberTS.end(), [](uint x) { return x != 1; }); - if (result == listNumberTS.end()) - { // All elements are equal to 1 or list is empty - nbTimeseries_ = 1; - } - else - { - nbTimeseries_ = *result; - } return true; } bool checkIntraModalConsistency(array& nbTimeseriesByMode, const array& isTSintramodal, - const array& isTSgenerated, Study& study) { // Initialization of a map associating a time-series to an object that retrieves // the number of time series inside an area - using mapTStoRetriever = map>; + using mapTStoRetriever = map>; mapTStoRetriever ts_to_numberOfTSretrievers; - ts_to_numberOfTSretrievers[timeSeriesLoad] = make_shared(study); - ts_to_numberOfTSretrievers[timeSeriesHydro] = make_shared(study); - ts_to_numberOfTSretrievers[timeSeriesWind] = make_shared(study); - ts_to_numberOfTSretrievers[timeSeriesSolar] = make_shared(study); - ts_to_numberOfTSretrievers[timeSeriesThermal] - = make_shared(study); - ts_to_numberOfTSretrievers[timeSeriesRenewable] - = make_shared(study); - ts_to_numberOfTSretrievers[timeSeriesTransmissionCapacities] - = make_shared(study); + ts_to_numberOfTSretrievers[timeSeriesLoad] = make_shared(); + ts_to_numberOfTSretrievers[timeSeriesHydro] = make_shared(); + ts_to_numberOfTSretrievers[timeSeriesWind] = make_shared(); + ts_to_numberOfTSretrievers[timeSeriesSolar] = make_shared(); + ts_to_numberOfTSretrievers[timeSeriesThermal] = make_shared(); + ts_to_numberOfTSretrievers[timeSeriesRenewable] = make_shared< + RenewClustersAreaNumberOfTSretriever>(); + ts_to_numberOfTSretrievers[timeSeriesTransmissionCapacities] = make_shared< + AreaLinksTransCapaNumberOfTSretriever>(); // Loop over TS kind and check intra-modal consistency mapTStoRetriever::iterator it = ts_to_numberOfTSretrievers.begin(); for (; it != ts_to_numberOfTSretrievers.end(); ++it) { const TimeSeriesType tsKind = it->first; - areaNumberOfTSretriever* tsRetriever = (it->second).get(); + AreaNumberOfTSretriever* tsRetriever = (it->second).get(); int indexTS = ts_to_tsIndex.at(it->first); - IntraModalConsistencyChecker intraModalchecker( - tsKind, isTSintramodal, isTSgenerated, tsRetriever, study); - if (!intraModalchecker.check()) - return false; - nbTimeseriesByMode[indexTS] = intraModalchecker.getTimeSeriesNumber(); + if (isTSintramodal[indexTS]) + { + IntraModalConsistencyChecker intraModalchecker(tsKind, tsRetriever, study); + if (!intraModalchecker.checkTSconsistency()) + { + return false; + } + nbTimeseriesByMode[indexTS] = intraModalchecker.getTimeSeriesNumber(); + } } return true; } -bool checkInterModalConsistencyForArea(Area& area, - const array& isTSintermodal, - const array& isTSgenerated, - Study& study) +bool checkInterModalConsistencyForArea(const Area& area, + const array& isTSintermodal) { // 1. Making a list of TS numbers : // In this list, we put the numbers of TS of every "inter-modal" mode over the current area. @@ -386,55 +276,41 @@ bool checkInterModalConsistencyForArea(Area& area, // The list containing the numbers of TS of every "inter-modal" mode over the current area std::vector listNumberTsOverArea; - auto& parameters = study.parameters; - // Load : Add load's number of TS in area ... int indexTS = ts_to_tsIndex.at(timeSeriesLoad); if (isTSintermodal[indexTS]) { - uint nbTimeSeries - = isTSgenerated[indexTS] ? parameters.nbTimeSeriesLoad : area.load.series->timeSeries.width; - listNumberTsOverArea.push_back(nbTimeSeries); + listNumberTsOverArea.push_back(area.load.series.timeSeries.width); } // Solar : Add solar's number of TS in area ... indexTS = ts_to_tsIndex.at(timeSeriesSolar); if (isTSintermodal[indexTS]) { - uint nbTimeSeries - = isTSgenerated[indexTS] ? parameters.nbTimeSeriesSolar : area.solar.series->timeSeries.width; - listNumberTsOverArea.push_back(nbTimeSeries); + listNumberTsOverArea.push_back(area.solar.series.timeSeries.width); } // Wind : Add wind's number of TS in area ... indexTS = ts_to_tsIndex.at(timeSeriesWind); if (isTSintermodal[indexTS]) { - uint nbTimeSeries - = isTSgenerated[indexTS] ? parameters.nbTimeSeriesWind : area.wind.series->timeSeries.width; - listNumberTsOverArea.push_back(nbTimeSeries); + listNumberTsOverArea.push_back(area.wind.series.timeSeries.width); } // Hydro : Add hydro's number of TS in area ... indexTS = ts_to_tsIndex.at(timeSeriesHydro); if (isTSintermodal[indexTS]) { - uint nbTimeSeries - = isTSgenerated[indexTS] ? parameters.nbTimeSeriesHydro : area.hydro.series->count; - listNumberTsOverArea.push_back(nbTimeSeries); + listNumberTsOverArea.push_back(area.hydro.series->TScount()); } // Thermal : Add thermal's number of TS of each cluster in area ... indexTS = ts_to_tsIndex.at(timeSeriesThermal); if (isTSintermodal[indexTS]) { - const uint clusterCount = (uint)area.thermal.clusterCount(); - for (uint j = 0; j != clusterCount; ++j) + for (auto& cluster: area.thermal.list.each_enabled()) { - auto& cluster = *(area.thermal.clusters[j]); - uint nbTimeSeries = isTSgenerated[indexTS] ? parameters.nbTimeSeriesThermal - : cluster.series->timeSeries.width; - listNumberTsOverArea.push_back(nbTimeSeries); + listNumberTsOverArea.push_back(cluster->series.timeSeries.width); } } @@ -442,12 +318,9 @@ bool checkInterModalConsistencyForArea(Area& area, indexTS = ts_to_tsIndex.at(timeSeriesRenewable); if (isTSintermodal[indexTS]) { - const uint clusterCount = (uint)area.renewable.clusterCount(); - for (uint j = 0; j != clusterCount; ++j) + for (const auto& cluster: area.renewable.list.each_enabled()) { - auto& cluster = *(area.renewable.clusters[j]); - uint nbTimeSeries = cluster.series->timeSeries.width; - listNumberTsOverArea.push_back(nbTimeSeries); + listNumberTsOverArea.push_back(cluster->series.timeSeries.width); } } @@ -456,8 +329,7 @@ bool checkInterModalConsistencyForArea(Area& area, { logs.error() << "Inter-modal correlation: time-series numbers of inter-modal modes in area '" - << area.name << "'" - << " are not identical"; + << area.name << "'" << " are not identical"; return false; } @@ -496,386 +368,378 @@ void storeTSnumbersForIntraModal(const array& intramo uint year, AreaList& areas) { - areas.each([&](Area& area) { - // ------------- - // Load ... - // ------------- - assert(year < area.load.series->timeseriesNumbers.height); - int indexTS = ts_to_tsIndex.at(timeSeriesLoad); - - if (isTSintramodal[indexTS]) - area.load.series->timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - - // ------------- - // Solar ... - // ------------- - assert(year < area.solar.series->timeseriesNumbers.height); - indexTS = ts_to_tsIndex.at(timeSeriesSolar); - - if (isTSintramodal[indexTS]) - area.solar.series->timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - - // ------------- - // Wind ... - // ------------- - assert(year < area.wind.series->timeseriesNumbers.height); - indexTS = ts_to_tsIndex.at(timeSeriesWind); - - if (isTSintramodal[indexTS]) - area.wind.series->timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - - // ------------- - // Hydro ... - // ------------- - assert(year < area.hydro.series->timeseriesNumbers.height); - indexTS = ts_to_tsIndex.at(timeSeriesHydro); - - if (isTSintramodal[indexTS]) - area.hydro.series->timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - - // ------------- - // Thermal ... - // ------------- - indexTS = ts_to_tsIndex.at(timeSeriesThermal); - - if (isTSintramodal[indexTS]) - { - auto end_th_clusters = area.thermal.list.mapping.end(); - for (auto i = area.thermal.list.mapping.begin(); i != end_th_clusters; ++i) - { - ThermalClusterList::SharedPtr cluster = i->second; - if (cluster->enabled) - cluster->series->timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - } - } - - // -------------------------- - // Renewable clusters ... - // -------------------------- - indexTS = ts_to_tsIndex.at(timeSeriesRenewable); - - if (isTSintramodal[indexTS]) - { - auto end_rn_clusters = area.renewable.list.cluster.end(); - for (auto j = area.renewable.list.cluster.begin(); j != end_rn_clusters; ++j) - { - RenewableClusterList::SharedPtr cluster = j->second; - if (cluster->enabled) - cluster->series->timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - } - } - - // ------------------------------- - // Transmission capacities ... - // ------------------------------- - indexTS = ts_to_tsIndex.at(timeSeriesTransmissionCapacities); - - if (isTSintramodal[indexTS]) - { - for (auto it = area.links.begin(); it != area.links.end(); ++it) - { - auto& link = *(it->second); - link.timeseriesNumbers[0][year] = intramodal_draws[indexTS]; - } - } - }); + areas.each( + [year, &isTSintramodal, &intramodal_draws](Area& area) + { + // ------------- + // Load ... + // ------------- + assert(year < area.load.series.timeseriesNumbers.height()); + int indexTS = ts_to_tsIndex.at(timeSeriesLoad); + + if (isTSintramodal[indexTS] && area.load.series.timeSeries.width > 1) + { + area.load.series.timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + + // ------------- + // Solar ... + // ------------- + assert(year < area.solar.series.timeseriesNumbers.height()); + indexTS = ts_to_tsIndex.at(timeSeriesSolar); + + if (isTSintramodal[indexTS] && area.solar.series.timeSeries.width > 1) + { + area.solar.series.timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + + // ------------- + // Wind ... + // ------------- + assert(year < area.wind.series.timeseriesNumbers.height()); + indexTS = ts_to_tsIndex.at(timeSeriesWind); + + if (isTSintramodal[indexTS] && area.wind.series.timeSeries.width > 1) + { + area.wind.series.timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + + // ------------- + // Hydro ... + // ------------- + assert(year < area.hydro.series->timeseriesNumbers.height()); + indexTS = ts_to_tsIndex.at(timeSeriesHydro); + + if (isTSintramodal[indexTS] && area.hydro.series->TScount() > 1) + { + area.hydro.series->timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + + // ------------- + // Thermal ... + // ------------- + indexTS = ts_to_tsIndex.at(timeSeriesThermal); + + if (isTSintramodal[indexTS]) + { + for (auto& cluster: area.thermal.list.each_enabled()) + { + cluster->series.timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + } + + // -------------------------- + // Renewable clusters ... + // -------------------------- + indexTS = ts_to_tsIndex.at(timeSeriesRenewable); + + if (isTSintramodal[indexTS]) + { + for (auto& cluster: area.renewable.list.each_enabled()) + { + cluster->series.timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + } + + // ------------------------------- + // Transmission capacities ... + // ------------------------------- + indexTS = ts_to_tsIndex.at(timeSeriesTransmissionCapacities); + + if (isTSintramodal[indexTS]) + { + for (auto it = area.links.begin(); it != area.links.end(); ++it) + { + auto& link = *(it->second); + if (link.directCapacities.timeSeries.width > 1) + { + link.timeseriesNumbers[year] = intramodal_draws[indexTS]; + } + } + } + }); } void drawAndStoreTSnumbersForNOTintraModal(const array& isTSintramodal, - const array& isTSgenerated, - array& nbTimeseriesByMode, uint year, Study& study) { - study.areas.each([&](Area& area) { - // ------------- - // Load ... - // ------------- - int indexTS = ts_to_tsIndex.at(timeSeriesLoad); - - if (!isTSintramodal[indexTS]) - { - uint nbTimeSeries = isTSgenerated[indexTS] ? nbTimeseriesByMode[indexTS] - : area.load.series->timeSeries.width; - area.load.series->timeseriesNumbers[0][year] - = (uint32_t)(floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - - // ------------- - // Solar ... - // ------------- - indexTS = ts_to_tsIndex.at(timeSeriesSolar); - - if (!isTSintramodal[indexTS]) - { - uint nbTimeSeries = isTSgenerated[indexTS] ? nbTimeseriesByMode[indexTS] - : area.solar.series->timeSeries.width; - area.solar.series->timeseriesNumbers[0][year] - = (uint32_t)(floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - - // ------------- - // Wind ... - // ------------- - indexTS = ts_to_tsIndex.at(timeSeriesWind); - - if (!isTSintramodal[indexTS]) - { - uint nbTimeSeries = isTSgenerated[indexTS] ? nbTimeseriesByMode[indexTS] - : area.wind.series->timeSeries.width; - area.wind.series->timeseriesNumbers[0][year] - = (uint32_t)(floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - - // ------------- - // Hydro ... - // ------------- - indexTS = ts_to_tsIndex.at(timeSeriesHydro); - - if (!isTSintramodal[indexTS]) - { - uint nbTimeSeries - = isTSgenerated[indexTS] ? nbTimeseriesByMode[indexTS] : area.hydro.series->ror.width; - area.hydro.series->timeseriesNumbers[0][year] - = (uint32_t)(floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - - // ------------- - // Thermal ... - // ------------- - indexTS = ts_to_tsIndex.at(timeSeriesThermal); - - auto end_th_clusters = area.thermal.list.mapping.end(); - for (auto i = area.thermal.list.mapping.begin(); i != end_th_clusters; ++i) - { - ThermalClusterList::SharedPtr cluster = i->second; - if (not cluster->enabled) - study.runtime->random[seedTimeseriesNumbers].next(); - else - { - if (!isTSintramodal[indexTS]) - { - uint nbTimeSeries = isTSgenerated[indexTS] ? nbTimeseriesByMode[indexTS] - : cluster->series->timeSeries.width; - cluster->series->timeseriesNumbers[0][year] = (uint32_t)( - floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - } - } - - // -------------------------- - // Renewable clusters ... - // -------------------------- - indexTS = ts_to_tsIndex.at(timeSeriesRenewable); - - auto end_rn_clusters = area.renewable.list.cluster.end(); - for (auto j = area.renewable.list.cluster.begin(); j != end_rn_clusters; ++j) - { - RenewableClusterList::SharedPtr cluster = j->second; - if (not cluster->enabled) - study.runtime->random[seedTimeseriesNumbers].next(); - else - { - if (!isTSintramodal[indexTS]) - { - // There is no TS generation for renewable clusters - uint nbTimeSeries = cluster->series->timeSeries.width; - cluster->series->timeseriesNumbers[0][year] = (uint32_t)( - floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - } - } - - // ------------------------------- - // Transmission capacities ... - // ------------------------------- - indexTS = ts_to_tsIndex.at(timeSeriesTransmissionCapacities); - - if (!isTSintramodal[indexTS]) - { - for (auto it = area.links.begin(); it != area.links.end(); ++it) - { - auto& link = *(it->second); - const uint nbTimeSeries = link.directCapacities.width; - if (nbTimeSeries == 1) - { - // Random generator (mersenne-twister) must not be called here - // in order to avoid a shift in the random generator results - // that would cause a change of Antares results - link.timeseriesNumbers[0][year] = 0; - } - else - { - link.timeseriesNumbers[0][year] = (uint32_t)( - floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); - } - } - } - }); + study.areas.each( + [&study, &isTSintramodal, year](Area& area) + { + // ------------- + // Load ... + // ------------- + int indexTS = ts_to_tsIndex.at(timeSeriesLoad); + + if (!isTSintramodal[indexTS]) + { + area.load.series.timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() + * area.load.series.timeSeries.width)); + } + + // ------------- + // Solar ... + // ------------- + indexTS = ts_to_tsIndex.at(timeSeriesSolar); + + if (!isTSintramodal[indexTS]) + { + area.solar.series.timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() + * area.solar.series.timeSeries.width)); + } + + // ------------- + // Wind ... + // ------------- + indexTS = ts_to_tsIndex.at(timeSeriesWind); + + if (!isTSintramodal[indexTS]) + { + area.wind.series.timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() + * area.wind.series.timeSeries.width)); + } + + // ------------- + // Hydro ... + // ------------- + indexTS = ts_to_tsIndex.at(timeSeriesHydro); + + if (!isTSintramodal[indexTS]) + { + area.hydro.series->timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() + * area.hydro.series->TScount())); + } + + // ------------- + // Thermal ... + // ------------- + indexTS = ts_to_tsIndex.at(timeSeriesThermal); + + for (auto& cluster: area.thermal.list.all()) + { + if (!cluster->enabled) + { + study.runtime->random[seedTimeseriesNumbers].next(); + } + else + { + if (!isTSintramodal[indexTS]) + { + cluster->series.timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() + * cluster->series.timeSeries.width)); + } + } + } + + // -------------------------- + // Renewable clusters ... + // -------------------------- + indexTS = ts_to_tsIndex.at(timeSeriesRenewable); + + for (auto& cluster: area.renewable.list.each_enabled()) + { + if (!isTSintramodal[indexTS]) + { + // There is no TS generation for renewable clusters + uint nbTimeSeries = cluster->series.timeSeries.width; + cluster->series.timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); + } + } + + // ------------------------------- + // Transmission capacities ... + // ------------------------------- + indexTS = ts_to_tsIndex.at(timeSeriesTransmissionCapacities); + + if (!isTSintramodal[indexTS]) + { + for (auto it = area.links.begin(); it != area.links.end(); ++it) + { + auto& link = *(it->second); + const uint nbTimeSeries = link.directCapacities.timeSeries.width; + if (nbTimeSeries > 1) + { + link.timeseriesNumbers[year] = (uint32_t)(floor( + study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); + } + } + } + }); // Binding constraints for (auto& group: study.bindingConstraintsGroups) { const auto nbTimeSeries = group->numberOfTimeseries(); - auto& value = group->timeseriesNumbers[0][year]; - if (nbTimeSeries == 1) + auto& groupTsNumber = group->timeseriesNumbers[year]; + if (nbTimeSeries > 1) { - value = 0; - } - else - { - value = (uint32_t)(floor(study.runtime->random[seedTimeseriesNumbers].next() * nbTimeSeries)); + groupTsNumber = (uint32_t)(floor(study.runtime->random[seedTimeseriesNumbers].next() + * nbTimeSeries)); } } } -Matrix* getFirstTSnumberInterModalMatrixFoundInArea( +Data::TimeSeriesNumbers* getFirstTSnumberInterModalMatrixFoundInArea( Area& area, const array& isTSintermodal) { - Matrix* tsNumbersMtx = nullptr; + Data::TimeSeriesNumbers* tsNumbersMtx = nullptr; if (isTSintermodal[ts_to_tsIndex.at(timeSeriesLoad)]) - tsNumbersMtx = &(area.load.series->timeseriesNumbers); + { + tsNumbersMtx = &(area.load.series.timeseriesNumbers); + } else { if (isTSintermodal[ts_to_tsIndex.at(timeSeriesSolar)]) - tsNumbersMtx = &(area.solar.series->timeseriesNumbers); + { + tsNumbersMtx = &(area.solar.series.timeseriesNumbers); + } else if (isTSintermodal[ts_to_tsIndex.at(timeSeriesWind)]) - tsNumbersMtx = &(area.wind.series->timeseriesNumbers); + { + tsNumbersMtx = &(area.wind.series.timeseriesNumbers); + } else if (isTSintermodal[ts_to_tsIndex.at(timeSeriesHydro)]) + { tsNumbersMtx = &(area.hydro.series->timeseriesNumbers); + } else if (isTSintermodal[ts_to_tsIndex.at(timeSeriesThermal)] - && area.thermal.clusterCount() > 0) - tsNumbersMtx = &(area.thermal.clusters[0]->series->timeseriesNumbers); + && !area.thermal.list.each_enabled().empty()) + { + std::shared_ptr cluster = *(area.thermal.list.each_enabled().begin()); + tsNumbersMtx = &(cluster->series.timeseriesNumbers); + } else if (isTSintermodal[ts_to_tsIndex.at(timeSeriesRenewable)] - && area.renewable.clusterCount() > 0) - tsNumbersMtx = &(area.renewable.clusters[0]->series->timeseriesNumbers); + && area.renewable.list.enabledCount() > 0) + { + std::shared_ptr cluster = *( + area.renewable.list.each_enabled().begin()); + tsNumbersMtx = &(cluster->series.timeseriesNumbers); + } } assert(tsNumbersMtx); return tsNumbersMtx; } -void applyMatrixDrawsToInterModalModesInArea(Matrix* tsNumbersMtx, - Area& area, - const array& isTSintermodal, - const uint years) +static void applyMatrixDrawsToInterModalModesInArea( + Data::TimeSeriesNumbers& tsNumbersMtx, + Area& area, + const array& isTSintermodal, + const uint years) { for (uint year = 0; year < years; ++year) { - const uint draw = tsNumbersMtx->entry[0][year]; + const uint32_t draw = tsNumbersMtx[year]; assert(draw < 100000); - assert(year < area.load.series->timeseriesNumbers.height); + assert(year < area.load.series.timeseriesNumbers.height()); if (isTSintermodal[ts_to_tsIndex.at(timeSeriesLoad)]) - area.load.series->timeseriesNumbers[0][year] = draw; + { + area.load.series.timeseriesNumbers[year] = draw; + } - assert(year < area.solar.series->timeseriesNumbers.height); + assert(year < area.solar.series.timeseriesNumbers.height()); if (isTSintermodal[ts_to_tsIndex.at(timeSeriesSolar)]) - area.solar.series->timeseriesNumbers[0][year] = draw; + { + area.solar.series.timeseriesNumbers[year] = draw; + } - assert(year < area.wind.series->timeseriesNumbers.height); + assert(year < area.wind.series.timeseriesNumbers.height()); if (isTSintermodal[ts_to_tsIndex.at(timeSeriesWind)]) - area.wind.series->timeseriesNumbers[0][year] = draw; + { + area.wind.series.timeseriesNumbers[year] = draw; + } - assert(year < area.hydro.series->timeseriesNumbers.height); + assert(year < area.hydro.series->timeseriesNumbers.height()); if (isTSintermodal[ts_to_tsIndex.at(timeSeriesHydro)]) - area.hydro.series->timeseriesNumbers[0][year] = draw; + { + area.hydro.series->timeseriesNumbers[year] = draw; + } if (isTSintermodal[ts_to_tsIndex.at(timeSeriesThermal)]) { - uint clusterCount = (uint)area.thermal.clusterCount(); - for (uint i = 0; i != clusterCount; ++i) + for (auto& cluster: area.thermal.list.each_enabled()) { - auto& cluster = *(area.thermal.clusters[i]); - assert(year < cluster.series->timeseriesNumbers.height); - cluster.series->timeseriesNumbers[0][year] = draw; + assert(year < cluster->series.timeseriesNumbers.height()); + cluster->series.timeseriesNumbers[year] = draw; } } if (isTSintermodal[ts_to_tsIndex.at(timeSeriesRenewable)]) { - uint clusterCount = (uint)area.renewable.clusterCount(); - for (uint i = 0; i != clusterCount; ++i) + for (const auto& cluster: area.renewable.list.each_enabled()) { - auto& cluster = *(area.renewable.clusters[i]); - assert(year < cluster.series->timeseriesNumbers.height); - cluster.series->timeseriesNumbers[0][year] = draw; + assert(year < cluster->series.timeseriesNumbers.height()); + cluster->series.timeseriesNumbers[year] = draw; } } } } -// Set tsNumbers to 1 for all years if only one TS is present -static void fixTSNumbersSingleAreaSingleMode(Matrix& tsNumbers, uint width, uint years) +bool TimeSeriesNumbers::checkAllElementsIdenticalOrOne(std::vector w) { - if (width == 1) + auto first_one = std::remove(w.begin(), w.end(), 1); // Reject all 1 to the end + return std::adjacent_find(w.begin(), first_one, std::not_equal_to()) == first_one; +} + +using Checks = std::vector>; + +static Checks buildChecksFromStudy(const AreaList& areas) +{ + Checks toCheck; + + // LINKS + for (const auto& [_, area]: areas) { - for (uint year = 0; year < years; year++) + const std::string areaID = area->id.to(); + for (const auto& [_, link]: area->links) { - tsNumbers[0][year] = 0; + const std::string areaID2 = link->with->id.to(); + toCheck.push_back({&link->timeseriesNumbers, "link " + areaID + " / " + areaID2}); } } + + // HYDRO + for (const auto& [_, area]: areas) + { + const std::string areaID = area->id.to(); + toCheck.push_back({&area->hydro.series->timeseriesNumbers, "hydro " + areaID}); + } + + return toCheck; } -static void fixTSNumbersWhenWidthIsOne(Study& study) +static bool performChecks(const Checks& toCheck) { - const uint years = 1 + study.runtime->rangeLimits.year[rangeEnd]; + bool ret = true; + for (const auto& [tsNumber, context]: toCheck) + { + const auto errorMessageMaybe = tsNumber->checkSeriesNumberOfColumnsConsistency(); + if (errorMessageMaybe.has_value()) + { + logs.error() << "Inconsistent number of columns for " << context << " (" + << errorMessageMaybe.value() << ")"; + ret = false; + } + } + if (!ret) + { + logs.error() << "Please check that all series have the same number of columns or 1 column, " + "or a combination of 1 column and the same number of columns"; + } - study.areas.each([&years](Area& area) { - // Load - fixTSNumbersSingleAreaSingleMode( - area.load.series->timeseriesNumbers, area.load.series->timeSeries.width, years); - // Solar - fixTSNumbersSingleAreaSingleMode( - area.solar.series->timeseriesNumbers, area.solar.series->timeSeries.width, years); - // Wind - fixTSNumbersSingleAreaSingleMode( - area.wind.series->timeseriesNumbers, area.wind.series->timeSeries.width, years); - // Hydro - fixTSNumbersSingleAreaSingleMode( - area.hydro.series->timeseriesNumbers, area.hydro.series->count, years); - - // Thermal - std::for_each(area.thermal.clusters.cbegin(), - area.thermal.clusters.cend(), - [&years](const Data::ThermalCluster* cluster) { - fixTSNumbersSingleAreaSingleMode(cluster->series->timeseriesNumbers, - cluster->series->timeSeries.width, - years); - }); - - // Renewables - std::for_each(area.renewable.clusters.cbegin(), - area.renewable.clusters.cend(), - [&years](const Data::RenewableCluster* cluster) - - { - fixTSNumbersSingleAreaSingleMode(cluster->series->timeseriesNumbers, - cluster->series->timeSeries.width, - years); - }); - - // NTC - std::for_each(area.links.cbegin(), - area.links.cend(), - [&years](const std::pair& it) { - auto link = it.second; - fixTSNumbersSingleAreaSingleMode( - link->timeseriesNumbers, link->directCapacities.width, years); - }); - }); - study.bindingConstraintsGroups.fixTSNumbersWhenWidthIsOne(); + return ret; } -bool TimeSeriesNumbers::checkAllElementsIdenticalOrOne(const std::vector& w) +bool TimeSeriesNumbers::CheckNumberOfColumns(const AreaList& areas) { - std::vector removedOnes; - // Remove all 1 - std::remove_copy(w.begin(), w.end(), std::back_inserter(removedOnes), 1); - // Try to find adjacent elements that are pairwise different - auto result - = std::adjacent_find(removedOnes.begin(), removedOnes.end(), std::not_equal_to()); - // Return "no such pair exists" - return result == removedOnes.end(); + Checks toCheck = buildChecksFromStudy(areas); + return performChecks(toCheck); } bool TimeSeriesNumbers::Generate(Study& study) @@ -885,66 +749,63 @@ bool TimeSeriesNumbers::Generate(Study& study) auto& parameters = study.parameters; if (parameters.derated) + { return GenerateDeratedMode(study); + } const uint years = 1 + study.runtime->rangeLimits.year[rangeEnd]; - const array isTSintramodal - = {(bool)(timeSeriesLoad & parameters.intraModal), - (bool)(timeSeriesHydro & parameters.intraModal), - (bool)(timeSeriesWind & parameters.intraModal) - && parameters.renewableGeneration.isAggregated(), - (bool)(timeSeriesThermal & parameters.intraModal), - (bool)(timeSeriesSolar & parameters.intraModal) - && parameters.renewableGeneration.isAggregated(), - (bool)(timeSeriesRenewable & parameters.intraModal) - && parameters.renewableGeneration.isClusters(), - (bool)(timeSeriesTransmissionCapacities & parameters.intraModal)}; + const array isTSintramodal = { + (bool)(timeSeriesLoad & parameters.intraModal), + (bool)(timeSeriesHydro & parameters.intraModal), + (bool)(timeSeriesWind & parameters.intraModal) + && parameters.renewableGeneration.isAggregated(), + (bool)(timeSeriesThermal & parameters.intraModal), + (bool)(timeSeriesSolar & parameters.intraModal) + && parameters.renewableGeneration.isAggregated(), + (bool)(timeSeriesRenewable & parameters.intraModal) + && parameters.renewableGeneration.isClusters(), + (bool)(timeSeriesTransmissionCapacities & parameters.intraModal)}; array nbTimeseriesByMode; array intramodal_draws; std::fill(intramodal_draws.begin(), intramodal_draws.end(), 0); - const array isTSgenerated - = {(bool)(timeSeriesLoad & parameters.timeSeriesToRefresh), - (bool)(timeSeriesHydro & parameters.timeSeriesToRefresh), - (bool)(timeSeriesWind & parameters.timeSeriesToRefresh), - (bool)(timeSeriesThermal & parameters.timeSeriesToRefresh), - (bool)(timeSeriesSolar & parameters.timeSeriesToRefresh), - false, // TS generation is always disabled for renewables - false}; // TS generation is always disabled for links transmission capacities - - if (not checkIntraModalConsistency(nbTimeseriesByMode, isTSintramodal, isTSgenerated, study)) + if (!checkIntraModalConsistency(nbTimeseriesByMode, isTSintramodal, study)) + { return false; + } for (uint year = 0; year < years; ++year) { - // Intra-modal TS : draw and store TS numbres - drawTSnumbersForIntraModal( - intramodal_draws, isTSintramodal, nbTimeseriesByMode, study.runtime->random); + // Intra-modal TS : draw and store TS numbers + drawTSnumbersForIntraModal(intramodal_draws, + isTSintramodal, + nbTimeseriesByMode, + study.runtime->random); storeTSnumbersForIntraModal(intramodal_draws, isTSintramodal, year, study.areas); // NOT intra-modal TS : draw and store TS numbers - drawAndStoreTSnumbersForNOTintraModal( - isTSintramodal, isTSgenerated, nbTimeseriesByMode, year, study); + drawAndStoreTSnumbersForNOTintraModal(isTSintramodal, year, study); } // =============== // Inter-modal // =============== - const array isTSintermodal - = {(bool)(timeSeriesLoad & parameters.interModal), - (bool)(timeSeriesHydro & parameters.interModal), - (bool)(timeSeriesWind & parameters.interModal) - && parameters.renewableGeneration.isAggregated(), - (bool)(timeSeriesThermal & parameters.interModal), - (bool)(timeSeriesSolar & parameters.interModal) - && parameters.renewableGeneration.isAggregated(), - (bool)(timeSeriesRenewable & parameters.interModal) - && parameters.renewableGeneration.isClusters(), - false}; // links transmission capacities time series cannot be inter-modal + const array isTSintermodal = { + (bool)(timeSeriesLoad & parameters.interModal), + (bool)(timeSeriesHydro & parameters.interModal), + (bool)(timeSeriesWind & parameters.interModal) + && parameters.renewableGeneration.isAggregated(), + (bool)(timeSeriesThermal & parameters.interModal), + (bool)(timeSeriesSolar & parameters.interModal) + && parameters.renewableGeneration.isAggregated(), + (bool)(timeSeriesRenewable & parameters.interModal) + && parameters.renewableGeneration.isClusters(), + false // links transmission capacities time series cannot be inter-modal + }; if (std::any_of(std::begin(isTSintermodal), std::end(isTSintermodal), [](bool x) { return x; })) { @@ -957,32 +818,36 @@ bool TimeSeriesNumbers::Generate(Study& study) for (auto i = study.areas.begin(); i != end; ++i) { auto& area = *(i->second); - if (not checkInterModalConsistencyForArea(area, isTSintermodal, isTSgenerated, study)) + if (not checkInterModalConsistencyForArea(area, isTSintermodal)) + { return false; + } - Matrix* tsNumbersMtx - = getFirstTSnumberInterModalMatrixFoundInArea(area, isTSintermodal); + Data::TimeSeriesNumbers* tsNumbersMtx = getFirstTSnumberInterModalMatrixFoundInArea( + area, + isTSintermodal); - applyMatrixDrawsToInterModalModesInArea(tsNumbersMtx, area, isTSintermodal, years); + applyMatrixDrawsToInterModalModesInArea(*tsNumbersMtx, area, isTSintermodal, years); } } return true; } -void TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(Data::Study& study, IResultWriter& resultWriter) +void TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(Data::Study& study, + IResultWriter& resultWriter) { using namespace Antares::Data; if (study.parameters.storeTimeseriesNumbers) { - fixTSNumbersWhenWidthIsOne(study); study.storeTimeSeriesNumbers(resultWriter); study.storeTimeSeriesNumbers(resultWriter); study.storeTimeSeriesNumbers(resultWriter); study.storeTimeSeriesNumbers(resultWriter); study.storeTimeSeriesNumbers(resultWriter); study.storeTimeSeriesNumbers(resultWriter); - study.storeTimeSeriesNumbers(resultWriter); + study.storeTimeSeriesNumbers( + resultWriter); Simulation::BindingConstraintsTimeSeriesNumbersWriter ts_writer(resultWriter); ts_writer.write(study.bindingConstraintsGroups); diff --git a/src/solver/simulation/timeseries-numbers.h b/src/solver/simulation/timeseries-numbers.h deleted file mode 100644 index 3844d51b24..0000000000 --- a/src/solver/simulation/timeseries-numbers.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_SIMULATION_GENERATE_TIMESERIES_H__ -#define __SOLVER_SIMULATION_GENERATE_TIMESERIES_H__ - -#include -#include -#include -#include "ITimeSeriesNumbersWriter.h" - -namespace Antares::Solver::TimeSeriesNumbers -{ -/*! -** \brief Generate all time-series numbers for a given set -*/ -bool Generate(Data::Study& study); - -void StoreTimeSeriesNumbersIntoOuput(Data::Study &study, IResultWriter& resultWriter); - -// Exported for unit-tests -bool checkAllElementsIdenticalOrOne(const std::vector& w); - -} // namespace Antares::Solver::TimeSeriesNumbers - -#endif // __SOLVER_SIMULATION_GENERATE_TIMESERIES_H__ diff --git a/src/solver/ts-generator/CMakeLists.txt b/src/solver/ts-generator/CMakeLists.txt index 2d0800f614..f2ef1559a9 100644 --- a/src/solver/ts-generator/CMakeLists.txt +++ b/src/solver/ts-generator/CMakeLists.txt @@ -4,10 +4,11 @@ project(ts-generator) # Time-Series Generators # set(SRC_GENERATORS - generator.h - generator.hxx - thermal.cpp - hydro.cpp + include/antares/solver/ts-generator/generator.h + include/antares/solver/ts-generator/generator.hxx + generator.cpp + availability.cpp + hydro.cpp ) source_group("ts-generator" FILES ${SRC_GENERATORS}) @@ -16,35 +17,50 @@ source_group("ts-generator" FILES ${SRC_GENERATORS}) # XCast # set(SRC_XCAST - xcast/constants.h - xcast/studydata.h - xcast/studydata.hxx + include/antares/solver/ts-generator/xcast/constants.h + include/antares/solver/ts-generator/xcast/studydata.h + include/antares/solver/ts-generator/xcast/studydata.hxx + include/antares/solver/ts-generator/law.h + + prepro.cpp + + include/antares/solver/ts-generator/prepro.h xcast/studydata.cpp xcast/gamma-euler.cpp xcast/gamma-inc.cpp xcast/core.cpp - xcast/math.hxx + include/antares/solver/ts-generator/xcast/math.hxx xcast/math.cpp # XCAST - xcast/xcast.h - xcast/xcast.hxx + include/antares/solver/ts-generator/xcast/xcast.h + include/antares/solver/ts-generator/xcast/xcast.hxx xcast/xcast.cpp ) source_group("ts-generator\\XCast" FILES ${SRC_XCAST}) - # # --- Library VARIABLES --- # add_library(antares-solver-ts-generator - ${SRC_GENERATORS} - ${SRC_XCAST}) + ${SRC_GENERATORS} + ${SRC_XCAST}) target_link_libraries(antares-solver-ts-generator - PRIVATE - result_writer - array - benchmarking - Antares::study + PRIVATE + result_writer + array + benchmarking + Antares::study + Antares::misc + antares-solver-simulation +) + +target_include_directories(antares-solver-ts-generator + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" ) diff --git a/src/solver/ts-generator/availability.cpp b/src/solver/ts-generator/availability.cpp new file mode 100644 index 0000000000..efb5991093 --- /dev/null +++ b/src/solver/ts-generator/availability.cpp @@ -0,0 +1,729 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include +#include +#include + +#include // For Antares::IO::fileSetContent +#include +#include +#include +#include +#include +#include "antares/study/simulation.h" + +#define SEP Yuni::IO::Separator + +constexpr double FAILURE_RATE_EQ_1 = 0.999; + +namespace Antares::TSGenerator +{ +AvailabilityTSGeneratorData::AvailabilityTSGeneratorData(Data::ThermalCluster* cluster): + unitCount(cluster->unitCount), + nominalCapacity(cluster->nominalCapacity), + forcedVolatility(cluster->forcedVolatility), + plannedVolatility(cluster->plannedVolatility), + forcedLaw(cluster->forcedLaw), + plannedLaw(cluster->plannedLaw), + prepro(cluster->prepro), + series(cluster->series.timeSeries), + modulationCapacity(cluster->modulation[Data::thermalModulationCapacity]), + name(cluster->name()) +{ +} + +AvailabilityTSGeneratorData::AvailabilityTSGeneratorData(LinkTSgenerationParams& source, + Data::TimeSeries& capacity, + Matrix<>& modulation, + const std::string& areaDestName): + unitCount(source.unitCount), + nominalCapacity(source.nominalCapacity), + forcedVolatility(source.forcedVolatility), + plannedVolatility(source.plannedVolatility), + forcedLaw(source.forcedLaw), + plannedLaw(source.plannedLaw), + prepro(source.prepro.get()), + series(capacity.timeSeries), + modulationCapacity(modulation[0]), + name(areaDestName) +{ +} + +namespace +{ +class GeneratorTempData final +{ +public: + explicit GeneratorTempData(Data::Study&, unsigned, MersenneTwister&); + explicit GeneratorTempData(bool, unsigned, MersenneTwister&); + + void generateTS(AvailabilityTSGeneratorData&) const; + +private: + bool derated; + + uint nbOfSeriesToGen_; + + MersenneTwister& rndgenerator; + + static constexpr int Log_size = 4000; + + int durationGenerator(Data::StatisticalLaw law, + int expec, + double volat, + double a, + double b) const; + + template + void prepareIndispoFromLaw(Data::StatisticalLaw law, + double volatility, + std::array& A, + std::array& B, + const T& duration) const; +}; + +GeneratorTempData::GeneratorTempData(Data::Study& study, + unsigned nbOfSeriesToGen, + MersenneTwister& rndGenerator): + derated(study.parameters.derated), + nbOfSeriesToGen_(nbOfSeriesToGen), + rndgenerator(rndGenerator) +{ +} + +GeneratorTempData::GeneratorTempData(bool derated, + unsigned int nbOfSeriesToGen, + MersenneTwister& rndGenerator): + derated(derated), + nbOfSeriesToGen_(nbOfSeriesToGen), + rndgenerator(rndGenerator) +{ +} + +template +void GeneratorTempData::prepareIndispoFromLaw(Data::StatisticalLaw law, + double volatility, + std::array& A, + std::array& B, + const T& duration) const +{ + switch (law) + { + case Data::LawUniform: + { + for (uint d = 0; d < DAYS_PER_YEAR; ++d) + { + double D = duration[d]; + double xtemp = volatility * (D - 1.); + A[d] = D - xtemp; + B[d] = 2. * xtemp + 1.; + } + break; + } + case Data::LawGeometric: + { + for (uint d = 0; d < DAYS_PER_YEAR; ++d) + { + double D = duration[d]; + double xtemp = volatility * volatility * D * (D - 1.); + if (xtemp != 0) + { + B[d] = 4. * xtemp + 1.; + B[d] = sqrt(B[d]) - 1.; + B[d] /= 2. * xtemp; + A[d] = D - 1. / B[d]; + B[d] = log(1. - B[d]); + B[d] = 1. / B[d]; + } + else + { + B[d] = 1.; + A[d] = 1.; + } + } + break; + } + } +} + +int GeneratorTempData::durationGenerator(Data::StatisticalLaw law, + int expec, + double volat, + double a, + double b) const +{ + if (volat == 0 || expec == 1) + { + return expec; + } + + double rndnumber = rndgenerator.next(); + + switch (law) + { + case Data::LawUniform: + { + return (int(a + rndnumber * b)); + } + case Data::LawGeometric: + { + int resultat = (1 + int(a + (b)*log(rndnumber))); + int limit = Log_size / 2 - 1; + + assert(limit == 1999); + return (resultat <= limit) ? resultat : limit; + } + } + assert(false && "return is missing"); + return 0; +} + +void GeneratorTempData::generateTS(AvailabilityTSGeneratorData& tsGenerationData) const +{ + assert(tsGenerationData.prepro); + + if (0 == tsGenerationData.unitCount || 0 == tsGenerationData.nominalCapacity) + { + return; + } + + const auto& preproData = *(tsGenerationData.prepro); + + int AUN = tsGenerationData.unitCount; + + auto& FOD = preproData.data[Data::PreproAvailability::foDuration]; + + auto& POD = preproData.data[Data::PreproAvailability::poDuration]; + + auto& FOR = preproData.data[Data::PreproAvailability::foRate]; + + auto& POR = preproData.data[Data::PreproAvailability::poRate]; + + auto& NPOmin = preproData.data[Data::PreproAvailability::npoMin]; + + auto& NPOmax = preproData.data[Data::PreproAvailability::npoMax]; + + double f_volatility = tsGenerationData.forcedVolatility; + + double p_volatility = tsGenerationData.plannedVolatility; + + auto f_law = tsGenerationData.forcedLaw; + + auto p_law = tsGenerationData.plannedLaw; + + std::vector> FPOW(DAYS_PER_YEAR); + std::vector> PPOW(DAYS_PER_YEAR); + + std::array lf; + std::array lp; + std::array ff; + std::array pp; + std::array af; + std::array ap; + std::array bf; + std::array bp; + + int FODOfTheDay; + int PODOfTheDay; + + int FOD_reel = 0; + int POD_reel = 0; + + for (uint d = 0; d < DAYS_PER_YEAR; ++d) + { + FPOW[d].resize(tsGenerationData.unitCount + 1); + PPOW[d].resize(tsGenerationData.unitCount + 1); + + PODOfTheDay = (int)POD[d]; + FODOfTheDay = (int)FOD[d]; + + lf[d] = FOR[d] / (FOR[d] + (FODOfTheDay) * (1. - FOR[d])); + lp[d] = POR[d] / (POR[d] + (PODOfTheDay) * (1. - POR[d])); + + if (0. < lf[d] && lf[d] < lp[d]) + { + lf[d] *= (1. - lp[d]) / (1. - lf[d]); + } + + if (0. < lp[d] && lp[d] < lf[d]) + { + lp[d] *= (1. - lf[d]) / (1. - lp[d]); + } + + double a = 0.; + double b = 0.; + + if (lf[d] <= FAILURE_RATE_EQ_1) + { + a = 1. - lf[d]; + ff[d] = lf[d] / a; + } + + if (lp[d] <= FAILURE_RATE_EQ_1) + { + b = 1. - lp[d]; + pp[d] = lp[d] / b; + } + + for (uint k = 0; k != tsGenerationData.unitCount + 1; ++k) + { + FPOW[d][k] = pow(a, (double)k); + PPOW[d][k] = pow(b, (double)k); + } + } + + prepareIndispoFromLaw(f_law, f_volatility, af, bf, FOD); + prepareIndispoFromLaw(p_law, p_volatility, ap, bp, POD); + + std::array AVP{}; + std::array LOG{}; + std::array LOGP{}; + + int MXO = 0; + + int PPO = 0; + + int PFO = 0; + + int NOW = 0; + + int FUT = 0; + + int NPO_cur = 0; + + int stock = 0; + + double A = 0; + double cumul = 0; + double last = 0; + + auto& modulation = tsGenerationData.modulationCapacity; + double* dstSeries = nullptr; + + const uint tsCount = nbOfSeriesToGen_ + 2; + for (uint tsIndex = 0; tsIndex != tsCount; ++tsIndex) + { + uint hour = 0; + + if (tsIndex > 1) + { + dstSeries = tsGenerationData.series[tsIndex - 2]; + } + + for (uint dayInTheYear = 0; dayInTheYear < DAYS_PER_YEAR; ++dayInTheYear) + { + assert(dayInTheYear < 366); + assert(lf[dayInTheYear] >= 0.); + assert(lp[dayInTheYear] >= 0.); + + PODOfTheDay = (int)POD[dayInTheYear]; + FODOfTheDay = (int)FOD[dayInTheYear]; + + assert(NOW < Log_size); + NPO_cur -= LOGP[NOW]; + LOGP[NOW] = 0; + AUN += LOG[NOW]; + LOG[NOW] = 0; + + if (NPO_cur > NPOmax[dayInTheYear]) + { + int cible_retour = NPO_cur - (int)NPOmax[dayInTheYear]; + + int cumul_retour = 0; + + for (int index = 1; index < Log_size; ++index) + { + if (cumul_retour == cible_retour) + { + break; + } + + if (LOGP[(NOW + index) % Log_size] + cumul_retour >= cible_retour) + { + LOGP[(NOW + index) % Log_size] -= (cible_retour - cumul_retour); + + LOG[(NOW + index) % Log_size] -= (cible_retour - cumul_retour); + + cumul_retour = cible_retour; + } + else + { + if (LOGP[(NOW + index) % Log_size] > 0) + { + cumul_retour += LOGP[(NOW + index) % Log_size]; + + LOG[(NOW + index) % Log_size] -= LOGP[(NOW + index) % Log_size]; + + LOGP[(NOW + index) % Log_size] = 0; + } + } + } + + AUN += cible_retour; + NPO_cur = (int)NPOmax[dayInTheYear]; + } + + int FOC = 0; + + int POC = 0; + + if (lf[dayInTheYear] > 0. && lf[dayInTheYear] <= FAILURE_RATE_EQ_1) + { + A = rndgenerator.next(); + last = FPOW[dayInTheYear][AUN]; + + if (A > last) + { + cumul = last; + for (int d = 1; d < AUN + 1; ++d) + { + last = ((last * ff[dayInTheYear]) * ((double)(AUN + 1. - d))) / (double)d; + cumul += last; + FOC = d; + if (A <= cumul) + { + break; + } + } + } + } + else + { + FOC = (lf[dayInTheYear] > 0.) ? AUN : 0; + } + + if (lp[dayInTheYear] > 0. && lp[dayInTheYear] <= FAILURE_RATE_EQ_1) + { + int AUN_app = AUN; + if (stock >= 0 && stock <= AUN) + { + AUN_app -= stock; + } + if (stock > AUN) + { + AUN_app = 0; + } + + last = PPOW[dayInTheYear][AUN_app]; + A = rndgenerator.next(); + + if (A > last) + { + cumul = last; + for (int d = 1; d < AUN_app + 1; ++d) + { + last = ((last * pp[dayInTheYear]) * ((double)(AUN_app + 1. - d))) + / (double)d; + cumul += last; + POC = d; + if (A <= cumul) + { + break; + } + } + } + } + else + { + POC = (lp[dayInTheYear] > 0.) ? AUN : 0; + } + + int candidat = POC + stock; + if (0 <= candidat && candidat <= AUN) + { + POC = candidat; + + stock = 0; + } + if (candidat > AUN) + { + stock = candidat - AUN; + + POC = AUN; + } + if (candidat < 0) + { + stock = candidat; + + POC = 0; + } + + if (POC + NPO_cur > NPOmax[dayInTheYear]) + { + stock += POC + NPO_cur - (int)NPOmax[dayInTheYear]; + + POC = (int)NPOmax[dayInTheYear] - NPO_cur; + + NPO_cur = (int)NPOmax[dayInTheYear]; + } + else + { + if (POC + NPO_cur < NPOmin[dayInTheYear]) + { + if (NPOmin[dayInTheYear] - NPO_cur > AUN) + { + stock -= (AUN - POC); + + POC = AUN; + NPO_cur += POC; + } + else + { + stock -= (int)NPOmin[dayInTheYear] - (POC + NPO_cur); + + POC = (int)NPOmin[dayInTheYear] - NPO_cur; + + NPO_cur = (int)NPOmin[dayInTheYear]; + } + } + else + { + NPO_cur += POC; + } + } + + if (tsGenerationData.unitCount == 1) + { + if (POC == 1 && FOC == 1) + { + PPO = 0; + PFO = 0; + MXO = 1; + } + else + { + MXO = 0; + PFO = FOC; + PPO = POC; + } + } + else + { + if (AUN != 0) + { + MXO = POC * FOC / AUN; + PPO = POC - MXO; + PFO = FOC - MXO; + } + else + { + MXO = 0; + PPO = 0; + PFO = 0; + } + } + + AUN = AUN - (PPO + PFO + MXO); + + if (PFO != 0 || MXO != 0) + { + FOD_reel = durationGenerator(f_law, + FODOfTheDay, + f_volatility, + af[dayInTheYear], + bf[dayInTheYear]); + } + if (PPO != 0 || MXO != 0) + { + POD_reel = durationGenerator(p_law, + PODOfTheDay, + p_volatility, + ap[dayInTheYear], + bp[dayInTheYear]); + } + + assert(FUT < Log_size); + if (PFO != 0) + { + FUT = (NOW + FOD_reel) % Log_size; + LOG[FUT] += PFO; + } + if (PPO != 0) + { + FUT = (NOW + POD_reel) % Log_size; + LOG[FUT] += PPO; + LOGP[FUT] = LOGP[FUT] + PPO; + } + if (MXO != 0) + { + FUT = (NOW + POD_reel + FOD_reel) % Log_size; + LOG[FUT] += MXO; + LOGP[FUT] = LOGP[FUT] + MXO; + } + NOW = (NOW + 1) % Log_size; + + AVP[dayInTheYear] = AUN * tsGenerationData.nominalCapacity; + + if (tsIndex > 1) + { + double AVPDayInTheYear = AVP[dayInTheYear]; + for (uint h = 0; h != 24; ++h) + { + dstSeries[hour] = std::round(AVPDayInTheYear * modulation[hour]); + ++hour; + } + } + } + } + + if (derated) + { + tsGenerationData.series.averageTimeseries(); + } +} +} // namespace + +std::vector getAllClustersToGen(const Data::AreaList& areas, + bool globalThermalTSgeneration) +{ + std::vector clusters; + + areas.each( + [&clusters, &globalThermalTSgeneration](const Data::Area& area) + { + for (const auto& cluster: area.thermal.list.all()) + { + if (cluster->doWeGenerateTS(globalThermalTSgeneration)) + { + clusters.push_back(cluster.get()); + } + } + }); + + return clusters; +} + +static void writeResultsToDisk(const Data::Study& study, + Solver::IResultWriter& writer, + const Matrix<>& series, + const std::string& savePath) +{ + if (study.parameters.noOutput) + { + return; + } + + std::string buffer; + series.saveToBuffer(buffer, 0); + writer.addEntryFromBuffer(savePath, buffer); +} + +static void writeResultsToDisk(const Matrix<>& series, const std::filesystem::path& savePath) +{ + std::string buffer; + series.saveToBuffer(buffer, 0); + + std::filesystem::path parentDir = savePath.parent_path(); + if (!std::filesystem::exists(parentDir)) + { + std::filesystem::create_directories(parentDir); + } + Antares::IO::fileSetContent(savePath.string(), buffer); +} + +bool generateThermalTimeSeries(Data::Study& study, + const std::vector& clusters, + Solver::IResultWriter& writer, + const std::string& savePath) +{ + logs.info(); + logs.info() << "Generating the thermal time-series"; + + bool archive = study.parameters.timeSeriesToArchive & Data::timeSeriesThermal; + + auto generator = GeneratorTempData(study, + study.parameters.nbTimeSeriesThermal, + study.runtime->random[Data::seedTsGenThermal]); + + for (auto* cluster: clusters) + { + AvailabilityTSGeneratorData tsGenerationData(cluster); + generator.generateTS(tsGenerationData); + + if (archive) // For compatibilty with in memory thermal TS generation + { + std::string filePath = savePath + SEP + cluster->parentArea->id + SEP + cluster->id() + + ".txt"; + writeResultsToDisk(study, writer, cluster->series.timeSeries, filePath); + } + } + + return true; +} + +// gp : we should try to add const identifiers before args here +bool generateLinkTimeSeries(std::vector& links, + StudyParamsForLinkTS& generalParams, + const std::string& savePath) +{ + logs.info(); + logs.info() << "Generation of links time-series"; + + auto generator = GeneratorTempData(generalParams.derated, + generalParams.nbLinkTStoGenerate, + generalParams.random); + for (auto& link: links) + { + if (!link.hasValidData) + { + logs.error() << "Missing data for link " << link.namesPair.first << "/" + << link.namesPair.second; + return false; + } + + if (link.forceNoGeneration) + { + continue; // Skipping the link + } + + Data::TimeSeriesNumbers fakeTSnumbers; // gp : to quickly get rid of + Data::TimeSeries ts(fakeTSnumbers); + ts.resize(generalParams.nbLinkTStoGenerate, HOURS_PER_YEAR); + + // DIRECT + AvailabilityTSGeneratorData tsConfigDataDirect(link, + ts, + link.modulationCapacityDirect, + link.namesPair.second); + + generator.generateTS(tsConfigDataDirect); + + std::string filePath = savePath + SEP + link.namesPair.first + SEP + link.namesPair.second + + "_direct.txt"; + writeResultsToDisk(ts.timeSeries, filePath); + + // INDIRECT + AvailabilityTSGeneratorData tsConfigDataIndirect(link, + ts, + link.modulationCapacityIndirect, + link.namesPair.second); + + generator.generateTS(tsConfigDataIndirect); + + filePath = savePath + SEP + link.namesPair.first + SEP + link.namesPair.second + + "_indirect.txt"; + writeResultsToDisk(ts.timeSeries, filePath); + } + + return true; +} +} // namespace Antares::TSGenerator diff --git a/src/solver/ts-generator/generator.cpp b/src/solver/ts-generator/generator.cpp new file mode 100644 index 0000000000..3423a9a8ad --- /dev/null +++ b/src/solver/ts-generator/generator.cpp @@ -0,0 +1,79 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "antares/solver/ts-generator/generator.h" + +namespace Antares::TSGenerator +{ + +void ResizeGeneratedTimeSeries(Data::AreaList& areas, Data::Parameters& params) +{ + areas.each( + [¶ms](Data::Area& area) + { + // Load + if (params.timeSeriesToGenerate & Data::timeSeriesLoad) + { + area.load.series.timeSeries.reset(params.nbTimeSeriesLoad, HOURS_PER_YEAR); + } + + // Wind + if (params.timeSeriesToGenerate & Data::timeSeriesWind) + { + area.wind.series.timeSeries.reset(params.nbTimeSeriesWind, HOURS_PER_YEAR); + } + + // Solar + if (params.timeSeriesToGenerate & Data::timeSeriesSolar) + { + area.solar.series.timeSeries.reset(params.nbTimeSeriesSolar, HOURS_PER_YEAR); + } + + // Hydro + if (params.timeSeriesToGenerate & Data::timeSeriesHydro) + { + Data::DataSeriesHydro* const series = area.hydro.series; + const uint nbSeries = params.nbTimeSeriesHydro; + series->resizeTS(nbSeries); + } + + // Thermal + bool globalThermalTSgeneration = params.timeSeriesToGenerate & Data::timeSeriesThermal; + for (const auto& cluster: area.thermal.list.all()) + { + if (cluster->doWeGenerateTS(globalThermalTSgeneration)) + { + cluster->series.timeSeries.reset(params.nbTimeSeriesThermal, HOURS_PER_YEAR); + } + } + }); +} + +void DestroyAll(Data::Study& study) +{ + Destroy(study, (uint)-1); + Destroy(study, (uint)-1); + Destroy(study, (uint)-1); + Destroy(study, (uint)-1); + Destroy(study, (uint)-1); +} + +} // namespace Antares::TSGenerator diff --git a/src/solver/ts-generator/generator.h b/src/solver/ts-generator/generator.h deleted file mode 100644 index 1f3582fb2c..0000000000 --- a/src/solver/ts-generator/generator.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_timeSeries_GENERATOR_H__ -#define __ANTARES_SOLVER_timeSeries_GENERATOR_H__ - -#include -#include -#include -#include -#include -#include "xcast/xcast.h" - -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -/*! -** \brief Regenerate the time-series -*/ -template -bool GenerateTimeSeries(Data::Study& study, uint year, IResultWriter& writer); - -bool GenerateThermalTimeSeries(Data::Study& study, - uint year, - bool globalThermalTSgeneration, - bool refresh, - IResultWriter& writer); - -/*! -** \brief Destroy all TS Generators -*/ -void DestroyAll(Data::Study& study); - -/*! -** \brief Destroy a TS generator if it exists and no longer needed -*/ -template -void Destroy(Data::Study& study, uint year); - -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares - -#include "generator.hxx" - -#endif // __ANTARES_SOLVER_timeSeries_GENERATOR_H__ diff --git a/src/solver/ts-generator/hydro.cpp b/src/solver/ts-generator/hydro.cpp index c554de8852..2d31f08b22 100644 --- a/src/solver/ts-generator/hydro.cpp +++ b/src/solver/ts-generator/hydro.cpp @@ -1,91 +1,72 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include "../simulation/sim_extern_variables_globales.h" -#include "../aleatoire/alea_fonctions.h" -#include -#include +#include + +#include +#include #include -#include "../misc/cholesky.h" -#include "../misc/matrix-dp-make.h" +#include "antares/solver/misc/cholesky.h" +#include "antares/solver/misc/matrix-dp-make.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" using namespace Antares; -using namespace Yuni; -#define SEP IO::Separator +#define SEP Yuni::IO::Separator #define EPSILON ((double)1.0e-9) -namespace Antares -{ -namespace Solver +namespace Antares::TSGenerator { -namespace TSGenerator -{ -static void PreproHydroInitMatrices(Data::Study& study, uint tsCount) -{ - study.areas.each([&](Data::Area& area) { - auto& hydroseries = *(area.hydro.series); - - hydroseries.ror.resize(tsCount, HOURS_PER_YEAR); - hydroseries.storage.resize(tsCount, DAYS_PER_YEAR); - hydroseries.count = tsCount; - }); -} static void PreproRoundAllEntriesPlusDerated(Data::Study& study) { bool derated = study.parameters.derated; - study.areas.each([&](Data::Area& area) { - auto& hydroseries = *(area.hydro.series); + study.areas.each( + [&derated](Data::Area& area) + { + auto& hydroseries = *(area.hydro.series); - hydroseries.ror.roundAllEntries(); - hydroseries.storage.roundAllEntries(); + hydroseries.ror.roundAllEntries(); + hydroseries.storage.roundAllEntries(); - if (derated) - { - hydroseries.ror.averageTimeseries(); - hydroseries.storage.averageTimeseries(); - } - }); + if (derated) + { + hydroseries.ror.averageTimeseries(); + hydroseries.storage.averageTimeseries(); + } + }); } -bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter& writer) +bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, Solver::IResultWriter& writer) { logs.info() << "Generating the hydro time-series"; - Progression::Task progression(study, currentYear, Solver::Progression::sectTSGHydro); + Solver::Progression::Task progression(study, currentYear, Solver::Progression::sectTSGHydro); auto& studyRTI = *(study.runtime); auto& calendar = study.calendar; - uint DIM = 12 * study.areas.size(); + uint DIM = MONTHS_PER_YEAR * study.areas.size(); uint DEM = DIM / 2; Matrix CHSKY; @@ -98,13 +79,13 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter double x, y, z, u; double** nullmatrx = nullptr; - if (1. > MatrixDPMake(CHSKY.entry, - study.preproHydroCorrelation.annual->entry, - B.entry, - nullmatrx, - study.areas.size(), - QCHOLTemp, - true)) + if (1. > Solver::MatrixDPMake(CHSKY.entry, + study.preproHydroCorrelation.annual->entry, + B.entry, + nullmatrx, + study.areas.size(), + QCHOLTemp, + true)) { throw FatalError("TS Generator: Hydro: Invalid correlation matrix"); } @@ -114,7 +95,7 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter for (uint i = 0; i < DIM; i++) { - uint areaIndexI = i / 12; + uint areaIndexI = i / MONTHS_PER_YEAR; auto* prepro = study.areas.byIndex[areaIndexI]->hydro.prepro; auto& corre = CORRE[i]; @@ -123,30 +104,37 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter for (uint j = 0; j < DIM; j++) { - uint areaIndexJ = j / 12; + uint areaIndexJ = j / MONTHS_PER_YEAR; auto* preproJ = study.areas.byIndex[areaIndexJ]->hydro.prepro; - x = Math::Abs(((int)(i % 12) - (int)(j % 12)) / 2.); + x = std::abs(((int)(i % MONTHS_PER_YEAR) - (int)(j % MONTHS_PER_YEAR)) / 2.); corre[j] = annualCorrAreaI[areaIndexJ] * pow(prepro->intermonthlyCorrelation * preproJ->intermonthlyCorrelation, x); - assert(not Math::NaN(corre[j]) and "TS generator Hydro: NaN value detected"); + assert(not std::isnan(corre[j]) and "TS generator Hydro: NaN value detected"); } } { - double r = MatrixDPMake( - CHSKY.entry, CORRE.entry, B.entry, nullmatrx, DIM, QCHOLTemp, true); + double r = Solver::MatrixDPMake(CHSKY.entry, + CORRE.entry, + B.entry, + nullmatrx, + DIM, + QCHOLTemp, + true); if (r < 1.) { logs.warning() << " TS Generator: Hydro correlation matrix was shrinked by " << r; if (r < 0.) + { throw FatalError("TS Generator: r must be positive"); + } } } - Cholesky(CHSKY.entry, B.entry, DIM, QCHOLTemp); + Solver::Cholesky(CHSKY.entry, B.entry, DIM, QCHOLTemp); B.clear(); CORRE.clear(); @@ -156,14 +144,12 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter double* NORM = new double[DIM]; for (uint i = 0; i != DIM; ++i) + { NORM[i] = 0.; + } uint nbTimeseries = study.parameters.nbTimeSeriesHydro; - PreproHydroInitMatrices(study, nbTimeseries); - - long cumul = 0; - for (uint l = 0; l != nbTimeseries; ++l) { for (uint s = 0; s < DEM; ++s) @@ -181,10 +167,10 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter } for (uint i = 0; i < DIM; ++i) { - auto& area = *(study.areas.byIndex[i / 12]); + auto& area = *(study.areas.byIndex[i / MONTHS_PER_YEAR]); auto& prepro = *area.hydro.prepro; auto& series = *area.hydro.series; - auto& ror = series.ror[l]; + auto ror = series.ror[l]; auto& colExpectation = prepro.data[Data::PreproHydro::expectation]; auto& colStdDeviation = prepro.data[Data::PreproHydro::stdDeviation]; @@ -192,33 +178,35 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter auto& colMaxEnergy = prepro.data[Data::PreproHydro::maximumEnergy]; auto& colPOW = prepro.data[Data::PreproHydro::powerOverWater]; - uint month = i % 12; + uint month = i % MONTHS_PER_YEAR; uint realmonth = calendar.months[month].realmonth; - uint daysPerMonth = calendar.months[month].days; - - assert(l < series.ror.width); - assert(not Math::NaN(colPOW[realmonth])); - if (month == 0) - cumul = 0; + assert(l < series.ror.timeSeries.width); + assert(not std::isnan(colPOW[realmonth])); double EnergieHydrauliqueTotaleMensuelle = 0; - if (not Math::Zero(colExpectation[realmonth])) + if (!Utils::isZero(colExpectation[realmonth])) { for (uint j = 0; j < i + 1; ++j) + { EnergieHydrauliqueTotaleMensuelle += CHSKY[i][j] * NORM[j]; + } EnergieHydrauliqueTotaleMensuelle *= colStdDeviation[realmonth]; EnergieHydrauliqueTotaleMensuelle += colExpectation[realmonth]; EnergieHydrauliqueTotaleMensuelle = exp(EnergieHydrauliqueTotaleMensuelle); - assert(not Math::NaN(EnergieHydrauliqueTotaleMensuelle)); + assert(not std::isnan(EnergieHydrauliqueTotaleMensuelle)); if (EnergieHydrauliqueTotaleMensuelle < colMinEnergy[realmonth]) + { EnergieHydrauliqueTotaleMensuelle = colMinEnergy[realmonth]; + } if (EnergieHydrauliqueTotaleMensuelle > colMaxEnergy[realmonth]) + { EnergieHydrauliqueTotaleMensuelle = colMaxEnergy[realmonth]; + } } uint h = calendar.months[month].hours.first; @@ -228,9 +216,11 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter double SIP = 0.; for (uint i = d; i < dend; i++) + { SIP += area.hydro.inflowPattern[0][i]; + } - if (Math::Zero(SIP)) + if (Utils::isZero(SIP)) { logs.fatal() << "Sum of monthly inflow patterns equals zero."; return false; @@ -271,10 +261,8 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter sumInflowPatterns -= dailyInflowPattern; } - assert(not Math::NaN(monthlyStorage) + assert(not std::isnan(monthlyStorage) && "TS generator Hydro: NaN value detected in timeseries"); - - cumul += daysPerMonth; } ++progression; @@ -287,32 +275,36 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter if (study.parameters.noOutput) { for (uint i = 0; i != study.areas.size(); ++i) + { ++progression; + } } else { logs.info() << "Archiving the hydro time-series"; - const int precision = 0; - String output; - study.areas.each([&](const Data::Area& area) { - study.buffer.clear() << "ts-generator" << SEP << "hydro" << SEP << "mc-" - << currentYear << SEP << area.id; - - { - std::string buffer; - area.hydro.series->ror.saveToBuffer(buffer, precision); - output.clear() << study.buffer << SEP << "ror.txt"; - writer.addEntryFromBuffer(output.c_str(), buffer); - } - - { - std::string buffer; - area.hydro.series->storage.saveToBuffer(buffer, precision); - output.clear() << study.buffer << SEP << "storage.txt"; - writer.addEntryFromBuffer(output.c_str(), buffer); - } - ++progression; - }); + study.areas.each( + [&study, ¤tYear, &writer, &progression](const Data::Area& area) + { + const int precision = 0; + Yuni::String output; + study.buffer.clear() << "ts-generator" << SEP << "hydro" << SEP << "mc-" + << currentYear << SEP << area.id; + + { + std::string buffer; + area.hydro.series->ror.timeSeries.saveToBuffer(buffer, precision); + output.clear() << study.buffer << SEP << "ror.txt"; + writer.addEntryFromBuffer(output.c_str(), buffer); + } + + { + std::string buffer; + area.hydro.series->storage.timeSeries.saveToBuffer(buffer, precision); + output.clear() << study.buffer << SEP << "storage.txt"; + writer.addEntryFromBuffer(output.c_str(), buffer); + } + ++progression; + }); } } @@ -321,6 +313,4 @@ bool GenerateHydroTimeSeries(Data::Study& study, uint currentYear, IResultWriter return true; } -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares +} // namespace Antares::TSGenerator diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/generator.h b/src/solver/ts-generator/include/antares/solver/ts-generator/generator.h new file mode 100644 index 0000000000..bfb2901bfa --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/generator.h @@ -0,0 +1,138 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_timeSeries_GENERATOR_H__ +#define __ANTARES_SOLVER_timeSeries_GENERATOR_H__ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "xcast/xcast.h" + +using LinkPair = std::pair; +using LinkPairs = std::vector; + +namespace Antares::TSGenerator +{ + +struct StudyParamsForLinkTS +{ + unsigned int nbLinkTStoGenerate = 1; + bool derated = false; + // gp : we will have a problem with that if seed-tsgen-links not set in + // gp : generaldata.ini. In that case, our default value is wrong. + MersenneTwister random; +}; + +struct LinkTSgenerationParams +{ + LinkPair namesPair; + + unsigned unitCount = 0; + double nominalCapacity = 0; + + double forcedVolatility = 0.; + double plannedVolatility = 0.; + + Data::StatisticalLaw forcedLaw = Data::LawUniform; + Data::StatisticalLaw plannedLaw = Data::LawUniform; + + std::unique_ptr prepro; + + Matrix<> modulationCapacityDirect; + Matrix<> modulationCapacityIndirect; + + bool forceNoGeneration = false; + bool hasValidData = true; +}; + +class AvailabilityTSGeneratorData +{ +public: + explicit AvailabilityTSGeneratorData(Data::ThermalCluster*); + + AvailabilityTSGeneratorData(LinkTSgenerationParams&, + Data::TimeSeries&, + Matrix<>& modulation, + const std::string& name); + + const unsigned& unitCount; + const double& nominalCapacity; + + const double& forcedVolatility; + const double& plannedVolatility; + + Data::StatisticalLaw& forcedLaw; + Data::StatisticalLaw& plannedLaw; + + Data::PreproAvailability* prepro; + + Matrix<>& series; + + Matrix<>::ColumnType& modulationCapacity; + + const std::string& name; +}; + +using listOfLinks = std::vector; + +void ResizeGeneratedTimeSeries(Data::AreaList& areas, Data::Parameters& params); + +/*! +** \brief Regenerate the time-series +*/ +template +bool GenerateTimeSeries(Data::Study& study, uint year, IResultWriter& writer); + +bool generateThermalTimeSeries(Data::Study& study, + const std::vector& clusters, + Solver::IResultWriter& writer, + const std::string& savePath); + +bool generateLinkTimeSeries(std::vector& links, + StudyParamsForLinkTS&, + const std::string& savePath); + +std::vector getAllClustersToGen(const Data::AreaList& areas, + bool globalThermalTSgeneration); + +/*! +** \brief Destroy all TS Generators +*/ +void DestroyAll(Data::Study& study); + +/*! +** \brief Destroy a TS generator if it exists and no longer needed +*/ +template +void Destroy(Data::Study& study, uint year); + +} // namespace Antares::TSGenerator + +#include "generator.hxx" + +#endif // __ANTARES_SOLVER_timeSeries_GENERATOR_H__ diff --git a/src/solver/ts-generator/generator.hxx b/src/solver/ts-generator/include/antares/solver/ts-generator/generator.hxx similarity index 75% rename from src/solver/ts-generator/generator.hxx rename to src/solver/ts-generator/include/antares/solver/ts-generator/generator.hxx index acf699e4b7..6596a4f7ab 100644 --- a/src/solver/ts-generator/generator.hxx +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/generator.hxx @@ -1,41 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_SOLVER_timeSeries_GENERATOR_HXX__ #define __ANTARES_SOLVER_timeSeries_GENERATOR_HXX__ -#include "../aleatoire/alea_fonctions.h" #include -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator +namespace Antares::TSGenerator { + // forward declaration // Hydro - see hydro.cpp bool GenerateHydroTimeSeries(Data::Study& study, uint year, IResultWriter& writer); @@ -97,7 +87,9 @@ void Destroy(Data::Study& study, uint year) auto* xcast = reinterpret_cast( study.cacheTSGenerator[Data::TimeSeriesBitPatternIntoIndex::value]); if (not xcast) + { return; + } // releasing auto& parameters = study.parameters; @@ -149,17 +141,6 @@ void Destroy(Data::Study& study, uint year) } } -inline void DestroyAll(Data::Study& study) -{ - Solver::TSGenerator::Destroy(study, (uint)-1); - Solver::TSGenerator::Destroy(study, (uint)-1); - Solver::TSGenerator::Destroy(study, (uint)-1); - Solver::TSGenerator::Destroy(study, (uint)-1); - Solver::TSGenerator::Destroy(study, (uint)-1); -} - -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares +} // namespace Antares::TSGenerator #endif // __ANTARES_SOLVER_timeSeries_GENERATOR_HXX__ diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/law.h b/src/solver/ts-generator/include/antares/solver/ts-generator/law.h new file mode 100644 index 0000000000..429ca02f15 --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/law.h @@ -0,0 +1,10 @@ +#pragma once + +namespace Antares::Data +{ +enum StatisticalLaw +{ + LawUniform, + LawGeometric +}; +} // namespace Antares::Data diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/prepro.h b/src/solver/ts-generator/include/antares/solver/ts-generator/prepro.h new file mode 100644 index 0000000000..4d93f56f8a --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/prepro.h @@ -0,0 +1,119 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_H__ +#define __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_H__ + +#include + +#include +#include +#include +#include + +namespace Antares::Data +{ +/*! +** \brief Thermal +*/ +class PreproAvailability +{ +public: + enum + { + //! FO Duration (Forced outage Duration - Duree moyenne d'indisponibilite fortuite) + foDuration = 0, + //! PO Duration (Planned outage Duration - Duree moyenne d'indisponibilite programmee) + poDuration, + //! FO Rate (Forced outage Rate - Taux moyen d'indisponibilite fortuite) + foRate, + //! PO Rate (Planned outage Rate - Taux moyen d'indisponibilite programmee) + poRate, + //! NPO min (nombre minimal de groupes en maintenance) + npoMin, + //! NPO max (nombre maximal de groupes en maintenance) + npoMax, + // max + preproAvailabilityMax, + }; + + //! \name Constructor + //@{ + /*! + ** \brief Default constructor + */ + explicit PreproAvailability(const YString& id, unsigned int unitCount); + //@} + + bool forceReload(bool reload) const; + + void markAsModified() const; + + /*! + ** \brief Reset all values to their default ones + */ + void reset(); + + //! Copy data from another struct + void copyFrom(const PreproAvailability& rhs); + + /*! + ** \brief Load settings for the thermal prepro from a folder + ** + ** \param folder The source folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool loadFromFolder(Study& study, const AnyString& folder); + + /*! + ** \brief Validate most settings against min/max rules + */ + bool validate() const; + + /*! + ** \brief Save settings used by the thermal prepro to a folder + ** + ** \param folder The targer folder + ** \return A non-zero value if the operation succeeded, 0 otherwise + */ + bool saveToFolder(const AnyString& folder) const; + + /*! + ** \brief Get the amount of memory used by the class + */ + uint64_t memoryUsage() const; + + /*! + ** \brief Normalize NPO max and check for consistency + ** + ** This method should only be used by the solver + */ + bool normalizeAndCheckNPO(); + + //! All {FO,PO}{Duration,Rate} annual values + // max x DAYS_PER_YEAR + Matrix<> data; + // Parent thermal cluster + YString id; + unsigned int unitCount; +}; // class PreproAvailability +} // namespace Antares::Data + +#endif // __ANTARES_LIBS_STUDY_PARTS_THERMAL_PREPRO_HXX__ diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/constants.h b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/constants.h new file mode 100644 index 0000000000..4873e049a9 --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/constants.h @@ -0,0 +1,48 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_CONSTANTS_H__ +#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_CONSTANTS_H__ + +//! Precision sur la factorisation des matrices +#define EPSIMIN ((float)1.0e-9) +//! Precision sur les verifications des produits LtL +#define EPSIMAX ((float)1.0e-3) + +//! Limite d'approche des bornes des processus +#define EPSIBOR ((float)1.0e-4) + +//! Infini + +#define INFINIP ((float)1.0e+9) +//! Infini - +#define INFININ ((float)-1.0e+9) + +// 1+ PETIT * theta +// 1 dans le developpement limite des correlations spatiales instantanees +// PETIT * theta << 1 pour le plafonnement du terme lineaire des dXt +// 2 * sqrt(PETIT) * theta << 1 pour le plafonnement du terme diffusion des dXt +#define PETIT ((float)1e-2) + +//! A la limite superieure des lois de Weibull la fonction de repartition vaut 1- NEGLI_WEIB +#define NEGLI_WEIB ((double)1.0e-4) +//! A la limite superieure des lois Gamma la fonction de repartition vaut 1- NEGLI_GAM +#define NEGLI_GAMM ((double)1.0e-4) + +#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_CONSTANTS_H__ diff --git a/src/solver/ts-generator/xcast/math.hxx b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/math.hxx similarity index 90% rename from src/solver/ts-generator/xcast/math.hxx rename to src/solver/ts-generator/include/antares/solver/ts-generator/xcast/math.hxx index 42c5105786..df8cca40d3 100644 --- a/src/solver/ts-generator/xcast/math.hxx +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/math.hxx @@ -1,43 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include + #include -#include -#include + #include -#include "xcast.h" +#include +#include "antares/solver/ts-generator/xcast/xcast.h" + #include "constants.h" using namespace Yuni; namespace Antares { -namespace Solver -{ namespace TSGenerator { namespace XCast @@ -193,7 +188,7 @@ static float diffusion(float a, float b, float g, float d, int l, float t, float // Warning: // On suppose ici que d a ete correctement initialise avec d=gamma_euler(1+1/a) // - assert(!Math::Zero(b) && "division by zero"); + assert(b != 0 && "division by zero"); const double v = pow(x / b, a); const double w = exp(v); @@ -246,7 +241,7 @@ static float diffusion(float a, float b, float g, float d, int l, float t, float for (k = 0; k < N; ++k) estim_aij += L[i][k] * L[j][k]; - if (Math::Abs(estim_aij - A[i][j]) > EPSIMAX) + if (std::abs(estim_aij - A[i][j]) > EPSIMAX) return false; } } @@ -318,7 +313,9 @@ static float maxiDiffusion(float a, float b, float g, float d, int l, float t) float m = diffusion(a, b, g, d, l, t, x); float y = diffusion(a, b, g, d, l, t, maximum(a, b, g, d, l)); if (y > m) + { m = y; + } if (a > 1.f) { x = (a - 1.f) / a; @@ -326,7 +323,9 @@ static float maxiDiffusion(float a, float b, float g, float d, int l, float t) x *= b; y = diffusion(a, b, g, d, l, t, x); if (y > m) + { m = y; + } } return m; } @@ -344,5 +343,4 @@ static float maxiDiffusion(float a, float b, float g, float d, int l, float t) } // namespace XCast } // namespace TSGenerator -} // namespace Solver } // namespace Antares diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/predicate.hxx b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/predicate.hxx new file mode 100644 index 0000000000..8ec42e2846 --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/predicate.hxx @@ -0,0 +1,168 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_TS_GENERATOR_XCAST_PREDICATE_HXX__ +#define __SOLVER_TS_GENERATOR_XCAST_PREDICATE_HXX__ + +#include + +#include + +#include +#include +#include "antares/study/parts/load/prepro.h" + +namespace Antares +{ +namespace TSGenerator +{ +namespace Predicate +{ +class Wind final +{ +public: + static bool preproDataIsReader(const Data::Area& area) + { + return area.wind.prepro != NULL; + } + + static const char* timeSeriesName() + { + return "wind"; + } + + bool accept(const Data::Area& area) const + { + assert(area.wind.prepro != NULL); + return !Utils::isZero(area.wind.prepro->xcast.capacity); + } + + Data::TimeSeries::TS& matrix(Data::Area& area) const + { + return area.wind.series.timeSeries; + } + + Data::XCast& xcastData(Data::Area& area) const + { + assert(area.wind.prepro != NULL); + return area.wind.prepro->xcast; + } + + static const Data::Correlation& correlation(const Data::Study& study) + { + return study.preproWindCorrelation; + } + + uint timeSeriesToGenerate(const Data::Study& study) const + { + return study.parameters.nbTimeSeriesWind; + } + +}; // class Wind + +class Load final +{ +public: + static bool preproDataIsReader(const Data::Area& area) + { + return area.load.prepro != NULL; + } + + static const char* timeSeriesName() + { + return "load"; + } + + bool accept(const Data::Area& area) const + { + assert(area.load.prepro != NULL); + return !Utils::isZero(area.load.prepro->xcast.capacity); + } + + Data::TimeSeries::TS& matrix(Data::Area& area) const + { + return area.load.series.timeSeries; + } + + Data::XCast& xcastData(Data::Area& area) const + { + assert(area.load.prepro != NULL); + return area.load.prepro->xcast; + } + + static const Data::Correlation& correlation(const Data::Study& study) + { + return study.preproLoadCorrelation; + } + + uint timeSeriesToGenerate(const Data::Study& study) const + { + return study.parameters.nbTimeSeriesLoad; + } + +}; // class Load + +class Solar final +{ +public: + static bool preproDataIsReader(const Data::Area& area) + { + return area.solar.prepro != NULL; + } + + static const char* timeSeriesName() + { + return "solar"; + } + + bool accept(const Data::Area& area) const + { + assert(area.solar.prepro != NULL); + return !Utils::isZero(area.solar.prepro->xcast.capacity); + } + + Data::TimeSeries::TS& matrix(Data::Area& area) const + { + return area.solar.series.timeSeries; + } + + Data::XCast& xcastData(Data::Area& area) const + { + assert(area.solar.prepro != NULL); + return area.solar.prepro->xcast; + } + + static const Data::Correlation& correlation(const Data::Study& study) + { + return study.preproSolarCorrelation; + } + + uint timeSeriesToGenerate(const Data::Study& study) const + { + return study.parameters.nbTimeSeriesSolar; + } + +}; // class Solar + +} // namespace Predicate +} // namespace TSGenerator +} // namespace Antares + +#endif // __SOLVER_TS_GENERATOR_XCAST_PREDICATE_HXX__ diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/studydata.h b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/studydata.h new file mode 100644 index 0000000000..81c42be09a --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/studydata.h @@ -0,0 +1,102 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_H__ +#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_H__ + +#include + +#include +#include + +namespace Antares::TSGenerator::XCast +{ +class StudyData final +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief + */ + StudyData(); + /*! + ** \brief Destructor + */ + ~StudyData(); + //@} + + /*! + ** \brief Load all informations from a study and a predicate + ** + ** Example of a predicate: + ** \code + ** struct WindPredicate + ** { + ** bool operator () (const Area&) const + ** { + ** return true; + ** } + ** + ** Data::XCast* retrieveXCastData(const Area* area) const + ** { + ** return area->wind.prepro->xcast; + ** } + ** }; + ** \endcode + ** + ** All areas excluded from the list will see their time-series matrix reset to 1x8760. + ** + ** \param study A study + ** \param predicate Predicate to determine whether the specified object meets some criteria + ** and to retrive some specific data from the area + */ + template + void loadFromStudy(Data::Study& study, + const Data::Correlation& correlation, + PredicateT& predicate); + +public: + //! List of all areas (sub-set of the complete list) + Data::Area::Vector localareas; + //! Correlation coefficients for each month + const Matrix* correlation[12]; + /*! + ** \brief Correlation mode (monthly / annual) + ** + ** \internal This value is a copy from the correlation data and + ** it's used to properly delete the coefficient matrices. + */ + Data::Correlation::Mode mode; + +private: + //! Delete + //! Rebuild data from our own area list + void reloadDataFromAreaList(const Data::Correlation& correlation); + + void prepareMatrix(Matrix& m, const Matrix& source) const; + +}; // class StudyData + +} // namespace Antares::TSGenerator::XCast + +#include "studydata.hxx" + +#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_H__ diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/studydata.hxx b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/studydata.hxx new file mode 100644 index 0000000000..466dc94aae --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/studydata.hxx @@ -0,0 +1,56 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_HXX__ +#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_HXX__ + +#include + +#include +#include +#include + +namespace Antares::TSGenerator::XCast +{ +template +void StudyData::loadFromStudy(Data::Study& study, + const Data::Correlation& correlation, + PredicateT& predicate) +{ + // clear our list of areas + localareas.clear(); + + // We will rebuild it using the predicate + for (auto i = study.areas.begin(); i != study.areas.end(); ++i) + { + auto& area = *(i->second); + if (predicate.accept(area)) + { + // XCast will have to use this area + logs.info() << " Added the area '" << area.name << "'"; + localareas.push_back(&area); + } + } + reloadDataFromAreaList(correlation); +} + +} // namespace Antares::TSGenerator::XCast + +#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_HXX__ diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/xcast.h b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/xcast.h new file mode 100644 index 0000000000..55bb128e85 --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/xcast.h @@ -0,0 +1,259 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_H__ +#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_H__ + +#include +#include + +#include +#include +#include +#include +#include "antares/solver/ts-generator/xcast/studydata.h" + +using namespace Antares::Solver; + +namespace Antares +{ +namespace TSGenerator +{ +namespace XCast +{ +/*! +** \brief XCast Generator for Load, Wind and solar timeseries +** +** \see predicate.hxx for specializations +*/ +class XCast final: private Yuni::NonCopyable +{ +public: + /*! + ** \brief Compute + */ + static double GammaEuler(double z); + + /*! + ** \brief Calcul de la forme inférieure de la fonction gamma incomplete + ** + ** Calcul de la forme inférieure de la fonction gamma incomplete (s,z) = somme{0;z} + *t^(s-1)exp(-t)dt + ** On utilise un developpement en serie jusqu'à l'ordre 30, ce qui garantit + ** une precision suffisante dans le domaine 1 <= s <= 2 et 0 <= z <= 10 + ** \warning Dans les lois de Weibull, la valeur maximale que z peut atteindre + ** est Log(1 / NEGLI_WEIB). Il faut donc regler NEGLI_WEIB en conséquence + ** + */ + static double GammaInc(double s, double z); + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + XCast(Data::Study& study, Data::TimeSeriesType ts, IResultWriter& writer); + /*! + ** \brief Destructor + */ + ~XCast(); + //@} + + //! \name Loading + //@{ + /*! + ** \brief initialize all XCast indicators from the current simulation parameters + */ + template + void loadFromStudy(const Data::Correlation& correlation, PredicateT& predicate); + //@} + + /*! + ** \brief Run the TS Generator + */ + bool run(); + +public: + //! The current study + Data::Study& study; + + //! The current year + uint year; + //! The time-series type + const Data::TimeSeriesType timeSeriesType; + + //! The random generator to use + MersenneTwister* random; + +private: + void allocateTemporaryData(); + void destroyTemporaryData(); + + template + void updateMissingCoefficients(PredicateT& predicate); + template + bool runWithPredicate(PredicateT& predicate, Progression::Task& progression); + + /*! + ** \brief Export all time-series for each process into the output folder + */ + template + void exportTimeSeriesToTheOutput(Progression::Task& progression, PredicateT& predicate); + + /*! + ** \brief Perform the generation of the time-series on a single day for all processes + ** + ** Ce code effectue dans l'ordre : + ** a) elaboration de series de valeurs horaires X(a) de processus "purs" + ** definis par A,B,G,D,T,L,C + ** b) transformation de ces series en X(b) par un lissage en moyenne glissante + ** defini par M (permet de regler l'autocorrelation a court terme) + ** c) Modulation des series en X(c) en fonction de coefficients FO de + ** variations quotidienne des valeurs horaires + ** d) Ecretement (haut, bas) de la serie en X(d) de façon a la contenir dans + ** des bornes imposees MI,MA + ** + ** ATTENTION : les 4 étapes sont enchainees pour chaque point horaire. + ** On ne passe donc pas de t à t+1 en faisant + ** X(a)(t) -> X(a)(t+1) + ** X(b)(t) -> X(b)(t+1) + ** + ** Le processus X(a) peut donc s'ecarter de sa loi marginale et de son + ** autocorrelation theoriques si les modulations FO et les bornes MI,MA + ** conduisent frequemment a rectifier sa trajectoire. + ** Ce cas peut se presenter si les bornes d'ecretement MI,MA sont egales a + ** G,D (voire plus etroites) et si les modulations FO sont marquees. + ** + ** + ** LOIS MODELISEES + ** regle generale pour tous les types de loi : t>=0 + ** regles particulieres selon les types de lois : + ** + ** \code + ** code loi a b g + *d autres contraintes Loi marginale + ** 1 quelconque quelconque g> INFININ/2 d0 b>0 g> INFININ/2 d=0 g= a-6*b d= a+6*b Normale d'espérance a et + *d'écart-type b + ** 4 a>=1 b>0 g> INFININ/2 d= gamma_euler(1+1/a) + *Weibull de forme a, d'échelle b et définie pour x>g + ** 5 a>=1 b>0 g> INFININ/2 d non défini + *Gamma de forme a, d'échelle b et définie pour x>g + ** \endcode + */ + bool generateValuesForTheCurrentDay(); + + template + void applyTransferFunction(PredicateT& predicate); + + //! Tirage de deux variables normales centrees et reduites + void normal(float& x, float& y); + +private: + //! The number of time-series + uint nbTimeseries_; + + //! Some data after transformation + StudyData pData; + + //! The correlation matrix for the current month + const Matrix* pCorrMonth; + + bool pNeverInitialized; + uint Nombre_points_intermediaire; + + //! True when starting a new month (some data may have to be reinitialized) + bool pNewMonth; + + // Statistics + //! The number of computed points a day + uint pComputedPointCount; + uint pNDPMatrixCount; + uint pLevellingCount; + + bool pAccuracyOnCorrelation; + bool All_normal; // all processes are Normal + + float* A; // les variables de A à CO sont des vues de ALPH à CORR pour un mois particulier + float* B; + float* G; + float* D; + int* M; + float* T; + Data::XCast::Distribution* L; + bool* BO; + float* MA; + float* MI; + float** FO; // contrainte : FO >=0 + + float STEP; + float SQST; + float* POSI; + float** CORR; + float* MAXI; + float* MINI; + float* Presque_maxi; + float* Presque_mini; + float* ESPE; + float* STDE; + float** LISS; + float** DATL; + + float* DIFF; + float* TREN; + float* WIEN; + float* BROW; + + float* BASI; // used only if all processes are Normal + float* ALPH; // used only if all processes are Normal + float* BETA; // used only if all processes are Normal + + float** Triangle_reference; + float** Triangle_courant; + float** Carre_reference; + float** Carre_courant; + + float* D_COPIE; + + float** DATA; + + // cholesky temporary data + float* pQCHOLTotal; + + //! + bool* pUseConversion; + + //! Name of the current timeseries + Yuni::CString<32, false> pTSName; + + IResultWriter& pWriter; +}; // class XCast + +} // namespace XCast +} // namespace TSGenerator +} // namespace Antares + +#include "xcast.hxx" + +#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_H__ diff --git a/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/xcast.hxx b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/xcast.hxx new file mode 100644 index 0000000000..919c79fc90 --- /dev/null +++ b/src/solver/ts-generator/include/antares/solver/ts-generator/xcast/xcast.hxx @@ -0,0 +1,40 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_HXX__ +#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_HXX__ + +namespace Antares +{ +namespace TSGenerator +{ +namespace XCast +{ +template +inline void XCast::loadFromStudy(const Data::Correlation& correlation, PredicateT& predicate) +{ + pData.template loadFromStudy(study, correlation, predicate); +} + +} // namespace XCast +} // namespace TSGenerator +} // namespace Antares + +#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_HXX__ diff --git a/src/solver/ts-generator/prepro.cpp b/src/solver/ts-generator/prepro.cpp new file mode 100644 index 0000000000..b093d4b837 --- /dev/null +++ b/src/solver/ts-generator/prepro.cpp @@ -0,0 +1,222 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include +#include +#include +#include + +#include +#include +#include "antares/study/study.h" + +using namespace Yuni; + +#define SEP IO::Separator + +namespace Antares::Data +{ +PreproAvailability::PreproAvailability(const YString& id, unsigned int unitCount): + id(id), + unitCount(unitCount) +{ +} + +void PreproAvailability::copyFrom(const PreproAvailability& rhs) +{ + id = rhs.id; + unitCount = rhs.unitCount; + data = rhs.data; + rhs.data.unloadFromMemory(); +} + +bool PreproAvailability::saveToFolder(const AnyString& folder) const +{ + if (IO::Directory::Create(folder)) + { + String buffer; + buffer.clear() << folder << SEP << "data.txt"; + return data.saveToCSVFile(buffer, /*decimal*/ 6); + } + return false; +} + +bool PreproAvailability::loadFromFolder(Study& study, const AnyString& folder) +{ + auto& buffer = study.bufferLoadingTS; + + buffer.clear() << folder << SEP << "data.txt"; + + // standard loading + return data.loadFromCSVFile(buffer, + preproAvailabilityMax, + DAYS_PER_YEAR, + Matrix<>::optFixedSize, + &study.dataBuffer); +} + +bool PreproAvailability::validate() const +{ + const auto& colFoRate = data[foRate]; + const auto& colPoRate = data[poRate]; + const auto& colFoDuration = data[foDuration]; + const auto& colPoDuration = data[poDuration]; + const auto& colNPOMin = data[npoMin]; + const auto& colNPOMax = data[npoMax]; + uint errors = 0; + + for (uint i = 0; i != DAYS_PER_YEAR; ++i) + { + double foRate = colFoRate[i]; + double poRate = colPoRate[i]; + double foDuration = colFoDuration[i]; + double poDuration = colPoDuration[i]; + double cNPOMin = colNPOMin[i]; + double cNPOMax = colNPOMax[i]; + + if (cNPOMin < 0) + { + logs.error() << "Prepro: " << id << ": NPO min can not be negative (line:" << (i + 1) + << ")"; + ++errors; + } + if (cNPOMax < 0) + { + logs.error() << "Prepro: " << id << ": NPO max can not be negative (line:" << (i + 1) + << ")"; + ++errors; + } + if (cNPOMin > cNPOMax) + { + logs.error() << "Prepro: " << id + << ": NPO max must be greater or equal to NPO min (line:" << (i + 1) + << ")"; + ++errors; + } + + if (foRate < 0. || foRate > 1.) + { + logs.error() << "Prepro: " << id << ": invalid value for FO rate (line:" << (i + 1) + << ")"; + ++errors; + } + + if (poRate < 0. || poRate > 1.) + { + logs.error() << "Prepro: " << id << ": invalid value for PO rate (line:" << (i + 1) + << ")"; + ++errors; + } + + if (foDuration < 1. || foDuration > 365.) + { + logs.error() << "Prepro: " << id << ": invalid value for FO Duration (line:" << (i + 1) + << ")"; + ++errors; + } + if (poDuration < 1. || poDuration > 365.) + { + logs.error() << "Prepro: " << id << ": invalid value for PO Duration (line:" << (i + 1) + << ")"; + ++errors; + } + + if (errors > 30) + { + logs.error() << "Prepro: " << id << ": too many errors. skipping"; + break; + } + } + return errors == 0; +} + +bool PreproAvailability::forceReload(bool reload) const +{ + return data.forceReload(reload); +} + +void PreproAvailability::markAsModified() const +{ + data.markAsModified(); +} + +uint64_t PreproAvailability::memoryUsage() const +{ + return sizeof(PreproAvailability); +} + +void PreproAvailability::reset() +{ + data.reset(preproAvailabilityMax, DAYS_PER_YEAR, true); + + auto& colFoDuration = data[foDuration]; + auto& colPoDuration = data[poDuration]; + + for (uint i = 0; i != DAYS_PER_YEAR; ++i) + { + colFoDuration[i] = 1.; + colPoDuration[i] = 1.; + } +} + +bool PreproAvailability::normalizeAndCheckNPO() +{ + // alias to our data columns + auto& columnNPOMax = data[npoMax]; + auto& columnNPOMin = data[npoMin]; + // errors management + uint errors = 0; + uint maxErrors = 10; + + // Flag to determine whether the column NPO max has been normalized or not + bool normalized = false; + + for (uint y = 0; y != data.height; ++y) + { + if (columnNPOMax[y] > unitCount) + { + columnNPOMax[y] = unitCount; + normalized = true; + } + + if (columnNPOMin[y] > columnNPOMax[y] && ++errors < maxErrors) + { + logs.error() << id << ": NPO min can not be greater than NPO max (hour: " << (y + 1) + << ", npo-min: " << columnNPOMin[y] << ", npo-max: " << columnNPOMax[y] + << ')'; + } + } + + if (errors >= maxErrors) + { + logs.error() << id << ": too many errors. skipping (total: " << errors << ')'; + } + + if (normalized) + { + logs.info() << " NPO max for entity '" << id << "' has been normalized"; + } + + data.markAsModified(); + return (0 == errors); +} + +} // namespace Antares::Data diff --git a/src/solver/ts-generator/thermal.cpp b/src/solver/ts-generator/thermal.cpp deleted file mode 100644 index 9196cfe489..0000000000 --- a/src/solver/ts-generator/thermal.cpp +++ /dev/null @@ -1,652 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include - -#include -#include -#include - -#include -#include -#include - -#include "../simulation/simulation.h" -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include "../simulation/sim_extern_variables_globales.h" -#include "../aleatoire/alea_fonctions.h" - -using namespace Yuni; - -#define SEP IO::Separator - -#define FAILURE_RATE_EQ_1 0.999 - -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace -{ -class GeneratorTempData final -{ -public: - GeneratorTempData(Data::Study& study, - Solver::Progression::Task& progr, - IResultWriter& writer); - - void prepareOutputFoldersForAllAreas(uint year); - - void operator()(Data::Area& area, Data::ThermalCluster& cluster); - -public: - Data::Study& study; - - bool archive; - - uint currentYear; - - uint nbThermalTimeseries; - - bool derated; - -private: - void writeResultsToDisk(const Data::Area& area, const Data::ThermalCluster& cluster); - - int durationGenerator(Data::ThermalLaw law, int expec, double volat, double a, double b); - - template - void prepareIndispoFromLaw(Data::ThermalLaw law, - double volatility, - double A[], - double B[], - const T& duration); - -private: - const uint nbHoursPerYear = HOURS_PER_YEAR; - const uint daysPerYear = DAYS_PER_YEAR; - - MersenneTwister& rndgenerator; - - double AVP[366]; - enum - { - Log_size = 4000 - }; - int LOG[Log_size]; - int LOGP[Log_size]; - - double lf[366]; - double lp[366]; - double ff[366]; - double pp[366]; - double af[366]; - double ap[366]; - double bf[366]; - double bp[366]; - double FPOW[366][102]; - double PPOW[366][102]; - - String pTempFilename; - Solver::Progression::Task& pProgression; - IResultWriter& pWriter; -}; - -GeneratorTempData::GeneratorTempData(Data::Study& study, - Solver::Progression::Task& progr, - IResultWriter& writer) : - study(study), - rndgenerator(study.runtime->random[Data::seedTsGenThermal]), - pProgression(progr), - pWriter(writer) -{ - auto& parameters = study.parameters; - - archive = (0 != (parameters.timeSeriesToArchive & Data::timeSeriesThermal)); - - nbThermalTimeseries = parameters.nbTimeSeriesThermal; - - derated = parameters.derated; -} - -void GeneratorTempData::writeResultsToDisk(const Data::Area& area, - const Data::ThermalCluster& cluster) -{ - if (not study.parameters.noOutput) - { - pTempFilename.reserve(study.folderOutput.size() + 256); - - pTempFilename.clear() << "ts-generator" << SEP << "thermal" << SEP << "mc-" << currentYear - << SEP << area.id << SEP << cluster.id() << ".txt"; - - assert(cluster.series); - enum - { - precision = 0 - }; - - std::string buffer; - cluster.series->timeSeries.saveToBuffer(buffer, precision); - - pWriter.addEntryFromBuffer(pTempFilename.c_str(), buffer); - } - - ++pProgression; -} - -template -void GeneratorTempData::prepareIndispoFromLaw(Data::ThermalLaw law, - double volatility, - double A[], - double B[], - const T& duration) -{ - switch (law) - { - case Data::thermalLawUniform: - { - for (uint d = 0; d < daysPerYear; ++d) - { - double D = (double)duration[d]; - double xtemp = volatility * (D - 1.); - A[d] = D - xtemp; - B[d] = 2. * xtemp + 1.; - } - break; - } - case Data::thermalLawGeometric: - { - for (uint d = 0; d < daysPerYear; ++d) - { - double D = (double)duration[d]; - double xtemp = volatility * volatility * D * (D - 1.); - if (xtemp != 0) - { - B[d] = 4. * xtemp + 1.; - B[d] = sqrt(B[d]) - 1.; - B[d] /= 2. * xtemp; - A[d] = D - 1. / B[d]; - B[d] = log(1. - B[d]); - B[d] = 1. / B[d]; - } - else - { - B[d] = 1.; - A[d] = 1.; - } - } - break; - } - } -} - -int GeneratorTempData::durationGenerator(Data::ThermalLaw law, - int expec, - double volat, - double a, - double b) -{ - if (volat == 0 or expec == 1) - return expec; - - double rndnumber = rndgenerator.next(); - switch (law) - { - case Data::thermalLawUniform: - { - return (int(a + rndnumber * b)); - } - case Data::thermalLawGeometric: - { - int resultat = (1 + int(a + (b)*log(rndnumber))); - enum - { - limit = Log_size / 2 - 1 - }; - assert(limit == 1999); - return (resultat <= limit) ? resultat : limit; - } - } - assert(false and "return is missing"); - return 0; -} - -void GeneratorTempData::operator()(Data::Area& area, Data::ThermalCluster& cluster) -{ - if (not cluster.prepro) - { - logs.error() - << "Cluster: " << area.name << '/' << cluster.name() - << ": The timeseries will not be regenerated. All data related to the ts-generator for " - << "'thermal' have been released."; - return; - } - - assert(cluster.series); - assert(cluster.prepro); - - if (0 == cluster.unitCount or 0 == cluster.nominalCapacity) - { - cluster.series->timeSeries.reset(1, nbHoursPerYear); - - if (archive) - writeResultsToDisk(area, cluster); - return; - } - - cluster.series->timeSeries.resize(nbThermalTimeseries, nbHoursPerYear); - - const auto& preproData = *(cluster.prepro); - - int AUN = (int)cluster.unitCount; - - auto& FOD = preproData.data[Data::PreproThermal::foDuration]; - - auto& POD = preproData.data[Data::PreproThermal::poDuration]; - - auto& FOR = preproData.data[Data::PreproThermal::foRate]; - - auto& POR = preproData.data[Data::PreproThermal::poRate]; - - auto& NPOmin = preproData.data[Data::PreproThermal::npoMin]; - - auto& NPOmax = preproData.data[Data::PreproThermal::npoMax]; - - double f_volatility = cluster.forcedVolatility; - - double p_volatility = cluster.plannedVolatility; - - auto f_law = cluster.forcedLaw; - - auto p_law = cluster.plannedLaw; - - int FODOfTheDay; - int PODOfTheDay; - - int FOD_reel = 0; - int POD_reel = 0; - - for (uint d = 0; d < daysPerYear; ++d) - { - PODOfTheDay = (int)POD[d]; - FODOfTheDay = (int)FOD[d]; - - lf[d] = FOR[d] / (FOR[d] + (FODOfTheDay) * (1. - FOR[d])); - lp[d] = POR[d] / (POR[d] + (PODOfTheDay) * (1. - POR[d])); - - if (0. < lf[d] and lf[d] < lp[d]) - lf[d] *= (1. - lp[d]) / (1. - lf[d]); - - if (0. < lp[d] and lp[d] < lf[d]) - lp[d] *= (1. - lf[d]) / (1. - lp[d]); - - double a = 0.; - double b = 0.; - - if (lf[d] <= FAILURE_RATE_EQ_1) - { - a = 1. - lf[d]; - ff[d] = lf[d] / a; - } - - if (lp[d] <= FAILURE_RATE_EQ_1) - { - b = 1. - lp[d]; - pp[d] = lp[d] / b; - } - - for (uint k = 0; k != cluster.unitCount + 1; ++k) - { - FPOW[d][k] = pow(a, (double)k); - PPOW[d][k] = pow(b, (double)k); - } - } - - prepareIndispoFromLaw(f_law, f_volatility, af, bf, FOD); - prepareIndispoFromLaw(p_law, p_volatility, ap, bp, POD); - - (void)::memset(AVP, 0, sizeof(AVP)); - (void)::memset(LOG, 0, sizeof(LOG)); - (void)::memset(LOGP, 0, sizeof(LOGP)); - - int MXO = 0; - - int PPO = 0; - - int PFO = 0; - - int NOW = 0; - - int FUT = 0; - - int NPO_cur = 0; - - int stock = 0; - - double A = 0; - double cumul = 0; - double last = 0; - - auto& modulation = cluster.modulation[Data::thermalModulationCapacity]; - - Antares::Data::DataSeriesCommon::SingleYear dstSeries = nullptr; - - const uint tsCount = nbThermalTimeseries + 2; - for (uint tsIndex = 0; tsIndex != tsCount; ++tsIndex) - { - uint hour = 0; - - if (tsIndex > 1) - dstSeries = cluster.series->timeSeries[tsIndex - 2]; - - for (uint dayInTheYear = 0; dayInTheYear < daysPerYear; ++dayInTheYear) - { - assert(AUN <= 100 and "Thermal Prepro: AUN is out of bounds (>=100)"); - assert(dayInTheYear < 366); - assert(not(lf[dayInTheYear] < 0.)); - assert(not(lp[dayInTheYear] < 0.)); - - PODOfTheDay = (int)POD[dayInTheYear]; - FODOfTheDay = (int)FOD[dayInTheYear]; - - assert(NOW < Log_size); - NPO_cur -= LOGP[NOW]; - LOGP[NOW] = 0; - AUN += LOG[NOW]; - LOG[NOW] = 0; - - if (NPO_cur > NPOmax[dayInTheYear]) - { - int cible_retour = NPO_cur - (int)NPOmax[dayInTheYear]; - - int cumul_retour = 0; - - for (int index = 1; index < Log_size; ++index) - { - if (cumul_retour == cible_retour) - break; - - if (LOGP[(NOW + index) % Log_size] + cumul_retour >= cible_retour) - { - LOGP[(NOW + index) % Log_size] -= (cible_retour - cumul_retour); - - LOG[(NOW + index) % Log_size] -= (cible_retour - cumul_retour); - - cumul_retour = cible_retour; - } - else - { - if (LOGP[(NOW + index) % Log_size] > 0) - { - cumul_retour += LOGP[(NOW + index) % Log_size]; - - LOG[(NOW + index) % Log_size] -= LOGP[(NOW + index) % Log_size]; - - LOGP[(NOW + index) % Log_size] = 0; - } - } - } - - AUN += cible_retour; - NPO_cur = (int)NPOmax[dayInTheYear]; - } - - int FOC = 0; - - int POC = 0; - - if (lf[dayInTheYear] > 0. and lf[dayInTheYear] <= FAILURE_RATE_EQ_1) - { - A = rndgenerator.next(); - last = FPOW[dayInTheYear][AUN]; - - if (A > last) - { - cumul = last; - for (int d = 1; d < AUN + 1; ++d) - { - last = ((last * ff[dayInTheYear]) * ((double)(AUN + 1. - d))) / (double)d; - cumul += last; - FOC = d; - if (A <= cumul) - break; - } - } - } - else - { - FOC = (lf[dayInTheYear] > 0.) ? AUN : 0; - } - - if (lp[dayInTheYear] > 0. and lp[dayInTheYear] <= FAILURE_RATE_EQ_1) - { - int AUN_app = AUN; - if (stock >= 0 and stock <= AUN) - AUN_app -= stock; - if (stock > AUN) - AUN_app = 0; - - last = PPOW[dayInTheYear][AUN_app]; - A = rndgenerator.next(); - - if (A > last) - { - cumul = last; - for (int d = 1; d < AUN_app + 1; ++d) - { - last - = ((last * pp[dayInTheYear]) * ((double)(AUN_app + 1. - d))) / (double)d; - cumul += last; - POC = d; - if (A <= cumul) - break; - } - } - } - else - { - POC = (lp[dayInTheYear] > 0.) ? AUN : 0; - } - - int candidat = POC + stock; - if (0 <= candidat and candidat <= AUN) - { - POC = candidat; - - stock = 0; - } - if (candidat > AUN) - { - stock = candidat - AUN; - - POC = AUN; - } - if (candidat < 0) - { - stock = candidat; - - POC = 0; - } - - if (POC + NPO_cur > NPOmax[dayInTheYear]) - { - stock += POC + NPO_cur - (int)NPOmax[dayInTheYear]; - - POC = (int)NPOmax[dayInTheYear] - NPO_cur; - - NPO_cur = (int)NPOmax[dayInTheYear]; - } - else - { - if (POC + NPO_cur < NPOmin[dayInTheYear]) - { - if (NPOmin[dayInTheYear] - NPO_cur > AUN) - { - stock -= (AUN - POC); - - POC = AUN; - NPO_cur += POC; - } - else - { - stock -= (int)NPOmin[dayInTheYear] - (POC + NPO_cur); - - POC = (int)NPOmin[dayInTheYear] - NPO_cur; - - NPO_cur = (int)NPOmin[dayInTheYear]; - } - } - else - { - NPO_cur += POC; - } - } - - if (cluster.unitCount == 1) - { - if (POC == 1 and FOC == 1) - { - PPO = 0; - PFO = 0; - MXO = 1; - } - else - { - MXO = 0; - PFO = FOC; - PPO = POC; - } - } - else - { - if (AUN != 0) - { - MXO = POC * FOC / AUN; - PPO = POC - MXO; - PFO = FOC - MXO; - } - else - { - MXO = 0; - PPO = 0; - PFO = 0; - } - } - - AUN = AUN - (PPO + PFO + MXO); - - if (PFO != 0 or MXO != 0) - FOD_reel = durationGenerator( - f_law, FODOfTheDay, f_volatility, af[dayInTheYear], bf[dayInTheYear]); - if (PPO != 0 or MXO != 0) - POD_reel = durationGenerator( - p_law, PODOfTheDay, p_volatility, ap[dayInTheYear], bp[dayInTheYear]); - - assert(FUT < Log_size); - if (PFO != 0) - { - FUT = (NOW + FOD_reel) % Log_size; - LOG[FUT] += PFO; - } - if (PPO != 0) - { - FUT = (NOW + POD_reel) % Log_size; - LOG[FUT] += PPO; - LOGP[FUT] = LOGP[FUT] + PPO; - } - if (MXO != 0) - { - FUT = (NOW + POD_reel + FOD_reel) % Log_size; - LOG[FUT] += MXO; - LOGP[FUT] = LOGP[FUT] + MXO; - } - NOW = (NOW + 1) % Log_size; - - AVP[dayInTheYear] = AUN * cluster.nominalCapacity; - - if (tsIndex > 1) - { - double AVPDayInTheYear = AVP[dayInTheYear]; - for (uint h = 0; h != 24; ++h) - { - dstSeries[hour] = Math::Round(AVPDayInTheYear * modulation[hour]); - ++hour; - } - } - } - } - - if (derated) - cluster.series->timeSeries.averageTimeseries(); - - if (archive) - writeResultsToDisk(area, cluster); - - cluster.calculationOfSpinning(); -} -} // namespace - -bool GenerateThermalTimeSeries(Data::Study& study, - uint year, - bool globalThermalTSgeneration, - bool refreshTSonCurrentYear, - Antares::Solver::IResultWriter& writer) -{ - logs.info(); - logs.info() << "Generating the thermal time-series"; - Solver::Progression::Task progression(study, year, Solver::Progression::sectTSGThermal); - - auto* generator = new GeneratorTempData(study, progression, writer); - - generator->currentYear = year; - - study.areas.each([&](Data::Area& area) { - auto end = area.thermal.list.mapping.end(); - for (auto it = area.thermal.list.mapping.begin(); it != end; ++it) - { - auto& cluster = *(it->second); - - if (cluster.doWeGenerateTS(globalThermalTSgeneration) && refreshTSonCurrentYear) - { - (*generator)(area, cluster); - } - - ++progression; - } - }); - - delete generator; - - return true; -} - -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares diff --git a/src/solver/ts-generator/xcast/constants.h b/src/solver/ts-generator/xcast/constants.h deleted file mode 100644 index fa0313da35..0000000000 --- a/src/solver/ts-generator/xcast/constants.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_CONSTANTS_H__ -#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_CONSTANTS_H__ - -//! Precision sur la factorisation des matrices -#define EPSIMIN ((float)1.0e-9) -//! Precision sur les verifications des produits LtL -#define EPSIMAX ((float)1.0e-3) - -//! Limite d'approche des bornes des processus -#define EPSIBOR ((float)1.0e-4) - -//! Infini + -#define INFINIP ((float)1.0e+9) -//! Infini - -#define INFININ ((float)-1.0e+9) - -// 1+ PETIT * theta -// 1 dans le developpement limite des correlations spatiales instantanees -// PETIT * theta << 1 pour le plafonnement du terme lineaire des dXt -// 2 * sqrt(PETIT) * theta << 1 pour le plafonnement du terme diffusion des dXt -#define PETIT ((float)1e-2) - -//! A la limite superieure des lois de Weibull la fonction de repartition vaut 1- NEGLI_WEIB -#define NEGLI_WEIB ((double)1.0e-4) -//! A la limite superieure des lois Gamma la fonction de repartition vaut 1- NEGLI_GAM -#define NEGLI_GAMM ((double)1.0e-4) - -#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_CONSTANTS_H__ diff --git a/src/solver/ts-generator/xcast/core.cpp b/src/solver/ts-generator/xcast/core.cpp index 754d898cde..a3d373e2c1 100644 --- a/src/solver/ts-generator/xcast/core.cpp +++ b/src/solver/ts-generator/xcast/core.cpp @@ -1,48 +1,39 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include + #include -#include -#include + #include -#include "xcast.h" -#include "constants.h" -#include "../../misc/cholesky.h" -#include "../../misc/matrix-dp-make.h" -#include "math.hxx" +#include +#include +#include "antares/antares/constants.h" +#include "antares/solver/misc/cholesky.h" +#include "antares/solver/misc/matrix-dp-make.h" +#include "antares/solver/ts-generator/xcast/math.hxx" +#include "antares/solver/ts-generator/xcast/xcast.h" using namespace Yuni; -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast +namespace Antares::TSGenerator::XCast { bool XCast::generateValuesForTheCurrentDay() { @@ -88,11 +79,15 @@ bool XCast::generateValuesForTheCurrentDay() for (uint s = 0; s != processCount; ++s) { if (L[s] != 3) + { All_normal = false; // s is not a Normal process + } } } if (All_normal) + { pAccuracyOnCorrelation = false; // standard accuracy is high accuracy + } } // si les parametres ont change on reinitialise certaines variables intermediaires @@ -107,7 +102,9 @@ bool XCast::generateValuesForTheCurrentDay() // on ne traite qu'en dessous de la diagonale et celle-ci n'a pas change (=1 // partout) for (uint j = 0; j < i; ++j) + { pCorrMonth->entry[i][j] *= 0.999f; + } } if (Cholesky(Triangle_courant, pCorrMonth->entry, processCount, pQCHOLTotal)) @@ -155,8 +152,10 @@ bool XCast::generateValuesForTheCurrentDay() for (uint t = 0; t < s; ++t) { x = T[s] * T[t] * STDE[s] * STDE[t]; - if (Math::Zero(x)) + if (Utils::isZero(x)) + { CORR[s][t] = 0.f; + } else { x = 1.f - ALPH[s] * ALPH[t]; @@ -193,8 +192,10 @@ bool XCast::generateValuesForTheCurrentDay() { x = T[s] * T[t] * STDE[s] * STDE[t]; float z = D_COPIE[t] * STDE[s]; - if (Math::Zero(x)) + if (Utils::isZero(x)) + { CORR[s][t] = 0.f; + } else { x = D_COPIE[s] * STDE[t] / z; @@ -221,8 +222,12 @@ bool XCast::generateValuesForTheCurrentDay() } // calcul et factorisation de la matrice du mois - shrink = MatrixDPMake( - Triangle_courant, CORR, Carre_reference, pCorrMonth->entry, processCount, pQCHOLTotal); + shrink = MatrixDPMake(Triangle_courant, + CORR, + Carre_reference, + pCorrMonth->entry, + processCount, + pQCHOLTotal); if (shrink == -1.f) { // sortie impossible car on a v�rifi� que C est d.p @@ -240,7 +245,9 @@ bool XCast::generateValuesForTheCurrentDay() { x = 1.f; if (T[s] > PETIT) + { x = PETIT / T[s]; + } if (x < STEP) { // plafonne le terme lineaire de retour � la moyenne a PETIT *(ecart � la @@ -256,7 +263,9 @@ bool XCast::generateValuesForTheCurrentDay() // plafonne l'amplitude de la diffusion � 2*sqrt(PETIT)*STDE (pour brown=1) x *= 4.f * PETIT; if (x < STEP) + { STEP = x; + } } } } @@ -281,16 +290,24 @@ bool XCast::generateValuesForTheCurrentDay() for (uint s = 0; s != processCount; ++s) { if (POSI[s] > 0.f) + { POSI[s] *= (MAXI[s] - ESPE[s]); + } else + { POSI[s] *= (ESPE[s] - MINI[s]); + } POSI[s] += ESPE[s]; if (POSI[s] >= MAXI[s]) + { POSI[s] = Presque_maxi[s]; + } if (POSI[s] <= MINI[s]) + { POSI[s] = Presque_mini[s]; + } // on reinitialise la memoire du lissage pour eviter l'accumulation des derives if (M[s] > 1.f) @@ -308,16 +325,24 @@ bool XCast::generateValuesForTheCurrentDay() for (uint s = 0; s != processCount; ++s) { if (POSI[s] > 0.f) + { POSI[s] *= (MAXI[s] - ESPE[s]); + } else + { POSI[s] *= (ESPE[s] - MINI[s]); + } POSI[s] += ESPE[s]; if (POSI[s] >= MAXI[s]) + { POSI[s] = Presque_maxi[s]; + } if (POSI[s] <= MINI[s]) + { POSI[s] = Presque_mini[s]; + } } } @@ -337,16 +362,22 @@ bool XCast::generateValuesForTheCurrentDay() // draw independent Nomal Variables uint j = processCount; if ((processCount - 2 * (processCount / 2)) != 0) + { ++j; + } for (uint k = 0; k < j; ++k) + { normal(WIEN[k], WIEN[j - (1 + k)]); + } // correlated brownian motions for (uint s = 0; s != processCount; ++s) { BROW[s] = 0.f; for (uint t = 0; t < s + 1; ++t) + { BROW[s] += Triangle_courant[s][t] * WIEN[t]; + } } // update processes positions @@ -357,16 +388,22 @@ bool XCast::generateValuesForTheCurrentDay() POSI[s] += BETA[s] * STDE[s] * BROW[s]; if (POSI[s] >= MAXI[s]) + { POSI[s] = Presque_maxi[s]; + } if (POSI[s] <= MINI[s]) + { POSI[s] = Presque_mini[s]; + } } } else // standard case { // calcul des coefficients de diffusion for (uint s = 0; s != processCount; ++s) + { DIFF[s] = diffusion(A[s], B[s], G[s], D[s], L[s], T[s], POSI[s]); + } // on calcule une matrice pour chaque point de passage if (pAccuracyOnCorrelation) @@ -381,8 +418,10 @@ bool XCast::generateValuesForTheCurrentDay() auto& userMonthlyCorr = pCorrMonth->column(s); for (uint t = 0; t < s; ++t) { - if (Math::Zero(DIFF[s]) || Math::Zero(DIFF[t])) + if (Utils::isZero(DIFF[s]) || Utils::isZero(DIFF[t])) + { corr_s[t] = 0; + } else { z = DIFF[t] * STDE[s]; @@ -425,23 +464,31 @@ bool XCast::generateValuesForTheCurrentDay() return false; } if (shrink < 1.f) + { ++pNDPMatrixCount; + } } } // accuracy // tirage au sort de lois normales independantes uint j = processCount; if ((processCount - 2 * (processCount / 2)) != 0) + { ++j; + } for (uint k = 0; k < j; ++k) + { normal(WIEN[k], WIEN[j - (1 + k)]); + } // calcul des mouvements browniens correles for (uint s = 0; s != processCount; ++s) { BROW[s] = 0.f; for (uint t = 0; t < s + 1; ++t) + { BROW[s] += Triangle_courant[s][t] * WIEN[t]; // chg 060610 + } } // calcul des parametres directeurs du prochain mouvement @@ -456,12 +503,16 @@ bool XCast::generateValuesForTheCurrentDay() { POSI[s] += (TREN[s] * STEP) + (DIFF[s] * SQST); if (POSI[s] >= MAXI[s]) + { POSI[s] = Presque_maxi[s]; + } if (POSI[s] <= MINI[s]) + { POSI[s] = Presque_mini[s]; + } } } // end of standard case - } // fin du point horaire + } // fin du point horaire for (uint s = 0; s != processCount; ++s) { @@ -475,27 +526,35 @@ bool XCast::generateValuesForTheCurrentDay() if (data_si > MA[s]) { data_si = MA[s]; - if (Math::Abs(FO[s][i]) > 0.f) + if (std::abs(FO[s][i]) > 0.f) { POSI[s] = MA[s] / FO[s][i]; POSI[s] -= G[s]; if (POSI[s] >= MAXI[s]) + { POSI[s] = Presque_maxi[s]; + } if (POSI[s] <= MINI[s]) + { POSI[s] = Presque_mini[s]; + } } } if (data_si < MI[s]) { data_si = MI[s]; - if (Math::Abs(FO[s][i]) > 0.f) + if (std::abs(FO[s][i]) > 0.f) { POSI[s] = MI[s] / FO[s][i]; POSI[s] -= G[s]; if (POSI[s] >= MAXI[s]) + { POSI[s] = Presque_maxi[s]; + } if (POSI[s] <= MINI[s]) + { POSI[s] = Presque_mini[s]; + } } } } @@ -513,13 +572,17 @@ bool XCast::generateValuesForTheCurrentDay() if (BO[s]) // si ecretement active { if (data_si > MA[s]) + { data_si = MA[s]; + } if (data_si < MI[s]) + { data_si = MI[s]; + } } } - assert(0 == Math::Infinite(data_si) && "Infinite value"); + assert(!std::isinf(data_si) && "Infinite value"); DATA[s][i] = data_si; } } @@ -536,25 +599,30 @@ bool XCast::generateValuesForTheCurrentDay() { // > if (POSI[s] > ESPE[s]) + { POSI[s] = (POSI[s] - ESPE[s]) / (MAXI[s] - ESPE[s]); + } else { // < if (POSI[s] < ESPE[s]) + { POSI[s] = (ESPE[s] - POSI[s]) / (MINI[s] - ESPE[s]); + } else // = + { POSI[s] = 0; + } } } // fin de la serie if (!pAccuracyOnCorrelation && Compteur_ndp == 100) + { ++pNDPMatrixCount; + } return true; } -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares +} // namespace Antares::TSGenerator::XCast diff --git a/src/solver/ts-generator/xcast/gamma-euler.cpp b/src/solver/ts-generator/xcast/gamma-euler.cpp index c933b737e9..d8828dc17e 100644 --- a/src/solver/ts-generator/xcast/gamma-euler.cpp +++ b/src/solver/ts-generator/xcast/gamma-euler.cpp @@ -1,48 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include + #include -#include -#include "xcast.h" #include + #include -#include +#include +#include "antares/solver/ts-generator/xcast/xcast.h" using namespace Yuni; #define PI 3.141592653589793 -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast +namespace Antares::TSGenerator::XCast { double XCast::GammaEuler(double z) { @@ -63,6 +53,7 @@ double XCast::GammaEuler(double z) { g = 6, }; + double x; const double t = z + double(g) + 0.5; double rho; @@ -84,7 +75,9 @@ double XCast::GammaEuler(double z) x = p[0]; for (int i = 1; i < g + 3; ++i) + { x += p[i] / (z + double(i)); + } x = 1. / (2.506628275 * pow(t, z + 0.5) * exp(-t) * x); } @@ -95,7 +88,9 @@ double XCast::GammaEuler(double z) x = p[0]; for (int i = 1; i < g + 3; ++i) + { x += p[i] / (z + double(i)); + } x = 2.506628275 * pow(t, z + 0.5) * exp(-t) * x; } @@ -103,7 +98,4 @@ double XCast::GammaEuler(double z) return (rho * x); } -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares +} // namespace Antares::TSGenerator::XCast diff --git a/src/solver/ts-generator/xcast/gamma-inc.cpp b/src/solver/ts-generator/xcast/gamma-inc.cpp index fdc2bcef4f..b005471022 100644 --- a/src/solver/ts-generator/xcast/gamma-inc.cpp +++ b/src/solver/ts-generator/xcast/gamma-inc.cpp @@ -1,42 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include -#include "xcast.h" #include + #include +#include +#include "antares/solver/ts-generator/xcast/xcast.h" using namespace Yuni; namespace Antares { -namespace Solver -{ namespace TSGenerator { namespace XCast @@ -63,5 +56,4 @@ double XCast::GammaInc(double s, double z) } // namespace XCast } // namespace TSGenerator -} // namespace Solver } // namespace Antares diff --git a/src/solver/ts-generator/xcast/math.cpp b/src/solver/ts-generator/xcast/math.cpp index 2ef43546fd..e9d34559ac 100644 --- a/src/solver/ts-generator/xcast/math.cpp +++ b/src/solver/ts-generator/xcast/math.cpp @@ -1,44 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include "xcast.h" +#include "antares/solver/ts-generator/xcast/xcast.h" namespace Antares { -namespace Solver -{ namespace TSGenerator { namespace XCast { void XCast::normal(float& x, float& y) { - assert(random != NULL); + assert(random); double z; double xd; @@ -59,5 +51,4 @@ void XCast::normal(float& x, float& y) } // namespace XCast } // namespace TSGenerator -} // namespace Solver } // namespace Antares diff --git a/src/solver/ts-generator/xcast/predicate.hxx b/src/solver/ts-generator/xcast/predicate.hxx deleted file mode 100644 index 6a78b7da1d..0000000000 --- a/src/solver/ts-generator/xcast/predicate.hxx +++ /dev/null @@ -1,177 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_TS_GENERATOR_XCAST_PREDICATE_HXX__ -#define __SOLVER_TS_GENERATOR_XCAST_PREDICATE_HXX__ - -#include -#include -#include -#include "antares/study/parts/load/prepro.h" - -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace Predicate -{ -class Wind final -{ -public: - static bool preproDataIsReader(const Data::Area& area) - { - return area.wind.prepro != NULL; - } - - static const char* timeSeriesName() - { - return "wind"; - } - - bool accept(const Data::Area& area) const - { - assert(area.wind.prepro != NULL); - return !Yuni::Math::Zero(area.wind.prepro->xcast.capacity); - } - - Matrix& matrix(Data::Area& area) const - { - assert(area.wind.series != NULL); - return area.wind.series->timeSeries; - } - - Data::XCast& xcastData(Data::Area& area) const - { - assert(area.wind.prepro != NULL); - return area.wind.prepro->xcast; - } - - static const Data::Correlation& correlation(const Data::Study& study) - { - return study.preproWindCorrelation; - } - - uint timeSeriesToGenerate(const Data::Study& study) const - { - return study.parameters.nbTimeSeriesWind; - } - -}; // class Wind - -class Load final -{ -public: - static bool preproDataIsReader(const Data::Area& area) - { - return area.load.prepro != NULL; - } - - static const char* timeSeriesName() - { - return "load"; - } - - bool accept(const Data::Area& area) const - { - assert(area.load.prepro != NULL); - return !Yuni::Math::Zero(area.load.prepro->xcast.capacity); - } - - Matrix& matrix(Data::Area& area) const - { - assert(area.load.series != NULL); - return area.load.series->timeSeries; - } - - Data::XCast& xcastData(Data::Area& area) const - { - assert(area.load.prepro != NULL); - return area.load.prepro->xcast; - } - - static const Data::Correlation& correlation(const Data::Study& study) - { - return study.preproLoadCorrelation; - } - - uint timeSeriesToGenerate(const Data::Study& study) const - { - return study.parameters.nbTimeSeriesLoad; - } - -}; // class Load - -class Solar final -{ -public: - static bool preproDataIsReader(const Data::Area& area) - { - return area.solar.prepro != NULL; - } - - static const char* timeSeriesName() - { - return "solar"; - } - - bool accept(const Data::Area& area) const - { - assert(area.solar.prepro != NULL); - return !Yuni::Math::Zero(area.solar.prepro->xcast.capacity); - } - - Matrix& matrix(Data::Area& area) const - { - assert(area.solar.series != NULL); - return area.solar.series->timeSeries; - } - - Data::XCast& xcastData(Data::Area& area) const - { - assert(area.solar.prepro != NULL); - return area.solar.prepro->xcast; - } - - static const Data::Correlation& correlation(const Data::Study& study) - { - return study.preproSolarCorrelation; - } - - uint timeSeriesToGenerate(const Data::Study& study) const - { - return study.parameters.nbTimeSeriesSolar; - } - -}; // class Solar - -} // namespace Predicate -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_TS_GENERATOR_XCAST_PREDICATE_HXX__ diff --git a/src/solver/ts-generator/xcast/studydata.cpp b/src/solver/ts-generator/xcast/studydata.cpp index b36b889770..217f61fe14 100644 --- a/src/solver/ts-generator/xcast/studydata.cpp +++ b/src/solver/ts-generator/xcast/studydata.cpp @@ -1,48 +1,41 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/ts-generator/xcast/studydata.h" + #include + #include -#include "studydata.h" using namespace Yuni; -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast +namespace Antares::TSGenerator::XCast { -StudyData::StudyData() : mode(Data::Correlation::modeNone) +StudyData::StudyData(): + mode(Data::Correlation::modeNone) { for (uint realmonth = 0; realmonth != 12; ++realmonth) + { correlation[realmonth] = nullptr; + } } StudyData::~StudyData() @@ -52,7 +45,9 @@ StudyData::~StudyData() case Data::Correlation::modeMonthly: { for (uint realmonth = 0; realmonth != 12; ++realmonth) + { delete correlation[realmonth]; + } break; } case Data::Correlation::modeAnnual: @@ -101,7 +96,9 @@ void StudyData::reloadDataFromAreaList(const Data::Correlation& originalCorrelat prepareMatrix(*m, *(originalCorrelation.annual)); for (uint realmonth = 0; realmonth != 12; ++realmonth) + { correlation[realmonth] = m; + } break; } case Data::Correlation::modeMonthly: @@ -121,11 +118,10 @@ void StudyData::reloadDataFromAreaList(const Data::Correlation& originalCorrelat else { for (uint realmonth = 0; realmonth != 12; ++realmonth) + { correlation[realmonth] = nullptr; + } } } -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares +} // namespace Antares::TSGenerator::XCast diff --git a/src/solver/ts-generator/xcast/studydata.h b/src/solver/ts-generator/xcast/studydata.h deleted file mode 100644 index 5a5ebdb223..0000000000 --- a/src/solver/ts-generator/xcast/studydata.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_H__ -#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_H__ - -#include -#include -#include //TODO collision - -namespace Antares::Solver::TSGenerator::XCast -{ -class StudyData final -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief - */ - StudyData(); - /*! - ** \brief Destructor - */ - ~StudyData(); - //@} - - /*! - ** \brief Load all informations from a study and a predicate - ** - ** Example of a predicate: - ** \code - ** struct WindPredicate - ** { - ** bool operator () (const Area&) const - ** { - ** return true; - ** } - ** - ** Data::XCast* retrieveXCastData(const Area* area) const - ** { - ** return area->wind.prepro->xcast; - ** } - ** }; - ** \endcode - ** - ** All areas excluded from the list will see their time-series matrix reset to 1x8760. - ** - ** \param study A study - ** \param predicate Predicate to determine whether the specified object meets some criteria - ** and to retrive some specific data from the area - */ - template - void loadFromStudy(Data::Study& study, - const Data::Correlation& correlation, - PredicateT& predicate); - -public: - //! List of all areas (sub-set of the complete list) - Data::Area::Vector localareas; - //! Correlation coefficients for each month - const Matrix* correlation[12]; - /*! - ** \brief Correlation mode (monthly / annual) - ** - ** \internal This value is a copy from the correlation data and - ** it's used to properly delete the coefficient matrices. - */ - Data::Correlation::Mode mode; - -private: - //! Delete - //! Rebuild data from our own area list - void reloadDataFromAreaList(const Data::Correlation& correlation); - - void prepareMatrix(Matrix& m, const Matrix& source) const; - -}; // class StudyData - -} // namespace Antares::Solver::TSGenerator::XCast - - - - -#include "studydata.hxx" - -#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_H__ diff --git a/src/solver/ts-generator/xcast/studydata.hxx b/src/solver/ts-generator/xcast/studydata.hxx deleted file mode 100644 index 2d0f5fd495..0000000000 --- a/src/solver/ts-generator/xcast/studydata.hxx +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_HXX__ -#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_HXX__ - -#include -#include -#include - -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast -{ -template -void StudyData::loadFromStudy(Data::Study& study, - const Data::Correlation& correlation, - PredicateT& predicate) -{ - // clear our list of areas - localareas.clear(); - - // We will rebuild it using the predicate - for (auto i = study.areas.begin(); i != study.areas.end(); ++i) - { - auto& area = *(i->second); - if (predicate.accept(area)) - { - // XCast will have to use this area - logs.info() << " Added the area '" << area.name << "'"; - localareas.push_back(&area); - } - else - { - // resize and set the values for the matrix - predicate.matrix(area).reset(1, HOURS_PER_YEAR); - } - } - reloadDataFromAreaList(correlation); -} - -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares - -#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_STUDY_DATA_HXX__ diff --git a/src/solver/ts-generator/xcast/xcast.cpp b/src/solver/ts-generator/xcast/xcast.cpp index 2cffb5235e..56f7234119 100644 --- a/src/solver/ts-generator/xcast/xcast.cpp +++ b/src/solver/ts-generator/xcast/xcast.cpp @@ -1,54 +1,44 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/solver/ts-generator/xcast/xcast.h" + +#include #include +#include + #include -#include -#include "xcast.h" -#include "predicate.hxx" + +#include #include -#include -#include -#include -#include +#include +#include "antares/solver/ts-generator/xcast/predicate.hxx" using namespace Yuni; #define SEP (IO::Separator) -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast +namespace Antares::TSGenerator::XCast { + enum { alpha = Data::XCast::dataCoeffAlpha, @@ -59,12 +49,12 @@ enum mu = Data::XCast::dataCoeffMu, }; -XCast::XCast(Data::Study& study, Data::TimeSeriesType ts, IResultWriter& writer) : - study(study), - timeSeriesType(ts), - pNeverInitialized(true), - pAccuracyOnCorrelation(false), - pWriter(writer) +XCast::XCast(Data::Study& study, Data::TimeSeriesType ts, IResultWriter& writer): + study(study), + timeSeriesType(ts), + pNeverInitialized(true), + pAccuracyOnCorrelation(false), + pWriter(writer) { } @@ -79,7 +69,9 @@ void XCast::exportTimeSeriesToTheOutput(Progression::Task& progression, Predicat if (study.parameters.noOutput) { for (uint i = 0; i != study.areas.size(); ++i) + { ++progression; + } } else { @@ -93,15 +85,17 @@ void XCast::exportTimeSeriesToTheOutput(Progression::Task& progression, Predicat output << "ts-generator" << SEP << predicate.timeSeriesName() << SEP << "mc-" << year; filename.reserve(output.size() + 80); - study.areas.each([&](Data::Area& area) { - filename.clear() << output << SEP << area.id << ".txt"; - std::string buffer; - predicate.matrix(area).saveToBuffer(buffer); + study.areas.each( + [this, &filename, &progression, &predicate, &output](Data::Area& area) + { + filename.clear() << output << SEP << area.id << ".txt"; + std::string buffer; + predicate.matrix(area).saveToBuffer(buffer); - pWriter.addEntryFromBuffer(filename.c_str(), buffer); + pWriter.addEntryFromBuffer(filename.c_str(), buffer); - ++progression; - }); + ++progression; + }); } } @@ -110,13 +104,8 @@ void XCast::applyTransferFunction(PredicateT& predicate) { enum { - - nbHoursADay = 24, - x = 0, - y = 1, - maxPoints = Data::XCast::conversionMaxPoints, }; @@ -148,8 +137,8 @@ void XCast::applyTransferFunction(PredicateT& predicate) if (p1[x] <= p0[x]) { std::ostringstream msg; - msg << "Transfer function: invalid X-coordinate at index (" << i - << ", " << (i + 1) << ")"; + msg << "Transfer function: invalid X-coordinate at index (" << i << ", " + << (i + 1) << ")"; throw FatalError(msg.str()); } a[i] = (p1[y] - p0[y]) / (p1[x] - p0[x]); @@ -157,7 +146,7 @@ void XCast::applyTransferFunction(PredicateT& predicate) } dailyResults = DATA[s]; - for (h = 0; h != nbHoursADay; ++h) + for (h = 0; h != HOURS_PER_DAY; ++h) { for (i = 0; i != tf.width; ++i) { @@ -168,7 +157,7 @@ void XCast::applyTransferFunction(PredicateT& predicate) if (dailyResults[h] >= pj[x] && dailyResults[h] <= pk[x]) { - assert(0 == Math::Infinite(b[j]) && "Infinite value"); + assert(!std::isinf(b[j]) && "Infinite value"); dailyResults[h] = (a[j] * dailyResults[h]) + b[j]; last_i = i; break; @@ -217,13 +206,16 @@ template class Allocator { public: - Allocator() : allocated(0) + Allocator(): + allocated(0) { } + ~Allocator() { logs.debug() << " allocated " << (allocated / 1024) << "Ko"; } + template inline T* allocate(const size_t s) { @@ -370,12 +362,6 @@ void XCast::destroyTemporaryData() template bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progression) { - enum - { - - nbHoursADay = 24, - }; - pTSName = predicate.timeSeriesName(); { @@ -395,8 +381,6 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi if (pNeverInitialized) { - const uint nbHours = 8760; - loadFromStudy(predicate.correlation(study), predicate); allocateTemporaryData(); @@ -405,26 +389,30 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi { auto& area = *(pData.localareas[s]); - predicate.matrix(area).resize(nbTimeseries, nbHours); auto& xcast = predicate.xcastData(area); pUseConversion[s] = (xcast.useConversion && xcast.conversion.width >= 3); } - pAccuracyOnCorrelation - = ((study.parameters.timeSeriesAccuracyOnCorrelation & timeSeriesType) != 0); + pAccuracyOnCorrelation = ((study.parameters.timeSeriesAccuracyOnCorrelation + & timeSeriesType) + != 0); } const uint processCount = (uint)pData.localareas.size(); if (study.areas.size() > pData.localareas.size()) - progression - += (nbTimeseries * 365) * ((uint)study.areas.size() - (uint)pData.localareas.size()); + { + progression += (nbTimeseries_ * DAYS_PER_YEAR) + * ((uint)study.areas.size() - (uint)pData.localareas.size()); + } if (processCount == 0) { if (study.parameters.timeSeriesToArchive & timeSeriesType) + { exportTimeSeriesToTheOutput(progression, predicate); + } return true; } @@ -434,7 +422,7 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi pNDPMatrixCount = 0; pLevellingCount = 0; - for (uint tsIndex = 0; tsIndex != nbTimeseries; ++tsIndex) + for (uint tsIndex = 0; tsIndex != nbTimeseries_; ++tsIndex) { uint hourInTheYear = 0; @@ -488,14 +476,16 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi MA[s] = +std::numeric_limits::max(); } } - memcpy(FO[s], xcastdata.K[realmonth], sizeof(float) * nbHoursADay); + memcpy(FO[s], xcastdata.K[realmonth], sizeof(float) * HOURS_PER_DAY); } uint nbDaysPerMonth = study.calendar.months[month].days; for (uint j = 0; j != nbDaysPerMonth; ++j) { if (not generateValuesForTheCurrentDay()) + { throw FatalError("xcast: Failed to generate values."); + } #ifndef NDEBUG @@ -503,9 +493,9 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi { float* dailyResults = DATA[s]; - for (uint h = 0; h != nbHoursADay; ++h) + for (uint h = 0; h != HOURS_PER_DAY; ++h) { - assert(0 == Math::Infinite(dailyResults[h]) && "Infinite value"); + assert(!std::isinf(dailyResults[h]) && "Infinite value"); } } #endif @@ -517,16 +507,18 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi auto& srcData = predicate.xcastData(currentArea); if (srcData.useTranslation != Data::XCast::tsTranslationBeforeConversion) + { continue; + } auto& column = srcData.translation[0]; float* dailyResults = DATA[s]; - assert(hourInTheYear + nbHoursADay <= srcData.translation.height + assert(hourInTheYear + HOURS_PER_DAY <= srcData.translation.height && "Bound checking"); - for (uint h = 0; h != nbHoursADay; ++h) + for (uint h = 0; h != HOURS_PER_DAY; ++h) { - assert(0 == Math::Infinite(dailyResults[h]) && "Infinite value"); + assert(!std::isinf(dailyResults[h]) && "Infinite value"); dailyResults[h] += (float)column[hourInTheYear + h]; } } @@ -539,9 +531,9 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi { float* dailyResults = DATA[s]; - for (uint h = 0; h != nbHoursADay; ++h) + for (uint h = 0; h != HOURS_PER_DAY; ++h) { - assert(0 == Math::Infinite(dailyResults[h]) && "Infinite value"); + assert(!std::isinf(dailyResults[h]) && "Infinite value"); } } #endif @@ -558,29 +550,33 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi auto& column = series.column(tsIndex); float* dailyResults = DATA[s]; - for (uint h = 0; h != nbHoursADay; ++h) + for (uint h = 0; h != HOURS_PER_DAY; ++h) { - assert(0 == Math::Infinite(dailyResults[h]) && "Infinite value"); + assert(!std::isinf(dailyResults[h]) && "Infinite value"); dailyResults[h] *= (float)srcData.capacity; } if (srcData.useTranslation == Data::XCast::tsTranslationAfterConversion) { - assert(hourInTheYear + nbHoursADay <= srcData.translation.height + assert(hourInTheYear + HOURS_PER_DAY <= srcData.translation.height && "Bound checking"); auto& tsavg = srcData.translation[0]; - for (uint h = 0; h != nbHoursADay; ++h) + for (uint h = 0; h != HOURS_PER_DAY; ++h) + { dailyResults[h] += (float)tsavg[hourInTheYear + h]; + } } - assert(hourInTheYear + nbHoursADay <= series.height && "Bound checking"); - for (uint h = 0; h != nbHoursADay; ++h) - column[hourInTheYear + h] = Math::Round(dailyResults[h]); + assert(hourInTheYear + HOURS_PER_DAY <= series.height && "Bound checking"); + for (uint h = 0; h != HOURS_PER_DAY; ++h) + { + column[hourInTheYear + h] = std::round(dailyResults[h]); + } ++progression; } - hourInTheYear += nbHoursADay; + hourInTheYear += HOURS_PER_DAY; pNewMonth = false; } @@ -588,7 +584,7 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi } { - uint y = ((pAccuracyOnCorrelation) ? pComputedPointCount : (nbTimeseries * 365)); + uint y = ((pAccuracyOnCorrelation) ? pComputedPointCount : (nbTimeseries_ * 365)); uint z = pNDPMatrixCount; logs.info() << " " << pComputedPointCount << " points calculated, using " << y @@ -597,11 +593,14 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi if (study.parameters.derated) { - study.areas.each([&](Data::Area& area) { predicate.matrix(area).averageTimeseries(); }); + study.areas.each([&predicate](Data::Area& area) + { predicate.matrix(area).averageTimeseries(); }); } if (study.parameters.timeSeriesToArchive & timeSeriesType) + { exportTimeSeriesToTheOutput(progression, predicate); + } if (timeSeriesType == Data::timeSeriesLoad) { @@ -610,10 +609,9 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi { auto& area = *(study.areas.byIndex[s]); - assert(area.load.series); assert(static_cast(Data::fhrDSM) < area.reserves.width); - auto& matrix = area.load.series->timeSeries; + auto& matrix = area.load.series.timeSeries; auto& dsmvalues = area.reserves.column(Data::fhrDSM); assert(matrix.width > 0); @@ -624,7 +622,7 @@ bool XCast::runWithPredicate(PredicateT& predicate, Progression::Task& progressi for (uint h = 0; h < matrix.height; ++h) { perHour[h] += dsmvalues[h]; - assert(!Math::NaN(perHour[h])); + assert(!std::isnan(perHour[h])); } } } @@ -641,7 +639,7 @@ bool XCast::run() { Solver::Progression::Task p(study, year, Progression::sectTSGLoad); - nbTimeseries = study.parameters.nbTimeSeriesLoad; + nbTimeseries_ = study.parameters.nbTimeSeriesLoad; Predicate::Load predicate; return runWithPredicate(predicate, p); @@ -650,7 +648,7 @@ bool XCast::run() { Solver::Progression::Task p(study, year, Progression::sectTSGSolar); - nbTimeseries = study.parameters.nbTimeSeriesSolar; + nbTimeseries_ = study.parameters.nbTimeSeriesSolar; Predicate::Solar predicate; return runWithPredicate(predicate, p); @@ -659,7 +657,7 @@ bool XCast::run() { Solver::Progression::Task p(study, year, Progression::sectTSGWind); - nbTimeseries = study.parameters.nbTimeSeriesWind; + nbTimeseries_ = study.parameters.nbTimeSeriesWind; Predicate::Wind predicate; return runWithPredicate(predicate, p); @@ -673,7 +671,4 @@ bool XCast::run() return false; } -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares +} // namespace Antares::TSGenerator::XCast diff --git a/src/solver/ts-generator/xcast/xcast.h b/src/solver/ts-generator/xcast/xcast.h deleted file mode 100644 index 7c6efb6d25..0000000000 --- a/src/solver/ts-generator/xcast/xcast.h +++ /dev/null @@ -1,263 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_H__ -#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_H__ - -#include -#include -#include -#include -#include "studydata.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast -{ -/*! -** \brief XCast Generator for Load, Wind and solar timeseries -** -** \see predicate.hxx for specializations -*/ -class XCast final : private Yuni::NonCopyable -{ -public: - /*! - ** \brief Compute - */ - static double GammaEuler(double z); - - /*! - ** \brief Calcul de la forme inférieure de la fonction gamma incomplete - ** - ** Calcul de la forme inférieure de la fonction gamma incomplete (s,z) = somme{0;z} - *t^(s-1)exp(-t)dt - ** On utilise un developpement en serie jusqu'à l'ordre 30, ce qui garantit - ** une precision suffisante dans le domaine 1 <= s <= 2 et 0 <= z <= 10 - ** \warning Dans les lois de Weibull, la valeur maximale que z peut atteindre - ** est Log(1 / NEGLI_WEIB). Il faut donc regler NEGLI_WEIB en conséquence - ** - */ - static double GammaInc(double s, double z); - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - XCast(Data::Study& study, Data::TimeSeriesType ts, IResultWriter& writer); - /*! - ** \brief Destructor - */ - ~XCast(); - //@} - - //! \name Loading - //@{ - /*! - ** \brief initialize all XCast indicators from the current simulation parameters - */ - template - void loadFromStudy(const Data::Correlation& correlation, PredicateT& predicate); - //@} - - /*! - ** \brief Run the TS Generator - */ - bool run(); - -public: - //! The current study - Data::Study& study; - - //! The number of time-series - uint nbTimeseries; - //! The current year - uint year; - //! The time-series type - const Data::TimeSeriesType timeSeriesType; - - //! The random generator to use - MersenneTwister* random; - -private: - void allocateTemporaryData(); - void destroyTemporaryData(); - - template - void updateMissingCoefficients(PredicateT& predicate); - template - bool runWithPredicate(PredicateT& predicate, Progression::Task& progression); - - /*! - ** \brief Export all time-series for each process into the output folder - */ - template - void exportTimeSeriesToTheOutput(Progression::Task& progression, PredicateT& predicate); - - /*! - ** \brief Perform the generation of the time-series on a single day for all processes - ** - ** Ce code effectue dans l'ordre : - ** a) elaboration de series de valeurs horaires X(a) de processus "purs" - ** definis par A,B,G,D,T,L,C - ** b) transformation de ces series en X(b) par un lissage en moyenne glissante - ** defini par M (permet de regler l'autocorrelation a court terme) - ** c) Modulation des series en X(c) en fonction de coefficients FO de - ** variations quotidienne des valeurs horaires - ** d) Ecretement (haut, bas) de la serie en X(d) de façon a la contenir dans - ** des bornes imposees MI,MA - ** - ** ATTENTION : les 4 étapes sont enchainees pour chaque point horaire. - ** On ne passe donc pas de t à t+1 en faisant - ** X(a)(t) -> X(a)(t+1) - ** X(b)(t) -> X(b)(t+1) - ** - ** Le processus X(a) peut donc s'ecarter de sa loi marginale et de son - ** autocorrelation theoriques si les modulations FO et les bornes MI,MA - ** conduisent frequemment a rectifier sa trajectoire. - ** Ce cas peut se presenter si les bornes d'ecretement MI,MA sont egales a - ** G,D (voire plus etroites) et si les modulations FO sont marquees. - ** - ** - ** LOIS MODELISEES - ** regle generale pour tous les types de loi : t>=0 - ** regles particulieres selon les types de lois : - ** - ** \code - ** code loi a b g - *d autres contraintes Loi marginale - ** 1 quelconque quelconque g> INFININ/2 d0 b>0 g> INFININ/2 d=0 g= a-6*b d= a+6*b Normale d'espérance a et - *d'écart-type b - ** 4 a>=1 b>0 g> INFININ/2 d= gamma_euler(1+1/a) - *Weibull de forme a, d'échelle b et définie pour x>g - ** 5 a>=1 b>0 g> INFININ/2 d non défini - *Gamma de forme a, d'échelle b et définie pour x>g - ** \endcode - */ - bool generateValuesForTheCurrentDay(); - - template - void applyTransferFunction(PredicateT& predicate); - - //! Tirage de deux variables normales centrees et reduites - void normal(float& x, float& y); - -private: - //! Some data after transformation - StudyData pData; - - //! The correlation matrix for the current month - const Matrix* pCorrMonth; - - bool pNeverInitialized; - uint Nombre_points_intermediaire; - - //! True when starting a new month (some data may have to be reinitialized) - bool pNewMonth; - - // Statistics - //! The number of computed points a day - uint pComputedPointCount; - uint pNDPMatrixCount; - uint pLevellingCount; - - bool pAccuracyOnCorrelation; - bool All_normal; // all processes are Normal - - float* A; // les variables de A à CO sont des vues de ALPH à CORR pour un mois particulier - float* B; - float* G; - float* D; - int* M; - float* T; - Data::XCast::Distribution* L; - bool* BO; - float* MA; - float* MI; - float** FO; // contrainte : FO >=0 - - float STEP; - float SQST; - float* POSI; - float** CORR; - float* MAXI; - float* MINI; - float* Presque_maxi; - float* Presque_mini; - float* ESPE; - float* STDE; - float** LISS; - float** DATL; - - float* DIFF; - float* TREN; - float* WIEN; - float* BROW; - - float* BASI; // used only if all processes are Normal - float* ALPH; // used only if all processes are Normal - float* BETA; // used only if all processes are Normal - - float** Triangle_reference; - float** Triangle_courant; - float** Carre_reference; - float** Carre_courant; - - float* D_COPIE; - - float** DATA; - - // cholesky temporary data - float* pQCHOLTotal; - - //! - bool* pUseConversion; - - //! Name of the current timeseries - Yuni::CString<32, false> pTSName; - - IResultWriter& pWriter; -}; // class XCast - -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares - -#include "xcast.hxx" - -#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_H__ diff --git a/src/solver/ts-generator/xcast/xcast.hxx b/src/solver/ts-generator/xcast/xcast.hxx deleted file mode 100644 index 9cc41b84aa..0000000000 --- a/src/solver/ts-generator/xcast/xcast.hxx +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_HXX__ -#define __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_HXX__ - -namespace Antares -{ -namespace Solver -{ -namespace TSGenerator -{ -namespace XCast -{ -template -inline void XCast::loadFromStudy(const Data::Correlation& correlation, PredicateT& predicate) -{ - pData.template loadFromStudy(study, correlation, predicate); -} - -} // namespace XCast -} // namespace TSGenerator -} // namespace Solver -} // namespace Antares - -#endif // __ANTARES_SOLVER_TS_GENERATOR_XCAST_XCAST_HXX__ diff --git a/src/solver/utils/CMakeLists.txt b/src/solver/utils/CMakeLists.txt index 0baf1e8bf5..16cf2a96e5 100644 --- a/src/solver/utils/CMakeLists.txt +++ b/src/solver/utils/CMakeLists.txt @@ -1,32 +1,47 @@ set(SRC - ortools_utils.h + include/antares/solver/utils/ortools_utils.h ortools_utils.cpp - filename.h + include/antares/solver/utils/filename.h filename.cpp - named_problem.h + include/antares/solver/utils/named_problem.h named_problem.cpp - mps_utils.h + include/antares/solver/utils/mps_utils.h mps_utils.cpp - name_translator.h + include/antares/solver/utils/name_translator.h name_translator.cpp - opt_period_string_generator.h + include/antares/solver/utils/opt_period_string_generator.h opt_period_string_generator.cpp - ) + basis_status.cpp + include/antares/solver/utils/basis_status.h + basis_status_impl.cpp + basis_status_impl.h +) add_library(utils ${SRC}) -if(NOT MSVC) +add_library(Antares::solverUtils ALIAS utils) +if (NOT MSVC) target_compile_options(utils PUBLIC "-Wno-unused-variable") -else() +else () #set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS} /wd 4101") # unused local variable #set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} /wd 4101") # unused local variable -endif() +endif () target_link_libraries(utils PUBLIC ortools::ortools sirius_solver Antares::study Antares::result_writer #ortools_utils.h + Antares::optimization-options antares-core #enum.h - ) +) + +target_include_directories(utils + PUBLIC + $ +) + +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/solver/utils/basis_status.cpp b/src/solver/utils/basis_status.cpp new file mode 100644 index 0000000000..fcdddb7941 --- /dev/null +++ b/src/solver/utils/basis_status.cpp @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include + +#include "basis_status_impl.h" + +namespace Antares::Optimization +{ +BasisStatus::BasisStatus(): + impl(std::make_unique()) +{ +} + +BasisStatus::~BasisStatus() = default; + +void BasisStatus::setStartingBasis(operations_research::MPSolver* solver) const +{ + impl->setStartingBasis(solver); +} + +void BasisStatus::extractBasis(const operations_research::MPSolver* solver) +{ + impl->extractBasis(solver); +} + +bool BasisStatus::exists() const +{ + return impl->exists(); +} +} // namespace Antares::Optimization diff --git a/src/solver/utils/basis_status_impl.cpp b/src/solver/utils/basis_status_impl.cpp new file mode 100644 index 0000000000..7dcb72ab01 --- /dev/null +++ b/src/solver/utils/basis_status_impl.cpp @@ -0,0 +1,56 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "basis_status_impl.h" + +#include + +#include "ortools/linear_solver/linear_solver.h" + +template +static void transferBasis(std::vector& destination, + const SourceT& source) +{ + destination.resize(source.size()); + for (size_t idx = 0; idx < source.size(); idx++) + { + destination[idx] = source[idx]->basis_status(); + } +} + +namespace Antares::Optimization +{ +void BasisStatusImpl::setStartingBasis(operations_research::MPSolver* solver) const +{ + solver->SetStartingLpBasis(StatutDesVariables, StatutDesContraintes); +} + +void BasisStatusImpl::extractBasis(const operations_research::MPSolver* solver) +{ + transferBasis(StatutDesVariables, solver->variables()); + transferBasis(StatutDesContraintes, solver->constraints()); +} + +bool BasisStatusImpl::exists() const +{ + return !StatutDesVariables.empty() && !StatutDesContraintes.empty(); +} +} // namespace Antares::Optimization diff --git a/src/solver/utils/basis_status_impl.h b/src/solver/utils/basis_status_impl.h new file mode 100644 index 0000000000..3ce23b12a7 --- /dev/null +++ b/src/solver/utils/basis_status_impl.h @@ -0,0 +1,49 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +#include + +#include "ortools/linear_solver/linear_solver.h" + +namespace Test +{ +class BasisStatus; +} + +namespace Antares::Optimization +{ +class BasisStatusImpl +{ +private: + friend class BasisStatus; + friend class Test::BasisStatus; // For tests + + using Status = operations_research::MPSolver::BasisStatus; + std::vector StatutDesVariables; + std::vector StatutDesContraintes; + + void setStartingBasis(operations_research::MPSolver* solver) const; + void extractBasis(const operations_research::MPSolver* solver); + bool exists() const; +}; +} // namespace Antares::Optimization diff --git a/src/solver/utils/filename.cpp b/src/solver/utils/filename.cpp index 0dd372a2f3..cc71083350 100644 --- a/src/solver/utils/filename.cpp +++ b/src/solver/utils/filename.cpp @@ -1,6 +1,26 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/utils/filename.h" + #include -#include "filename.h" -#include "opt_period_string_generator.h" // ------------------------------------ // Optimization period factory @@ -11,16 +31,19 @@ std::shared_ptr createOptPeriodAsString(bool isOptimiz unsigned int year) { if (isOptimizationWeekly) + { return std::make_shared(week, year); + } else + { return std::make_shared(day, week, year); + } } -std::string createOptimizationFilename( - const std::string& title, - const OptPeriodStringGenerator& optPeriodStringGenerator, - unsigned int optNumber, - const std::string& extension) +std::string createOptimizationFilename(const std::string& title, + const OptPeriodStringGenerator& optPeriodStringGenerator, + unsigned int optNumber, + const std::string& extension) { std::ostringstream outputFile; outputFile << title.c_str() << "-"; diff --git a/src/solver/utils/filename.h b/src/solver/utils/filename.h deleted file mode 100644 index 4acad64e3f..0000000000 --- a/src/solver/utils/filename.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include -#include "../optimisation/opt_period_string_generator_base.h" - -std::shared_ptr createOptPeriodAsString(bool isOptimizationWeekly, - unsigned int day, - unsigned int week, - unsigned int year); - -std::string createCriterionFilename(const OptPeriodStringGenerator& optPeriodStringGenerator, - const unsigned int optNumber); -std::string createMPSfilename(const OptPeriodStringGenerator& optPeriodStringGenerator, - const unsigned int optNumber); diff --git a/src/solver/utils/include/antares/solver/utils/basis_status.h b/src/solver/utils/include/antares/solver/utils/basis_status.h new file mode 100644 index 0000000000..c6e99363f4 --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/basis_status.h @@ -0,0 +1,58 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include + +namespace Test +{ +class BasisStatus; +} + +namespace operations_research +{ +class MPSolver; +} + +namespace Antares::Optimization +{ +class BasisStatusImpl; + +class BasisStatus +{ +public: + // Prevent copy & move + BasisStatus(); + ~BasisStatus(); + BasisStatus(const BasisStatus&) = delete; + BasisStatus(BasisStatus&&) = delete; + BasisStatus& operator=(const BasisStatus&) = delete; + BasisStatus& operator=(BasisStatus&&) = delete; + + bool exists() const; + void setStartingBasis(operations_research::MPSolver* solver) const; + void extractBasis(const operations_research::MPSolver* solver); + +private: + std::unique_ptr impl; + friend class Test::BasisStatus; // For tests +}; +} // namespace Antares::Optimization diff --git a/src/solver/utils/include/antares/solver/utils/filename.h b/src/solver/utils/include/antares/solver/utils/filename.h new file mode 100644 index 0000000000..472d8f8477 --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/filename.h @@ -0,0 +1,36 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include + +#include "opt_period_string_generator.h" + +std::shared_ptr createOptPeriodAsString(bool isOptimizationWeekly, + unsigned int day, + unsigned int week, + unsigned int year); + +std::string createCriterionFilename(const OptPeriodStringGenerator& optPeriodStringGenerator, + const unsigned int optNumber); +std::string createMPSfilename(const OptPeriodStringGenerator& optPeriodStringGenerator, + const unsigned int optNumber); diff --git a/src/solver/utils/include/antares/solver/utils/mps_utils.h b/src/solver/utils/include/antares/solver/utils/mps_utils.h new file mode 100644 index 0000000000..0afe5901ff --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/mps_utils.h @@ -0,0 +1,119 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +extern "C" +{ +#include "spx_definition_arguments.h" +#include "spx_fonctions.h" +#include "srs_api.h" +} + +#include "antares/study/fwd.h" + +#include "named_problem.h" +#include "ortools_utils.h" + +using namespace Antares; +using namespace Antares::Data; +using namespace Antares::Optimization; +using namespace operations_research; + +// ====================== +// MPS files writing +// ====================== + +class I_MPS_writer +{ +public: + explicit I_MPS_writer(uint currentOptimNumber): + current_optim_number_(currentOptimNumber) + { + } + + I_MPS_writer() = default; + virtual ~I_MPS_writer() = default; + virtual void runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) = 0; + +protected: + uint current_optim_number_ = 0; +}; + +class fullMPSwriter final: public I_MPS_writer +{ +public: + fullMPSwriter(PROBLEME_SIMPLEXE_NOMME* named_splx_problem, uint currentOptimNumber); + void runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) override; + +private: + PROBLEME_SIMPLEXE_NOMME* named_splx_problem_ = nullptr; +}; + +class fullOrToolsMPSwriter: public I_MPS_writer +{ +public: + virtual ~fullOrToolsMPSwriter() = default; + fullOrToolsMPSwriter(MPSolver* solver, uint currentOptimNumber); + void runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) override; + +private: + MPSolver* solver_ = nullptr; +}; + +class nullMPSwriter: public I_MPS_writer +{ +public: + virtual ~nullMPSwriter() = default; + using I_MPS_writer::I_MPS_writer; + + void runIfNeeded(Solver::IResultWriter& /*writer*/, const std::string& /*filename*/) override + { + // Does nothing + } +}; + +class mpsWriterFactory +{ +public: + virtual ~mpsWriterFactory() = default; + mpsWriterFactory(Data::mpsExportStatus exportMPS, + bool exportMPSOnError, + const int current_optim_number, + PROBLEME_SIMPLEXE_NOMME* named_splx_problem, + bool ortoolsUsed, + MPSolver* solver); + + std::unique_ptr create(); + std::unique_ptr createOnOptimizationError(); + +private: + // Member functions... + std::unique_ptr createFullmpsWriter(); + bool doWeExportMPS(); + + // Member data... + Data::mpsExportStatus export_mps_; + bool export_mps_on_error_; + PROBLEME_SIMPLEXE_NOMME* named_splx_problem_ = nullptr; + bool ortools_used_; + MPSolver* solver_ = nullptr; + uint current_optim_number_; +}; diff --git a/src/solver/utils/include/antares/solver/utils/name_translator.h b/src/solver/utils/include/antares/solver/utils/name_translator.h new file mode 100644 index 0000000000..5612e30c76 --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/name_translator.h @@ -0,0 +1,52 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once + +#include +#include +#include + +class NameTranslator +{ +public: + virtual ~NameTranslator() = default; + virtual char** translate(const std::vector& src, std::vector& pointerVec) + = 0; + static std::unique_ptr create(bool useRealNames); +}; + +class RealName: public NameTranslator +{ +public: + ~RealName() override = default; + +private: + char** translate(const std::vector& src, std::vector& pointerVec) override; +}; + +class NullName: public NameTranslator +{ +public: + ~NullName() override = default; + +private: + char** translate(const std::vector& src, std::vector& pointerVec) override; +}; diff --git a/src/solver/utils/include/antares/solver/utils/named_problem.h b/src/solver/utils/include/antares/solver/utils/named_problem.h new file mode 100644 index 0000000000..2df99e7749 --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/named_problem.h @@ -0,0 +1,85 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include +#include +#include + +#include "spx_definition_arguments.h" +#include "spx_fonctions.h" + +namespace Antares +{ +namespace Optimization +{ +class BasisStatus; + +struct PROBLEME_SIMPLEXE_NOMME: public PROBLEME_SIMPLEXE +{ +public: + PROBLEME_SIMPLEXE_NOMME(const std::vector& NomDesVariables, + const std::vector& NomDesContraintes, + const std::vector& VariablesEntieres, + BasisStatus& basisStatus, + bool UseNamedProblems, + bool SolverLogs); + +private: + const std::vector& NomDesVariables; + const std::vector& NomDesContraintes; + bool useNamedProblems_; + +public: + const std::vector& VariablesEntieres; + BasisStatus& basisStatus; + + bool isMIP() const; + bool basisExists() const; + + bool UseNamedProblems() const + { + return useNamedProblems_; + } + + void SetUseNamedProblems(bool useNamedProblems) + { + useNamedProblems_ = useNamedProblems; + } + + const std::vector& VariableNames() const + { + return NomDesVariables; + } + + const std::vector& ConstraintNames() const + { + return NomDesContraintes; + } + + bool IntegerVariable(size_t idx) const + { + return VariablesEntieres[idx]; + } +}; +} // namespace Optimization +} // namespace Antares diff --git a/src/solver/utils/include/antares/solver/utils/opt_period_string_generator.h b/src/solver/utils/include/antares/solver/utils/opt_period_string_generator.h new file mode 100644 index 0000000000..f19a65bcfa --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/opt_period_string_generator.h @@ -0,0 +1,73 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once +#include + +/* + MPS and criterion generated files wear the same time interval sequence in their names. + This time interval sequence is either - (for a weekly optimization), + or -- (for a daily optimization). + So, depending on whether the optimization is weekly or daily, the files are named either : + - problem----optim-nb-.mps + - problem-----optim-nb-.mps + + The following class hierarchy intend to represent these time interval sequences (weekly or + daily), and it turns them into a string when building the names of the previous files. This + hierarchy is designed for polymorphism : whetever the time interval an object of that hierarchy + represents, it is passed as a base class argument, and the right 'to_string()' function is + called. +*/ + +class OptPeriodStringGenerator +{ +public: + virtual std::string to_string() const = 0; + virtual ~OptPeriodStringGenerator() = default; +}; + +// ------------------------------------ +// Daily optimization +// ------------------------------------ +class OptDailyStringGenerator final: public OptPeriodStringGenerator +{ +public: + OptDailyStringGenerator(unsigned int day, unsigned int week, unsigned int year); + std::string to_string() const override; + +private: + unsigned int day_ = 0; + unsigned int week_ = 0; + unsigned int year_ = 0; +}; + +// ------------------------------------ +// Weekly optimization +// ------------------------------------ +class OptWeeklyStringGenerator final: public OptPeriodStringGenerator +{ +public: + OptWeeklyStringGenerator(unsigned int week, unsigned int year); + std::string to_string() const override; + +private: + unsigned int week_ = 0; + unsigned int year_ = 0; +}; diff --git a/src/solver/utils/include/antares/solver/utils/optimization_statistics.h b/src/solver/utils/include/antares/solver/utils/optimization_statistics.h new file mode 100644 index 0000000000..7a8c54c2db --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/optimization_statistics.h @@ -0,0 +1,124 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_UTILS_STATISTICS_H__ +#define __SOLVER_UTILS_STATISTICS_H__ + +#include +#include +#include + +class OptimizationStatistics +{ +private: + std::atomic totalSolveTime; + std::atomic nbSolve; + + std::atomic totalUpdateTime; + std::atomic nbUpdate; + +public: + void reset() + { + totalSolveTime = 0; + nbSolve = 0; + totalUpdateTime = 0; + nbUpdate = 0; + } + + OptimizationStatistics() + { + this->reset(); + } + + OptimizationStatistics(OptimizationStatistics&& rhs): + totalSolveTime(rhs.totalSolveTime.load()), + nbSolve(rhs.nbSolve.load()), + totalUpdateTime(rhs.totalUpdateTime.load()), + nbUpdate(rhs.nbUpdate.load()) + { + } + + OptimizationStatistics(const OptimizationStatistics&) = delete; + OptimizationStatistics& operator=(const OptimizationStatistics&) = delete; + OptimizationStatistics& operator=(OptimizationStatistics&&) = delete; + + void add(const OptimizationStatistics& other) + { + totalSolveTime += other.totalSolveTime; + totalUpdateTime += other.totalUpdateTime; + nbSolve += other.nbSolve; + nbUpdate += other.nbUpdate; + } + + void addUpdateTime(long long updateTime) + { + totalUpdateTime += updateTime; + nbUpdate++; + } + + void addSolveTime(long long solveTime) + { + totalSolveTime += solveTime; + nbSolve++; + } + + unsigned int getNbUpdate() const + { + return nbUpdate; + } + + long long getTotalSolveTime() const + { + return totalSolveTime; + } + + long long getTotalUpdateTime() const + { + return totalUpdateTime; + } + + double getAverageUpdateTime() const + { + if (nbUpdate == 0) + { + return 0.0; + } + return ((double)totalUpdateTime) / nbUpdate; + } + + double getAverageSolveTime() const + { + if (nbSolve == 0) + { + return 0.0; + } + return ((double)totalSolveTime) / nbSolve; + } + + std::string toString() const + { + return "Average solve time: " + std::to_string(std::lround(getAverageSolveTime())) + " ms, " + + "average update time: " + std::to_string(std::lround(getAverageUpdateTime())) + + " ms"; + } +}; + +#endif diff --git a/src/solver/utils/include/antares/solver/utils/ortools_utils.h b/src/solver/utils/include/antares/solver/utils/ortools_utils.h new file mode 100644 index 0000000000..3dd0970ecc --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/ortools_utils.h @@ -0,0 +1,133 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include + +#include + +// ignore unused parameters warnings from ortools +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +#include "ortools/linear_solver/linear_solver.h" +#pragma GCC diagnostic pop + +#include "ortools_wrapper.h" + +using namespace operations_research; + +void ORTOOLS_EcrireJeuDeDonneesLineaireAuFormatMPS(MPSolver* solver, + Antares::Solver::IResultWriter& writer, + const std::string& filename); + +/*! + * \brief Return list of available ortools solver name on our side + * + * \return List of available ortools solver name + */ +std::list getAvailableOrtoolsSolverName(); + +/*! + * \brief Return a single string containing all solvers available, separated by a ", " and ending + * with a ".". + * + */ +std::string availableOrToolsSolversString(); + +/*! + * \brief Create a MPSolver with correct linear or mixed variant + * + * \return MPSolver + */ +MPSolver* MPSolverFactory(const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* probleme, + const std::string& solverName); + +std::string generateTempPath(const std::string& filename); +void removeTemporaryFile(const std::string& tmpPath); + +class OrtoolsUtils +{ +public: + struct SolverNames + { + std::string LPSolverName, MIPSolverName; + }; + static const std::map solverMap; +}; + +namespace Antares +{ +namespace Optimization +{ + +class Nomenclature +{ +public: + Nomenclature() = delete; + + explicit Nomenclature(char prefix): + prefix_(prefix) + { + } + + void SetTarget(const std::vector& target) + { + target_ = ⌖ + } + + std::string GetName(unsigned index) const + { + if (target_ == nullptr || target_->at(index).empty()) + { + return prefix_ + std::to_string(index); + } + return target_->at(index); + } + +private: + const std::vector* target_ = nullptr; + char prefix_; +}; + +class ProblemSimplexeNommeConverter +{ +public: + explicit ProblemSimplexeNommeConverter( + const std::string& solverName, + const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe); + + MPSolver* Convert(); + +private: + const std::string& solverName_; + const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe_; + Nomenclature variableNameManager_ = Nomenclature('x'); + Nomenclature constraintNameManager_ = Nomenclature('c'); + + void CreateVariable(unsigned idxVar, MPSolver* solver, MPObjective* const objective) const; + void CopyVariables(MPSolver* solver) const; + void UpdateContraints(unsigned idxRow, MPSolver* solver) const; + void CopyRows(MPSolver* solver) const; + void CopyMatrix(const MPSolver* solver) const; +}; +} // namespace Optimization +} // namespace Antares diff --git a/src/solver/utils/include/antares/solver/utils/ortools_wrapper.h b/src/solver/utils/include/antares/solver/utils/ortools_wrapper.h new file mode 100644 index 0000000000..4f688dda4a --- /dev/null +++ b/src/solver/utils/include/antares/solver/utils/ortools_wrapper.h @@ -0,0 +1,53 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __ORTOOLS_WRAPPER__ +#define __ORTOOLS_WRAPPER__ + +#include + +#include + +#include "named_problem.h" + +using namespace operations_research; + +MPSolver* ORTOOLS_Simplexe(Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* Probleme, + MPSolver* ProbSpx, + bool keepBasis, + const Antares::Solver::Optimization::OptimizationOptions& options); + +MPSolver* ORTOOLS_ConvertIfNeeded(const std::string& solverName, + const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* Probleme, + MPSolver* solver); + +void ORTOOLS_ModifierLeVecteurCouts(MPSolver* ProbSpx, const double* costs, int nbVar); +void ORTOOLS_ModifierLeVecteurSecondMembre(MPSolver* ProbSpx, + const double* rhs, + const char* sens, + int nbRow); +void ORTOOLS_CorrigerLesBornes(MPSolver* ProbSpx, + const double* bMin, + const double* bMax, + const int* typeVar, + int nbVar); +void ORTOOLS_LibererProbleme(MPSolver* ProbSpx); + +#endif diff --git a/src/solver/utils/mps_utils.cpp b/src/solver/utils/mps_utils.cpp index 3a40854431..6780b84922 100644 --- a/src/solver/utils/mps_utils.cpp +++ b/src/solver/utils/mps_utils.cpp @@ -1,9 +1,28 @@ -#include - -#include "../simulation/simulation.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/utils/mps_utils.h" -#include "ortools_utils.h" -#include "mps_utils.h" +#include +#include "antares/solver/simulation/simulation.h" +#include "antares/solver/utils/ortools_utils.h" using namespace Antares; using namespace Antares::Data; @@ -24,8 +43,8 @@ constexpr size_t OPT_APPEL_SOLVEUR_BUFFER_SIZE = 256; ** This file is part of Antares_Simulator. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** ** There are special exceptions to the terms and conditions of the @@ -36,20 +55,21 @@ constexpr size_t OPT_APPEL_SOLVEUR_BUFFER_SIZE = 256; ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** SPDX-License-Identifier: MPL-2.0 */ -#include +#include #include #include -#include -#include "filename.h" -#include "../optimisation/opt_constants.h" -#include "name_translator.h" + +#include +#include "antares/solver/optimisation/opt_constants.h" +#include "antares/solver/utils/filename.h" +#include "antares/solver/utils/name_translator.h" using namespace Yuni; @@ -58,14 +78,19 @@ using namespace Yuni; class ProblemConverter { public: - void copyProbSimplexeToProbMps(PROBLEME_MPS* dest, PROBLEME_SIMPLEXE_NOMME* src, NameTranslator& nameTranslator) + void copyProbSimplexeToProbMps(PROBLEME_MPS* dest, + PROBLEME_SIMPLEXE_NOMME* src, + NameTranslator& nameTranslator) { // Variables dest->NbVar = src->NombreDeVariables; mVariableType.resize(src->NombreDeVariables); - // TODO[FOM] use actual variable types when MIP resolution is integrated - std::fill(mVariableType.begin(), mVariableType.end(), SRS_CONTINUOUS_VAR); + for (int var = 0; var < src->NombreDeVariables; var++) + { + mVariableType[var] = src->VariablesEntieres[var] ? SRS_INTEGER_VAR : SRS_CONTINUOUS_VAR; + } + dest->TypeDeVariable = mVariableType.data(); dest->TypeDeBorneDeLaVariable = src->TypeDeVariable; // VARIABLE_BORNEE_DES_DEUX_COTES, // VARIABLE_BORNEE_INFERIEUREMENT, etc. @@ -87,7 +112,8 @@ class ProblemConverter // Names dest->LabelDeLaVariable = nameTranslator.translate(src->VariableNames(), mVariableNames); - dest->LabelDeLaContrainte = nameTranslator.translate(src->ConstraintNames(), mConstraintNames); + dest->LabelDeLaContrainte = nameTranslator.translate(src->ConstraintNames(), + mConstraintNames); } private: @@ -121,8 +147,9 @@ void OPT_EcrireJeuDeDonneesLineaireAuFormatMPS(PROBLEME_SIMPLEXE_NOMME* Prob, // -------------------- // Full mps writing // -------------------- -fullMPSwriter::fullMPSwriter(PROBLEME_SIMPLEXE_NOMME* named_splx_problem, uint optNumber) : - I_MPS_writer(optNumber), named_splx_problem_(named_splx_problem) +fullMPSwriter::fullMPSwriter(PROBLEME_SIMPLEXE_NOMME* named_splx_problem, uint optNumber): + I_MPS_writer(optNumber), + named_splx_problem_(named_splx_problem) { } @@ -134,12 +161,13 @@ void fullMPSwriter::runIfNeeded(Solver::IResultWriter& writer, const std::string // --------------------------------- // Full mps writing by or-tools // --------------------------------- -fullOrToolsMPSwriter::fullOrToolsMPSwriter(MPSolver* solver, uint optNumber) : - I_MPS_writer(optNumber), solver_(solver) +fullOrToolsMPSwriter::fullOrToolsMPSwriter(MPSolver* solver, uint optNumber): + I_MPS_writer(optNumber), + solver_(solver) { } -void fullOrToolsMPSwriter::runIfNeeded(Solver::IResultWriter& writer, - const std::string& filename) + +void fullOrToolsMPSwriter::runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) { ORTOOLS_EcrireJeuDeDonneesLineaireAuFormatMPS(solver_, writer, filename); } @@ -149,13 +177,13 @@ mpsWriterFactory::mpsWriterFactory(Data::mpsExportStatus exportMPS, const int current_optim_number, PROBLEME_SIMPLEXE_NOMME* named_splx_problem, bool ortoolsUsed, - MPSolver* solver) : - export_mps_(exportMPS), - export_mps_on_error_(exportMPSOnError), - named_splx_problem_(named_splx_problem), - ortools_used_(ortoolsUsed), - solver_(solver), - current_optim_number_(current_optim_number) + MPSolver* solver): + export_mps_(exportMPS), + export_mps_on_error_(exportMPSOnError), + named_splx_problem_(named_splx_problem), + ortools_used_(ortoolsUsed), + solver_(solver), + current_optim_number_(current_optim_number) { } diff --git a/src/solver/utils/mps_utils.h b/src/solver/utils/mps_utils.h deleted file mode 100644 index 11dfaaa6c7..0000000000 --- a/src/solver/utils/mps_utils.h +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once - -extern "C" -{ -#include "spx_definition_arguments.h" -#include "spx_fonctions.h" - -#include "srs_api.h" -} - -#include "named_problem.h" -#include "ortools_utils.h" - -using namespace Antares; -using namespace Antares::Data; -using namespace Antares::Optimization; -using namespace operations_research; - -// ====================== -// MPS files writing -// ====================== - -class I_MPS_writer -{ -public: - explicit I_MPS_writer(uint currentOptimNumber) : current_optim_number_(currentOptimNumber) - { - } - I_MPS_writer() = default; - virtual void runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) = 0; - -protected: - uint current_optim_number_ = 0; -}; - -class fullMPSwriter final : public I_MPS_writer -{ -public: - fullMPSwriter(PROBLEME_SIMPLEXE_NOMME* named_splx_problem, uint currentOptimNumber); - void runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) override; - -private: - PROBLEME_SIMPLEXE_NOMME* named_splx_problem_ = nullptr; -}; - -class fullOrToolsMPSwriter : public I_MPS_writer -{ -public: - fullOrToolsMPSwriter(MPSolver* solver, uint currentOptimNumber); - void runIfNeeded(Solver::IResultWriter& writer, const std::string& filename) override; - -private: - MPSolver* solver_ = nullptr; -}; - -class nullMPSwriter : public I_MPS_writer -{ -public: - using I_MPS_writer::I_MPS_writer; - void runIfNeeded(Solver::IResultWriter& /*writer*/, - const std::string& /*filename*/) override - { - // Does nothing - } -}; - -class mpsWriterFactory -{ -public: - mpsWriterFactory(Data::mpsExportStatus exportMPS, - bool exportMPSOnError, - const int current_optim_number, - PROBLEME_SIMPLEXE_NOMME* named_splx_problem, - bool ortoolsUsed, - MPSolver* solver); - - std::unique_ptr create(); - std::unique_ptr createOnOptimizationError(); - -private: - // Member functions... - std::unique_ptr createFullmpsWriter(); - bool doWeExportMPS(); - - // Member data... - Data::mpsExportStatus export_mps_; - bool export_mps_on_error_; - PROBLEME_SIMPLEXE_NOMME* named_splx_problem_ = nullptr; - bool ortools_used_; - MPSolver* solver_ = nullptr; - uint current_optim_number_; -}; diff --git a/src/solver/utils/name_translator.cpp b/src/solver/utils/name_translator.cpp index 6c3374fee1..e9a0d21aa4 100644 --- a/src/solver/utils/name_translator.cpp +++ b/src/solver/utils/name_translator.cpp @@ -1,28 +1,52 @@ -#include "name_translator.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/utils/name_translator.h" + #include #include -char** RealName::translate(const std::vector& src, - std::vector& pointerVec) +char** RealName::translate(const std::vector& src, std::vector& pointerVec) { - std::transform(src.begin(), - src.end(), - std::back_inserter(pointerVec), - [](const std::string& str) { return str.empty() ? nullptr : const_cast(str.data()); }); - return pointerVec.data(); + std::transform(src.begin(), + src.end(), + std::back_inserter(pointerVec), + [](const std::string& str) + { return str.empty() ? nullptr : const_cast(str.data()); }); + return pointerVec.data(); } -char** NullName::translate(const std::vector& src, - std::vector& pointerVec) +char** NullName::translate(const std::vector& src, std::vector& pointerVec) { - pointerVec.assign(src.size(), nullptr); - return pointerVec.data(); + pointerVec.assign(src.size(), nullptr); + return pointerVec.data(); } std::unique_ptr NameTranslator::create(bool useRealNames) { - if (useRealNames) - return std::make_unique(); - else - return std::make_unique(); + if (useRealNames) + { + return std::make_unique(); + } + else + { + return std::make_unique(); + } } diff --git a/src/solver/utils/name_translator.h b/src/solver/utils/name_translator.h deleted file mode 100644 index a179bf1caf..0000000000 --- a/src/solver/utils/name_translator.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -#include -#include - -class NameTranslator -{ -public: - virtual char** translate(const std::vector& src, - std::vector& pointerVec) = 0; - static std::unique_ptr create(bool useRealNames); -}; - -class RealName : public NameTranslator -{ - char** translate(const std::vector& src, - std::vector& pointerVec) override; -}; - -class NullName : public NameTranslator -{ - char** translate(const std::vector& src, - std::vector& pointerVec) override; -}; diff --git a/src/solver/utils/named_problem.cpp b/src/solver/utils/named_problem.cpp index 984e678bc6..cd23fa6e10 100644 --- a/src/solver/utils/named_problem.cpp +++ b/src/solver/utils/named_problem.cpp @@ -1,37 +1,56 @@ -#include "named_problem.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/utils/named_problem.h" + #include -#include -namespace Antares -{ -namespace Optimization -{ +#include "antares/solver/utils/basis_status.h" +namespace Antares::Optimization +{ PROBLEME_SIMPLEXE_NOMME::PROBLEME_SIMPLEXE_NOMME(const std::vector& NomDesVariables, const std::vector& NomDesContraintes, - std::vector& StatutDesVariables, - std::vector& StatutDesContraintes, - bool UseNamedProblems) : - - NomDesVariables(NomDesVariables), - NomDesContraintes(NomDesContraintes), - StatutDesVariables(StatutDesVariables), - StatutDesContraintes(StatutDesContraintes), - useNamedProblems_(UseNamedProblems) + const std::vector& VariablesEntieres, + BasisStatus& basisStatus, + bool UseNamedProblems, + bool SolverLogs): + NomDesVariables(NomDesVariables), + NomDesContraintes(NomDesContraintes), + useNamedProblems_(UseNamedProblems), + VariablesEntieres(VariablesEntieres), + basisStatus(basisStatus) { + AffichageDesTraces = SolverLogs ? OUI_SPX : NON_SPX; } bool PROBLEME_SIMPLEXE_NOMME::isMIP() const { - // TODO replace implementation when MIP is introduced - // For now, no problem is MIP. - return false; + return std::any_of(VariablesEntieres.cbegin(), + VariablesEntieres.cend(), + [](bool x) { return x; }); } bool PROBLEME_SIMPLEXE_NOMME::basisExists() const { - return !StatutDesVariables.empty() && !StatutDesContraintes.empty(); + return basisStatus.exists(); } -} // namespace Optimization -} // namespace Antares +} // namespace Antares::Optimization diff --git a/src/solver/utils/named_problem.h b/src/solver/utils/named_problem.h deleted file mode 100644 index 7e749e29ee..0000000000 --- a/src/solver/utils/named_problem.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include "spx_definition_arguments.h" -#include "spx_fonctions.h" - -#include -#include -#include -#include - -namespace Antares -{ -namespace Optimization -{ -struct PROBLEME_SIMPLEXE_NOMME : public PROBLEME_SIMPLEXE -{ -public: - PROBLEME_SIMPLEXE_NOMME(const std::vector& NomDesVariables, - const std::vector& NomDesContraintes, - std::vector& StatutDesVariables, - std::vector& StatutDesContraintes, - bool UseNamedProblems); - -private: - const std::vector& NomDesVariables; - const std::vector& NomDesContraintes; - bool useNamedProblems_; - -public: - std::vector& StatutDesVariables; - std::vector& StatutDesContraintes; - - bool isMIP() const; - bool basisExists() const; - - bool UseNamedProblems() const - { - return useNamedProblems_; - } - - void SetUseNamedProblems(bool useNamedProblems) - { - useNamedProblems_ = useNamedProblems; - } - - const std::vector& VariableNames() const - { - return NomDesVariables; - } - - const std::vector& ConstraintNames() const - { - return NomDesContraintes; - } -}; -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/utils/opt_period_string_generator.cpp b/src/solver/utils/opt_period_string_generator.cpp index 4422abc616..6d459c39e6 100644 --- a/src/solver/utils/opt_period_string_generator.cpp +++ b/src/solver/utils/opt_period_string_generator.cpp @@ -1,12 +1,34 @@ -#include "opt_period_string_generator.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/utils/opt_period_string_generator.h" // ------------------------------------ // Daily optimization // ------------------------------------ OptDailyStringGenerator::OptDailyStringGenerator(unsigned int day, unsigned int week, - unsigned int year) : - day_(day), week_(week), year_(year) + unsigned int year): + day_(day), + week_(week), + year_(year) { } @@ -21,8 +43,9 @@ std::string OptDailyStringGenerator::to_string() const // ------------------------------------ // Weekly optimization // ------------------------------------ -OptWeeklyStringGenerator::OptWeeklyStringGenerator(unsigned int week, unsigned int year) : - week_(week), year_(year) +OptWeeklyStringGenerator::OptWeeklyStringGenerator(unsigned int week, unsigned int year): + week_(week), + year_(year) { } @@ -31,4 +54,4 @@ std::string OptWeeklyStringGenerator::to_string() const std::string to_return = std::to_string(year_ + 1) + "-"; to_return += std::to_string(week_ + 1); return to_return; -} \ No newline at end of file +} diff --git a/src/solver/utils/opt_period_string_generator.h b/src/solver/utils/opt_period_string_generator.h deleted file mode 100644 index ad8471cfda..0000000000 --- a/src/solver/utils/opt_period_string_generator.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include "../optimisation/opt_period_string_generator_base.h" - -/* - MPS and criterion generated files wear the same time interval sequence in their names. - This time interval sequence is either - (for a weekly optimization), - or -- (for a daily optimization). - So, depending on whether the optimization is weekly or daily, the files are named either : - - problem----optim-nb-.mps - - problem-----optim-nb-.mps - - The following class hierarchy intend to represent these time interval sequences (weekly or - daily), and it turns them into a string when building the names of the previous files. This - hierarchy is designed for polymorphism : whetever the time interval an object of that hierarchy - represents, it is passed as a base class argument, and the right 'to_string()' function is - called. -*/ - -// ------------------------------------ -// Daily optimization -// ------------------------------------ -class OptDailyStringGenerator final : public OptPeriodStringGenerator -{ -public: - OptDailyStringGenerator(unsigned int day, unsigned int week, unsigned int year); - std::string to_string() const override; - -private: - unsigned int day_ = 0; - unsigned int week_ = 0; - unsigned int year_ = 0; -}; - -// ------------------------------------ -// Weekly optimization -// ------------------------------------ -class OptWeeklyStringGenerator final : public OptPeriodStringGenerator -{ -public: - OptWeeklyStringGenerator(unsigned int week, unsigned int year); - std::string to_string() const override; - -private: - unsigned int week_ = 0; - unsigned int year_ = 0; -}; \ No newline at end of file diff --git a/src/solver/utils/optimization_statistics.h b/src/solver/utils/optimization_statistics.h deleted file mode 100644 index 2ecb063017..0000000000 --- a/src/solver/utils/optimization_statistics.h +++ /dev/null @@ -1,100 +0,0 @@ -#ifndef __SOLVER_UTILS_STATISTICS_H__ -#define __SOLVER_UTILS_STATISTICS_H__ - -#include -#include -#include - -class OptimizationStatistics -{ -private: - std::atomic totalSolveTime; - std::atomic nbSolve; - - std::atomic totalUpdateTime; - std::atomic nbUpdate; - -public: - void reset() - { - totalSolveTime = 0; - nbSolve = 0; - totalUpdateTime = 0; - nbUpdate = 0; - } - - OptimizationStatistics() - { - this->reset(); - } - - OptimizationStatistics(OptimizationStatistics &&rhs) - : - totalSolveTime(rhs.totalSolveTime.load()), - nbSolve(rhs.nbSolve.load()), - totalUpdateTime(rhs.totalUpdateTime.load()), - nbUpdate(rhs.nbUpdate.load()) - {} - - OptimizationStatistics(const OptimizationStatistics&) = delete; - OptimizationStatistics& operator=(const OptimizationStatistics&) = delete; - OptimizationStatistics& operator=( OptimizationStatistics&&) = delete; - - void add(const OptimizationStatistics& other) - { - totalSolveTime += other.totalSolveTime; - totalUpdateTime += other.totalUpdateTime; - nbSolve += other.nbSolve; - nbUpdate += other.nbUpdate; - } - - void addUpdateTime(long long updateTime) - { - totalUpdateTime += updateTime; - nbUpdate++; - } - - void addSolveTime(long long solveTime) - { - totalSolveTime += solveTime; - nbSolve++; - } - - unsigned int getNbUpdate() const - { - return nbUpdate; - } - - long long getTotalSolveTime() const - { - return totalSolveTime; - } - - long long getTotalUpdateTime() const - { - return totalUpdateTime; - } - - double getAverageUpdateTime() const - { - if (nbUpdate == 0) - return 0.0; - return ((double)totalUpdateTime) / nbUpdate; - } - - double getAverageSolveTime() const - { - if (nbSolve == 0) - return 0.0; - return ((double)totalSolveTime) / nbSolve; - } - - std::string toString() const - { - return "Average solve time: " + std::to_string(std::lround(getAverageSolveTime())) + " ms, " - + "average update time: " + std::to_string(std::lround(getAverageUpdateTime())) - + " ms"; - } -}; - -#endif diff --git a/src/solver/utils/ortools_utils.cpp b/src/solver/utils/ortools_utils.cpp index dd2f60d693..2cc81b80fa 100644 --- a/src/solver/utils/ortools_utils.cpp +++ b/src/solver/utils/ortools_utils.cpp @@ -1,13 +1,39 @@ -#include "ortools_utils.h" +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "antares/solver/utils/ortools_utils.h" -#include -#include -#include #include +#include +#include +#include +#include "antares/antares/Enum.hpp" +#include "antares/solver/utils/basis_status.h" + using namespace operations_research; -const char* const XPRESS_PARAMS = "THREADS 1"; +const std::string XPRESS_PARAMS = "THREADS 1"; +const std::string SCIP_PARAMS = "parallel/maxnthreads 1"; + +using Antares::Solver::Optimization::OptimizationOptions; // MPSolverParameters's copy constructor is private static void setGenericParameters(MPSolverParameters& params) @@ -16,6 +42,55 @@ static void setGenericParameters(MPSolverParameters& params) params.SetIntegerParam(MPSolverParameters::PRESOLVE, 0); } +static void checkSetSolverSpecificParameters(bool status, + const std::string& solverName, + const std::string& specificParameters) +{ + if (!status) + { + throw Antares::Error::InvalidSolverSpecificParameters(solverName, specificParameters); + } + else + { + Antares::logs.info() << " Successfully set " + solverName + " solver specific parameters"; + } +} + +static void TuneSolverSpecificOptions(MPSolver* solver, + const std::string& solverName, + const std::string& solverParameters) +{ + if (!solver) + { + return; + } + + bool status; + std::string specificParams; + + switch (solver->ProblemType()) + { + // Allow solver to use only one thread + case MPSolver::XPRESS_LINEAR_PROGRAMMING: + case MPSolver::XPRESS_MIXED_INTEGER_PROGRAMMING: + { + specificParams = XPRESS_PARAMS + " " + solverParameters; + status = solver->SetSolverSpecificParametersAsString(specificParams); + checkSetSolverSpecificParameters(status, solverName, specificParams); + break; + } + case MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING: + { + specificParams = SCIP_PARAMS + ", " + solverParameters; + status = solver->SetSolverSpecificParametersAsString(specificParams); + checkSetSolverSpecificParameters(status, solverName, specificParams); + break; + } + default: + break; + } +} + static bool solverSupportsWarmStart(const MPSolver::OptimizationProblemType solverType) { switch (solverType) @@ -33,8 +108,9 @@ namespace Optimization { ProblemSimplexeNommeConverter::ProblemSimplexeNommeConverter( const std::string& solverName, - const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe) : - solverName_(solverName), problemeSimplexe_(problemeSimplexe) + const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe): + solverName_(solverName), + problemeSimplexe_(problemeSimplexe) { if (problemeSimplexe_->UseNamedProblems()) { @@ -46,7 +122,6 @@ ProblemSimplexeNommeConverter::ProblemSimplexeNommeConverter( MPSolver* ProblemSimplexeNommeConverter::Convert() { MPSolver* solver = MPSolverFactory(problemeSimplexe_, solverName_); - TuneSolverSpecificOptions(solver); // Create the variables and set objective cost. CopyVariables(solver); @@ -59,24 +134,7 @@ MPSolver* ProblemSimplexeNommeConverter::Convert() return solver; } -void ProblemSimplexeNommeConverter::TuneSolverSpecificOptions(MPSolver* solver) const -{ - if (!solver) - return; - - switch (solver->ProblemType()) - { - case MPSolver::XPRESS_LINEAR_PROGRAMMING: - case MPSolver::XPRESS_MIXED_INTEGER_PROGRAMMING: - solver->SetSolverSpecificParametersAsString(XPRESS_PARAMS); - break; - // Add solver-specific options here - default: - break; - } -} - -void ProblemSimplexeNommeConverter::CopyMatrix(const MPSolver* solver) +void ProblemSimplexeNommeConverter::CopyMatrix(const MPSolver* solver) const { auto variables = solver->variables(); auto constraints = solver->constraints(); @@ -95,32 +153,31 @@ void ProblemSimplexeNommeConverter::CopyMatrix(const MPSolver* solver) } } -void ProblemSimplexeNommeConverter::UpdateCoefficient(unsigned idxVar, - MPSolver* solver, - MPObjective* const objective) +void ProblemSimplexeNommeConverter::CreateVariable(unsigned idxVar, + MPSolver* solver, + MPObjective* const objective) const { - double min_l = 0.0; - if (problemeSimplexe_->Xmin != NULL) - { - min_l = problemeSimplexe_->Xmin[idxVar]; - } + double min_l = problemeSimplexe_->Xmin[idxVar]; double max_l = problemeSimplexe_->Xmax[idxVar]; - const MPVariable* var = solver->MakeNumVar(min_l, max_l, variableNameManager_.GetName(idxVar)); + bool isIntegerVariable = problemeSimplexe_->IntegerVariable(idxVar); + const MPVariable* var = solver->MakeVar(min_l, + max_l, + isIntegerVariable, + variableNameManager_.GetName(idxVar)); objective->SetCoefficient(var, problemeSimplexe_->CoutLineaire[idxVar]); } -void ProblemSimplexeNommeConverter::CopyVariables(MPSolver* solver) +void ProblemSimplexeNommeConverter::CopyVariables(MPSolver* solver) const { MPObjective* const objective = solver->MutableObjective(); - for (int idxVar = 0; idxVar < problemeSimplexe_->NombreDeVariables; ++idxVar) { - UpdateCoefficient(idxVar, solver, objective); + CreateVariable(idxVar, solver, objective); } } -void ProblemSimplexeNommeConverter::UpdateContraints(unsigned idxRow, MPSolver* solver) +void ProblemSimplexeNommeConverter::UpdateContraints(unsigned idxRow, MPSolver* solver) const { double bMin = -MPSolver::infinity(), bMax = MPSolver::infinity(); if (problemeSimplexe_->Sens[idxRow] == '=') @@ -139,7 +196,7 @@ void ProblemSimplexeNommeConverter::UpdateContraints(unsigned idxRow, MPSolver* solver->MakeRowConstraint(bMin, bMax, constraintNameManager_.GetName(idxRow)); } -void ProblemSimplexeNommeConverter::CopyRows(MPSolver* solver) +void ProblemSimplexeNommeConverter::CopyRows(MPSolver* solver) const { for (int idxRow = 0; idxRow < problemeSimplexe_->NombreDeContraintes; ++idxRow) { @@ -150,29 +207,66 @@ void ProblemSimplexeNommeConverter::CopyRows(MPSolver* solver) } // namespace Optimization } // namespace Antares -static void extract_from_MPSolver(const MPSolver* solver, +static void extractSolutionValues(const std::vector& variables, Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe) { - auto& variables = solver->variables(); int nbVar = problemeSimplexe->NombreDeVariables; - - // Extracting variable values and reduced costs for (int idxVar = 0; idxVar < nbVar; ++idxVar) { - auto& var = variables[idxVar]; + const MPVariable* var = variables[idxVar]; problemeSimplexe->X[idxVar] = var->solution_value(); + } +} + +static void extractReducedCosts(const std::vector& variables, + Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe) +{ + int nbVar = problemeSimplexe->NombreDeVariables; + for (int idxVar = 0; idxVar < nbVar; ++idxVar) + { + const MPVariable* var = variables[idxVar]; problemeSimplexe->CoutsReduits[idxVar] = var->reduced_cost(); } +} - auto& constraints = solver->constraints(); - int nbRow = problemeSimplexe->NombreDeContraintes; - for (int idxRow = 0; idxRow < nbRow; ++idxRow) +static void extractDualValues(const std::vector& constraints, + Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe) +{ + int nbRows = problemeSimplexe->NombreDeContraintes; + for (int idxRow = 0; idxRow < nbRows; ++idxRow) { - auto& row = constraints[idxRow]; + const MPConstraint* row = constraints[idxRow]; problemeSimplexe->CoutsMarginauxDesContraintes[idxRow] = row->dual_value(); } } +static void extract_from_MPSolver(const MPSolver* solver, + Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe) +{ + assert(solver); + assert(problemeSimplexe); + + const bool isMIP = problemeSimplexe->isMIP(); + + extractSolutionValues(solver->variables(), problemeSimplexe); + + if (isMIP) + { + // TODO extract dual values & marginal costs from LP with fixed integer variables + const int nbVar = problemeSimplexe->NombreDeVariables; + std::fill(problemeSimplexe->CoutsReduits, problemeSimplexe->CoutsReduits + nbVar, 0.); + const int nbRows = problemeSimplexe->NombreDeContraintes; + std::fill(problemeSimplexe->CoutsMarginauxDesContraintes, + problemeSimplexe->CoutsMarginauxDesContraintes + nbRows, + 0.); + } + else + { + extractReducedCosts(solver->variables(), problemeSimplexe); + extractDualValues(solver->constraints(), problemeSimplexe); + } +} + std::string generateTempPath(const std::string& filename) { namespace fs = std::filesystem; @@ -241,7 +335,8 @@ MPSolver* ORTOOLS_ConvertIfNeeded(const std::string& solverName, { if (solver == nullptr) { - return Antares::Optimization::ProblemSimplexeNommeConverter(solverName, Probleme).Convert(); + Antares::Optimization::ProblemSimplexeNommeConverter converter(solverName, Probleme); + return converter.Convert(); } else { @@ -251,15 +346,22 @@ MPSolver* ORTOOLS_ConvertIfNeeded(const std::string& solverName, MPSolver* ORTOOLS_Simplexe(Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* Probleme, MPSolver* solver, - bool keepBasis) + bool keepBasis, + const OptimizationOptions& options) { MPSolverParameters params; - setGenericParameters(params); + setGenericParameters( + params); // Keep generic params for default settings working for all solvers + if (options.solverLogs) // May be overriden by log level if set as specific parameters + { + solver->EnableOutput(); + } + TuneSolverSpecificOptions(solver, options.ortoolsSolver, options.solverParameters); const bool warmStart = solverSupportsWarmStart(solver->ProblemType()); // Provide an initial simplex basis, if any if (warmStart && Probleme->basisExists()) { - solver->SetStartingLpBasisInt(Probleme->StatutDesVariables, Probleme->StatutDesContraintes); + Probleme->basisStatus.setStartingBasis(solver); } if (solveAndManageStatus(solver, Probleme->ExistenceDUneSolution, params)) @@ -268,8 +370,7 @@ MPSolver* ORTOOLS_Simplexe(Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* Probl // Save the final simplex basis for next resolutions if (warmStart && keepBasis) { - solver->GetFinalLpBasisInt(Probleme->StatutDesVariables, - Probleme->StatutDesContraintes); + Probleme->basisStatus.extractBasis(solver); } } @@ -295,11 +396,17 @@ void ORTOOLS_ModifierLeVecteurSecondMembre(MPSolver* solver, for (int idxRow = 0; idxRow < nbRow; ++idxRow) { if (sens[idxRow] == '=') + { constraints[idxRow]->SetBounds(rhs[idxRow], rhs[idxRow]); + } else if (sens[idxRow] == '<') + { constraints[idxRow]->SetBounds(-MPSolver::infinity(), rhs[idxRow]); + } else if (sens[idxRow] == '>') + { constraints[idxRow]->SetBounds(rhs[idxRow], MPSolver::infinity()); + } } } @@ -330,28 +437,43 @@ void ORTOOLS_LibererProbleme(MPSolver* solver) delete solver; } -const std::map OrtoolsUtils::solverMap - = {{"xpress", {"xpress_lp", "xpress"}}, - {"sirius", {"sirius_lp", "sirius"}}, - {"coin", {"clp", "cbc"}}, - {"glpk", {"glpk_lp", "glpk"}}}; +const std::map OrtoolsUtils::solverMap = { + {"xpress", {"xpress_lp", "xpress"}}, + {"sirius", {"sirius_lp", "sirius"}}, + {"coin", {"clp", "cbc"}}, + {"glpk", {"glpk_lp", "glpk"}}, + {"scip", {"scip", "scip"}}}; std::list getAvailableOrtoolsSolverName() { std::list result; - for (const auto& solverName : OrtoolsUtils::solverMap) + for (const auto& solverName: OrtoolsUtils::solverMap) { MPSolver::OptimizationProblemType solverType; MPSolver::ParseSolverType(solverName.second.LPSolverName, &solverType); if (MPSolver::SupportsProblemType(solverType)) + { result.push_back(solverName.first); + } } - return result; } +std::string availableOrToolsSolversString() +{ + const std::list availableSolverList = getAvailableOrtoolsSolverName(); + std::ostringstream solvers; + for (const std::string& avail: availableSolverList) + { + bool last = &avail == &availableSolverList.back(); + std::string sep = last ? "." : ", "; + solvers << avail << sep; + } + return solvers.str(); +} + MPSolver* MPSolverFactory(const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* probleme, const std::string& solverName) { @@ -359,14 +481,19 @@ MPSolver* MPSolverFactory(const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* try { if (probleme->isMIP()) + { solver = MPSolver::CreateSolver((OrtoolsUtils::solverMap.at(solverName)).MIPSolverName); + } else + { solver = MPSolver::CreateSolver((OrtoolsUtils::solverMap.at(solverName)).LPSolverName); + } if (!solver) { std::string msg_to_throw = "Solver " + solverName + " not found. \n"; - msg_to_throw += "Please make sure that your OR-Tools install supports solver " + solverName + "."; + msg_to_throw += "Please make sure that your OR-Tools install supports solver " + + solverName + "."; throw Antares::Data::AssertionError(msg_to_throw); } diff --git a/src/solver/utils/ortools_utils.h b/src/solver/utils/ortools_utils.h deleted file mode 100644 index 3ec59ef13d..0000000000 --- a/src/solver/utils/ortools_utils.h +++ /dev/null @@ -1,102 +0,0 @@ -#pragma once - -#include -#include - -#include - -#include "ortools/linear_solver/linear_solver.h" - -#include "ortools_wrapper.h" - -using namespace operations_research; - -void ORTOOLS_EcrireJeuDeDonneesLineaireAuFormatMPS(MPSolver* solver, - Antares::Solver::IResultWriter& writer, - const std::string& filename); - -/*! - * \brief Return list of available ortools solver name on our side - * - * \return List of available ortools solver name - */ -std::list getAvailableOrtoolsSolverName(); - -/*! - * \brief Create a MPSolver with correct linear or mixed variant - * - * \return MPSolver - */ -MPSolver* MPSolverFactory(const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* probleme, - const std::string& solverName); - -std::string generateTempPath(const std::string& filename); -void removeTemporaryFile(const std::string& tmpPath); - -class OrtoolsUtils -{ -public: - struct SolverNames - { - std::string LPSolverName, MIPSolverName; - }; - static const std::map solverMap; -}; - -namespace Antares -{ -namespace Optimization -{ - -class Nomenclature -{ -public: - Nomenclature() = delete; - - explicit Nomenclature(char prefix) : prefix_(prefix) - { - } - - void SetTarget(const std::vector& target) - { - target_ = ⌖ - } - - std::string GetName(unsigned index) const - { - if (target_ == nullptr || target_->at(index).empty()) - { - return prefix_ + std::to_string(index); - } - return target_->at(index); - } - -private: - const std::vector* target_ = nullptr; - char prefix_; -}; - -class ProblemSimplexeNommeConverter -{ -public: - explicit ProblemSimplexeNommeConverter( - const std::string& solverName, - const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe); - - MPSolver* Convert(); - -private: - const std::string& solverName_; - const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* problemeSimplexe_; - Nomenclature variableNameManager_ = Nomenclature('x'); - Nomenclature constraintNameManager_ = Nomenclature('c'); - - void UpdateCoefficient(unsigned idxVar, MPSolver* solver, MPObjective* const objective); - void CopyVariables(MPSolver* solver); - void UpdateContraints(unsigned idxRow, MPSolver* solver); - void CopyRows(MPSolver* solver); - void TuneSolverSpecificOptions(MPSolver* solver) const; - void CopyMatrix(const MPSolver* solver); -}; -} // namespace Optimization -} // namespace Antares diff --git a/src/solver/utils/ortools_wrapper.h b/src/solver/utils/ortools_wrapper.h deleted file mode 100644 index 976c864a49..0000000000 --- a/src/solver/utils/ortools_wrapper.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef __ORTOOLS_WRAPPER__ -#define __ORTOOLS_WRAPPER__ - -#include -#include "named_problem.h" - -using namespace operations_research; - -MPSolver* ORTOOLS_Simplexe(Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* Probleme, - MPSolver* ProbSpx, - bool keepBasis); - -MPSolver* ORTOOLS_ConvertIfNeeded(const std::string& solverName, - const Antares::Optimization::PROBLEME_SIMPLEXE_NOMME* Probleme, - MPSolver* solver); - -void ORTOOLS_ModifierLeVecteurCouts(MPSolver* ProbSpx, const double* costs, int nbVar); -void ORTOOLS_ModifierLeVecteurSecondMembre(MPSolver* ProbSpx, - const double* rhs, - const char* sens, - int nbRow); -void ORTOOLS_CorrigerLesBornes(MPSolver* ProbSpx, - const double* bMin, - const double* bMax, - const int* typeVar, - int nbVar); -void ORTOOLS_LibererProbleme(MPSolver* ProbSpx); - -#endif diff --git a/src/solver/variable/CMakeLists.txt b/src/solver/variable/CMakeLists.txt index df21955781..11ed4b5c9d 100644 --- a/src/solver/variable/CMakeLists.txt +++ b/src/solver/variable/CMakeLists.txt @@ -1,189 +1,185 @@ project(variable) set(SRC_VARIABLE - variable.h - variable.hxx - info.h - container.h - container.hxx - endoflist.h - state.h - state.cpp - state.hxx - area.h - area.hxx - area.inc.hxx - setofareas.h - setofareas.hxx - bindConstraints.h - bindConstraints.hxx - constants.h - categories.h - surveyresults.h - surveyresults/reportbuilder.hxx - surveyresults/surveyresults.h - surveyresults/data.h - surveyresults/surveyresults.cpp - ) + include/antares/solver/variable/variable.h + include/antares/solver/variable/variable.hxx + include/antares/solver/variable/info.h + include/antares/solver/variable/container.h + include/antares/solver/variable/container.hxx + include/antares/solver/variable/endoflist.h + include/antares/solver/variable/state.h + state.cpp + include/antares/solver/variable/state.hxx + include/antares/solver/variable/area.h + include/antares/solver/variable/area.hxx + include/antares/solver/variable/setofareas.h + include/antares/solver/variable/setofareas.hxx + include/antares/solver/variable/bindConstraints.h + include/antares/solver/variable/bindConstraints.hxx + include/antares/solver/variable/categories.h + include/antares/solver/variable/surveyresults.h + include/antares/solver/variable/surveyresults/reportbuilder.hxx + include/antares/solver/variable/surveyresults/surveyresults.h + include/antares/solver/variable/surveyresults/data.h + surveyresults/surveyresults.cpp +) source_group("variable" FILES ${SRC_VARIABLE}) set(SRC_VARIABLE_STORAGE - # Storage - storage/intermediate.h - storage/intermediate.hxx - storage/intermediate.cpp - storage/results.h - storage/empty.h - storage/raw.h - storage/raw.hxx - storage/rawdata.h - storage/rawdata.cpp - storage/minmax.h - storage/minmax.hxx - storage/minmax-data.h - storage/minmax-data.cpp - storage/average.h - storage/averagedata.h - storage/averagedata.cpp - storage/stdDeviation.h - storage/fwd.h - ) + # Storage + include/antares/solver/variable/storage/intermediate.h + include/antares/solver/variable/storage/intermediate.hxx + storage/intermediate.cpp + include/antares/solver/variable/storage/results.h + include/antares/solver/variable/storage/empty.h + include/antares/solver/variable/storage/raw.h + include/antares/solver/variable/storage/raw.hxx + include/antares/solver/variable/storage/rawdata.h + storage/rawdata.cpp + include/antares/solver/variable/storage/minmax.h + include/antares/solver/variable/storage/minmax.hxx + include/antares/solver/variable/storage/minmax-data.h + storage/minmax-data.cpp + include/antares/solver/variable/storage/average.h + include/antares/solver/variable/storage/averagedata.h + storage/averagedata.cpp + include/antares/solver/variable/storage/stdDeviation.h + include/antares/solver/variable/storage/fwd.h +) source_group("variable\\storage" FILES ${SRC_VARIABLE_STORAGE}) set(SRC_VARIABLE_COMMON - # Commons - commons/join.h - commons/load.h - commons/wind.h - commons/hydro.h - commons/rowBalance.h - commons/psp.h - commons/miscGenMinusRowPSP.h - commons/solar.h - commons/spatial-aggregate.h - commons/links/links.cpp.inc.hxx - commons/links/links.h.inc.hxx - commons/links/links.hxx.inc.hxx - ) + # Commons + include/antares/solver/variable/commons/join.h + include/antares/solver/variable/commons/load.h + include/antares/solver/variable/commons/wind.h + include/antares/solver/variable/commons/hydro.h + include/antares/solver/variable/commons/rowBalance.h + include/antares/solver/variable/commons/psp.h + include/antares/solver/variable/commons/miscGenMinusRowPSP.h + include/antares/solver/variable/commons/solar.h + include/antares/solver/variable/commons/spatial-aggregate.h + include/antares/solver/variable/commons/links/links.h + include/antares/solver/variable/commons/links/links.hxx +) source_group("variable\\common" FILES ${SRC_VARIABLE_COMMON}) set(SRC_VARIABLE_ADEQUACY - adequacy/all.h - adequacy/area.cpp - adequacy/area.memory-estimation.cpp - adequacy/bc.memory-estimation.cpp - adequacy/links.h - adequacy/links.cpp - adequacy/spilledEnergy.h - adequacy/overallCost.h - ) + include/antares/solver/variable/adequacy/all.h + include/antares/solver/variable/adequacy/links.h + include/antares/solver/variable/adequacy/spilledEnergy.h + include/antares/solver/variable/adequacy/overallCost.h +) source_group("variable\\adequacy" FILES ${SRC_VARIABLE_ADEQUACY}) set(SRC_VARIABLE_ECONOMY - economy/all.h - economy/links.h - economy/links.cpp - economy/area.cpp - economy/area.memory-estimation.cpp - economy/bc.memory-estimation.cpp - - # Variables for Economy - economy/max-mrg.h - economy/max-mrg.cpp - economy/price.h - economy/balance.h - economy/operatingCost.h - economy/overallCost.h - economy/nonProportionalCost.h - economy/hydrostorage.h - economy/pumping.h - economy/reservoirlevel.h - economy/inflow.h - economy/overflow.h - economy/waterValue.h - economy/hydroCost.h - economy/shortTermStorage.h - economy/STStorageInjectionByCluster.h - economy/STStorageWithdrawalByCluster.h - economy/STStorageLevelsByCluster.h - economy/STStorageCashFlowByCluster.h - economy/unsupliedEnergy.h - economy/domesticUnsuppliedEnergy.h - economy/localMatchingRuleViolations.h - economy/spilledEnergyAfterCSR.h - economy/dtgMarginAfterCsr.h - economy/spilledEnergy.h - economy/dispatchableGeneration.h - economy/renewableGeneration.h - economy/thermalAirPollutantEmissions.h - economy/productionByDispatchablePlant.h - economy/productionByRenewablePlant.h - economy/npCostByDispatchablePlant.h - economy/nbOfDispatchedUnitsByPlant.h - economy/nbOfDispatchedUnits.h - economy/profitByPlant.h - economy/lold.h - economy/lolp.h - economy/avail-dispatchable-generation.h - economy/dispatchable-generation-margin.h - - # Links - economy/links/flowLinear.h - economy/links/flowLinearAbs.h - economy/links/loopFlow.h - economy/links/flowQuad.h - economy/links/hurdleCosts.h - economy/links/congestionFee.h - economy/links/congestionFeeAbs.h - economy/links/marginalCost.h - economy/links/congestionProbability.h - - # Binding constraints - economy/bindingConstraints/bindingConstraintsMarginalCost.h - ) + include/antares/solver/variable/economy/all.h + include/antares/solver/variable/economy/links.h + + # Variables for Economy + include/antares/solver/variable/economy/max-mrg.h + economy/max-mrg.cpp + include/antares/solver/variable/economy/price.h + include/antares/solver/variable/economy/balance.h + include/antares/solver/variable/economy/operatingCost.h + include/antares/solver/variable/economy/overallCost.h + include/antares/solver/variable/economy/nonProportionalCost.h + include/antares/solver/variable/economy/hydrostorage.h + include/antares/solver/variable/economy/pumping.h + include/antares/solver/variable/economy/reservoirlevel.h + include/antares/solver/variable/economy/inflow.h + include/antares/solver/variable/economy/overflow.h + include/antares/solver/variable/economy/waterValue.h + include/antares/solver/variable/economy/hydroCost.h + include/antares/solver/variable/economy/STSbyGroup.h + include/antares/solver/variable/economy/STStorageInjectionByCluster.h + include/antares/solver/variable/economy/STStorageWithdrawalByCluster.h + include/antares/solver/variable/economy/STStorageLevelsByCluster.h + include/antares/solver/variable/economy/STStorageCashFlowByCluster.h + include/antares/solver/variable/economy/unsupliedEnergy.h + include/antares/solver/variable/economy/domesticUnsuppliedEnergy.h + include/antares/solver/variable/economy/localMatchingRuleViolations.h + include/antares/solver/variable/economy/spilledEnergyAfterCSR.h + include/antares/solver/variable/economy/dtgMarginAfterCsr.h + include/antares/solver/variable/economy/spilledEnergy.h + include/antares/solver/variable/economy/dispatchableGeneration.h + include/antares/solver/variable/economy/renewableGeneration.h + include/antares/solver/variable/economy/thermalAirPollutantEmissions.h + include/antares/solver/variable/economy/productionByDispatchablePlant.h + include/antares/solver/variable/economy/productionByRenewablePlant.h + include/antares/solver/variable/economy/npCostByDispatchablePlant.h + include/antares/solver/variable/economy/nbOfDispatchedUnitsByPlant.h + include/antares/solver/variable/economy/nbOfDispatchedUnits.h + include/antares/solver/variable/economy/profitByPlant.h + include/antares/solver/variable/economy/lold.h + include/antares/solver/variable/economy/lolp.h + include/antares/solver/variable/economy/avail-dispatchable-generation.h + include/antares/solver/variable/economy/dispatchable-generation-margin.h + + # Links + include/antares/solver/variable/economy/links/flowLinear.h + include/antares/solver/variable/economy/links/flowLinearAbs.h + include/antares/solver/variable/economy/links/loopFlow.h + include/antares/solver/variable/economy/links/flowQuad.h + include/antares/solver/variable/economy/links/hurdleCosts.h + include/antares/solver/variable/economy/links/congestionFee.h + include/antares/solver/variable/economy/links/congestionFeeAbs.h + include/antares/solver/variable/economy/links/marginalCost.h + include/antares/solver/variable/economy/links/congestionProbability.h + + # Binding constraints + include/antares/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h +) source_group("variable\\economy" FILES ${SRC_VARIABLE_ECONOMY}) - - # # --- Library VARIABLES --- # add_library(antares-solver-variable - ${SRC_VARIABLE} - ${SRC_VARIABLE_COMMON} - ${SRC_VARIABLE_STORAGE} - ${SRC_VARIABLE_ADEQUACY} - ${SRC_VARIABLE_ECONOMY} ) + ${SRC_VARIABLE} + ${SRC_VARIABLE_COMMON} + ${SRC_VARIABLE_STORAGE} + ${SRC_VARIABLE_ADEQUACY} + ${SRC_VARIABLE_ECONOMY}) target_include_directories(antares-solver-variable - PRIVATE - ${CMAKE_SOURCE_DIR}/libs - PUBLIC - .) -target_link_libraries(antares-solver-variable PRIVATE antares-core - Antares::study + PRIVATE + $ + PUBLIC + $ +) +target_link_libraries(antares-solver-variable + PUBLIC + antares-solver-simulation + PRIVATE + antares-core + Antares::study ) add_library(antares-solver-variable-info - adequacy/all.h - economy/all.h - economy/area.memory-estimation.cpp - adequacy/area.memory-estimation.cpp - economy/bc.memory-estimation.cpp - adequacy/bc.memory-estimation.cpp - surveyresults.h - surveyresults/surveyresults.h - surveyresults/data.h - surveyresults/surveyresults.cpp + include/antares/solver/variable/adequacy/all.h + include/antares/solver/variable/economy/all.h + include/antares/solver/variable/surveyresults.h + include/antares/solver/variable/surveyresults/surveyresults.h + include/antares/solver/variable/surveyresults/data.h + surveyresults/surveyresults.cpp ) target_include_directories(antares-solver-variable-info - PRIVATE - ${CMAKE_SOURCE_DIR}/libs + PUBLIC + $ + PRIVATE + $ ) -target_link_libraries(antares-solver-variable-info PRIVATE antares-core - Antares::study +target_link_libraries(antares-solver-variable-info + PRIVATE + antares-core + Antares::study + antares-solver-simulation ) +install(DIRECTORY include/antares + DESTINATION "include" +) diff --git a/src/solver/variable/adequacy/all.h b/src/solver/variable/adequacy/all.h deleted file mode 100644 index 20fb1dc302..0000000000 --- a/src/solver/variable/adequacy/all.h +++ /dev/null @@ -1,269 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ADEQUACY_ALL_H__ -#define __SOLVER_VARIABLE_ADEQUACY_ALL_H__ - -#include "../variable.h" -#include "../area.h" -#include "../setofareas.h" -#include "../bindConstraints.h" - -#include "../economy/thermalAirPollutantEmissions.h" -#include "../economy/price.h" -#include "../economy/balance.h" - -#include "../commons/load.h" -#include "../commons/wind.h" -#include "../commons/hydro.h" -#include "../commons/rowBalance.h" -#include "../commons/psp.h" -#include "../commons/miscGenMinusRowPSP.h" -#include "../commons/solar.h" -#include "../commons/join.h" -#include "../commons/spatial-aggregate.h" - -#include "../economy/dispatchableGeneration.h" -#include "../economy/renewableGeneration.h" -#include "../adequacy/overallCost.h" -#include "../economy/operatingCost.h" -#include "../economy/hydrostorage.h" -#include "../economy/pumping.h" -#include "../economy/reservoirlevel.h" -#include "../economy/inflow.h" -#include "../economy/overflow.h" -#include "../economy/waterValue.h" -#include "../economy/hydroCost.h" -#include "../economy/shortTermStorage.h" -#include "../economy/unsupliedEnergy.h" -#include "../adequacy/spilledEnergy.h" -#include "../economy/productionByDispatchablePlant.h" -#include "../economy/productionByRenewablePlant.h" - -// Short term storage output variables by cluster -#include "../economy/STStorageInjectionByCluster.h" -#include "../economy/STStorageWithdrawalByCluster.h" -#include "../economy/STStorageLevelsByCluster.h" - -#include "../economy/lold.h" -#include "../economy/lolp.h" -#include "../economy/max-mrg.h" - -#include "../economy/avail-dispatchable-generation.h" -#include "../economy/dispatchable-generation-margin.h" - -#include "../economy/links/flowLinear.h" -#include "../economy/links/flowLinearAbs.h" -#include "../economy/links/flowQuad.h" -#include "../economy/links/hurdleCosts.h" -#include "../economy/links/congestionFee.h" -#include "../economy/links/congestionFeeAbs.h" -#include "../economy/links/marginalCost.h" -#include "../economy/links/congestionProbability.h" - -// Output variables associated to binding constraints -#include "../economy/bindingConstraints/bindingConstraintsMarginalCost.h" - -// By thermal plant -#include "../economy/profitByPlant.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Adequacy -{ -/*! -** \brief All variables for a single link (economy) -*/ -typedef Variable::Economy::FlowLinear // Flow linear - >>>>>>> - VariablePerLink; -// forward declaration -class Links; - -/*! -** \brief All variables for a single area (economy) -*/ -typedef // Prices - Variable::Adequacy::OverallCost // Overall Cost (Op. Cost + Unsupplied Eng.) - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - VariablesPerArea; - -/*! -** \brief All variables for a single set of areas (economy) -*/ -typedef // Prices - Common::SpatialAggregate< - Variable::Adequacy::OverallCost, - Common::SpatialAggregate< - Variable::Economy::OperatingCost, - Common::SpatialAggregate< - Variable::Economy::Price, - // pollutant - Common::SpatialAggregate< - Variable::Economy::ThermalAirPollutantEmissions, - // Production by thermal cluster - Common::SpatialAggregate< - Variable::Economy::Balance, - // Misc Gen. - Common::SpatialAggregate< - Variable::Economy::RowBalance, - Common::SpatialAggregate< - Variable::Economy::PSP, - Common::SpatialAggregate< - Variable::Economy::MiscGenMinusRowPSP, - // Time series - Common::SpatialAggregate< - Variable::Economy::TimeSeriesValuesLoad, - Common::SpatialAggregate< - Variable::Economy::TimeSeriesValuesHydro, - Common::SpatialAggregate< - Variable::Economy::TimeSeriesValuesWind, - Common::SpatialAggregate< - Variable::Economy::TimeSeriesValuesSolar, - // Other - Common::SpatialAggregate< - Variable::Economy::DispatchableGeneration, - Common::SpatialAggregate< - Variable::Economy::RenewableGeneration, - Common::SpatialAggregate< - Variable::Economy::HydroStorage, - Common::SpatialAggregate< - Variable::Economy::Pumping, - Common::SpatialAggregate< - Variable::Economy::ReservoirLevel, - Common::SpatialAggregate< - Variable::Economy::Inflows, - Common::SpatialAggregate< - Variable::Economy::Overflows, - Common::SpatialAggregate< - Variable::Economy::WaterValue, - Common::SpatialAggregate< - Variable::Economy::HydroCost, - Common::SpatialAggregate< - Variable::Economy::ShortTermStorageByGroup, - Common::SpatialAggregate< - Variable::Economy::UnsupliedEnergy, - Common::SpatialAggregate< - Variable::Adequacy::SpilledEnergy, - // LOLD - Common::SpatialAggregate< - Variable::Economy::LOLD, - Common::SpatialAggregate< - Variable::Economy::LOLP, - - Common::SpatialAggregate< - Variable::Economy::AvailableDispatchGen, - Common::SpatialAggregate< - Variable::Economy::DispatchableGenMargin, - Common::SpatialAggregate< - Variable::Economy:: - Marge>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - VariablesPerSetOfAreas; - -typedef Variable::Economy::BindingConstMarginCost< // Marginal cost for a binding constraint - Container::EndOfList // End of variable list - > - - VariablesPerBindingConstraints; - -typedef Variable::Join< - // Variables for each area / links attached to the areas - Variable::Areas, - // Variables for each set of areas - Variable::SetsOfAreas, - // Variables for each binding constraint - Variable::BindingConstraints> - ItemList; - -/*! -** \brief All variables for a simulation (economy) -*/ -typedef Container::List AllVariables; - -} // namespace Adequacy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -// post include -#include "links.h" - -#endif // __SOLVER_VARIABLE_ADEQUACY_ALL_H__ diff --git a/src/solver/variable/adequacy/area.cpp b/src/solver/variable/adequacy/area.cpp deleted file mode 100644 index 4071772e65..0000000000 --- a/src/solver/variable/adequacy/area.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "all.h" - -#define NEXTTYPE Adequacy::VariablesPerArea -#include "../area.inc.hxx" \ No newline at end of file diff --git a/src/solver/variable/adequacy/area.memory-estimation.cpp b/src/solver/variable/adequacy/area.memory-estimation.cpp deleted file mode 100644 index c3d22076b2..0000000000 --- a/src/solver/variable/adequacy/area.memory-estimation.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "all.h" - -using NEXTTYPE = Solver::Variable::Adequacy::VariablesPerArea; -#include "../area.memory-estimation.inc.hxx" diff --git a/src/solver/variable/adequacy/bc.memory-estimation.cpp b/src/solver/variable/adequacy/bc.memory-estimation.cpp deleted file mode 100644 index 510475be9e..0000000000 --- a/src/solver/variable/adequacy/bc.memory-estimation.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "all.h" - -using bc_next_type = Solver::Variable::Adequacy::VariablesPerBindingConstraints; - -#include "../bc.memory-estimation.inc.hxx" diff --git a/src/solver/variable/adequacy/links.cpp b/src/solver/variable/adequacy/links.cpp deleted file mode 100644 index 0f0dde8bf0..0000000000 --- a/src/solver/variable/adequacy/links.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "links.h" -#include "../commons/links/links.cpp.inc.hxx" diff --git a/src/solver/variable/adequacy/links.h b/src/solver/variable/adequacy/links.h deleted file mode 100644 index 38f53b3daf..0000000000 --- a/src/solver/variable/adequacy/links.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ADEQUACY_LINK_H__ -#define __SOLVER_VARIABLE_ADEQUACY_LINK_H__ - -#ifdef LINK_NAMESPACE -#undef LINK_NAMESPACE -#endif -#define LINK_NAMESPACE Adequacy - -#include -#include "all.h" -#include "../commons/links/links.h.inc.hxx" - -#endif // __SOLVER_VARIABLE_ADEQUACY_LINK_H__ diff --git a/src/solver/variable/adequacy/overallCost.h b/src/solver/variable/adequacy/overallCost.h deleted file mode 100644 index 3a501d8f71..0000000000 --- a/src/solver/variable/adequacy/overallCost.h +++ /dev/null @@ -1,314 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ADEQUACY_OverallCost_H__ -#define __SOLVER_VARIABLE_ADEQUACY_OverallCost_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Adequacy -{ -struct VCardOverallCost -{ - //! Caption - static std::string Caption() - { - return "OV. COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Overall Cost throughout all MC years"; - } - - //! The expecte results - typedef Results, - R::AllYears::Average // Use these values for spatial cluster - > - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardOverallCost VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OverallCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class OverallCost : public Variable::IVariable, NextT, VCardOverallCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardOverallCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~OverallCost() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = 0; i < state.study.runtime->rangeLimits.hour[Data::rangeCount]; ++i) - { - pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterOperatingCostForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - auto area = state.area; - auto& thermal = state.thermal; - // Total UnsupliedEnergy emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] += - // Current Hydro Storage generation - (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] - * area->thermal.unsuppliedEnergyCost) - + ((state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek] - + state.resSpilled.entry[area->index][state.hourInTheWeek]) - * area->thermal.spilledEnergyCost); - - // Hydro costs : water value and pumping - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += state.problemeHebdo->CaracteristiquesHydrauliques[state.area->index] - .WeeklyWaterValueStateRegular - * (state.hourlyResults->TurbinageHoraire[state.hourInTheWeek] - - area->hydro.pumpingEfficiency - * state.hourlyResults->PompageHoraire[state.hourInTheWeek]); - - // Thermal costs - for (uint clusterIndex = 0; clusterIndex != area->thermal.clusterCount(); ++clusterIndex) - { - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - += thermal[area->index].thermalClustersOperatingCost[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; -}; // class OverallCost - -} // namespace Adequacy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ADEQUACY_OverallCost_H__ diff --git a/src/solver/variable/adequacy/spilledEnergy.h b/src/solver/variable/adequacy/spilledEnergy.h deleted file mode 100644 index e176be53c9..0000000000 --- a/src/solver/variable/adequacy/spilledEnergy.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ADEQUACY_SpilledEnergy_H__ -#define __SOLVER_VARIABLE_ADEQUACY_SpilledEnergy_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Adequacy -{ -struct VCardSpilledEnergy -{ - //! Caption - static std::string Caption() - { - return "SPIL. ENRG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Spilled Energy (generation that cannot be satisfied)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSpilledEnergy VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall SpilledEnergy emissions expected from all -** the thermal dispatchable clusters -*/ -template -class SpilledEnergy : public Variable::IVariable, NextT, VCardSpilledEnergy> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSpilledEnergy VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~SpilledEnergy() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - assert(state.hourlyResults && "Invalid pointer to simplex results"); - - // Total SpilledEnergy emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = +state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek] - + state.resSpilled.entry[state.area->index][state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class SpilledEnergy - -} // namespace Adequacy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ADEQUACY_SpilledEnergy_H__ diff --git a/src/solver/variable/area.h b/src/solver/variable/area.h deleted file mode 100644 index de4a5315a2..0000000000 --- a/src/solver/variable/area.h +++ /dev/null @@ -1,230 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_AREA_H__ -#define __SOLVER_VARIABLE_AREA_H__ - -#include "state.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -struct VCardAllAreas -{ - //! Caption - static std::string Caption() - { - return "Areas"; - } - //! Unit - static std::string Unit() - { - return ""; - } - - //! The short description of the variable - static std::string Description() - { - return ""; - } - - //! The expecte results - typedef Results<> ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & Category::de, - //! Indentation (GUI) - nodeDepthForGUI = +1, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 0, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - //! Intermediate values - hasIntermediateValues = 0, - }; - -}; // class VCard - -template -class Areas //: public Variable::IVariable, NextT, VCardAllAreas> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardAllAreas VCardType; - //! Ancestor - // typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - enum - { - //! How many items have we got - count = NextT::count, - }; - - template - struct Statistics - { - enum - { - count = NextType::template Statistics::count - }; - }; - -public: - /*! - ** \brief Retrieve the list of all individual variables - ** - ** The predicate must implement the method `add(name, unit, comment)`. - */ - template - static void RetrieveVariableList(PredicateT& predicate); - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - Areas(); - //! Destructor - ~Areas(); - //@} - - void initializeFromStudy(Data::Study& study); - void initializeFromArea(Data::Study*, Data::Area*); - void initializeFromThermalCluster(Data::Study*, Data::Area*, Data::ThermalCluster*); - void initializeFromAreaLink(Data::Study*, Data::AreaLink*); - - void simulationBegin(); - void simulationEnd(); - - void yearBegin(uint year, uint numSpace); - // void yearEndBuildPrepareDataForEachThermalCluster(State& state, uint year); - // void yearEndBuildForEachThermalCluster(State& state, uint year); - - void yearEndBuild(State& state, uint year, uint numSpace); - - void yearEnd(uint year, uint numSpace); - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary); - - void hourBegin(uint hourInTheYear); - - void hourForEachArea(State& state, uint numSpace); - void hourForEachLink(State& state, uint numSpace); - - void hourEnd(State& state, uint hourInTheYear); - - void weekBegin(State& state); - void weekForEachArea(State& state, uint numSpace); - void weekEnd(State& state); - - void buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const; - - void buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - uint numSpace) const; - - void buildDigest(SurveyResults&, int digestLevel, int dataLevel) const; - - void beforeYearByYearExport(uint year, uint numSpace); - - uint64_t memoryUsage() const; - - template - static void provideInformations(I& infos); - - template - void yearEndSpatialAggregates(V&, uint, uint) - { - // do nothing - } - - template - void computeSpatialAggregatesSummary(V&, std::map&, unsigned int) - { - // do nothing - } - - template - void simulationEndSpatialAggregates(V&) - { - // do nothing - } - - template - void computeSpatialAggregateWith(O& out); - - template - void computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace); - - template - const double* retrieveHourlyResultsForCurrentYear() const; - - template - void retrieveResultsForArea(typename Storage::ResultsType** result, - const Data::Area* area); - - template - void retrieveResultsForThermalCluster(typename Storage::ResultsType** result, - const Data::ThermalCluster* cluster); - - template - void retrieveResultsForLink(typename Storage::ResultsType** result, - const Data::AreaLink* link); - -private: - //! Area list - NextType* pAreas; - //! The number of areas - uint pAreaCount; - -}; // class Areas - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#include "area.hxx" - -#endif // __SOLVER_VARIABLE_AREA_H__ diff --git a/src/solver/variable/area.hxx b/src/solver/variable/area.hxx deleted file mode 100644 index a41b8dbf50..0000000000 --- a/src/solver/variable/area.hxx +++ /dev/null @@ -1,283 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_AREA_HXX__ -#define __SOLVER_VARIABLE_AREA_HXX__ - -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -template -inline Areas::Areas() -{ - // Do nothing -} - -template -inline void Areas::initializeFromArea(Data::Study*, Data::Area*) -{ - // Nothing to do here - // This method is called by initializeFromStudy() to all children -} - -template -inline void Areas::initializeFromAreaLink(Data::Study*, Data::AreaLink*) -{ - // Nothing to do here -} - -template -inline void Areas::initializeFromThermalCluster(Data::Study*, - Data::Area*, - Data::ThermalCluster*) -{ - // This method should not be called at this point -} - -template -void Areas::buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const -{ - int count_int = count; - bool linkDataLevel = dataLevel & Category::link; - bool areaDataLevel = dataLevel & Category::area; - bool thermalAggregateDataLevel = dataLevel & Category::thermalAggregate; - if (count_int && (linkDataLevel || areaDataLevel || thermalAggregateDataLevel)) - { - assert(results.data.area != NULL - && "The area must not be null to generate a survey report"); - - // Build the survey results for the given area - auto& area = *results.data.area; - - // Filtering - if (0 == (dataLevel & Category::link)) // filter on all but links - { - switch (precision) - { - case Category::hourly: - if (not(area.filterSynthesis & Data::filterHourly)) - return; - break; - case Category::daily: - if (not(area.filterSynthesis & Data::filterDaily)) - return; - break; - case Category::weekly: - if (not(area.filterSynthesis & Data::filterWeekly)) - return; - break; - case Category::monthly: - if (not(area.filterSynthesis & Data::filterMonthly)) - return; - break; - case Category::annual: - if (not(area.filterSynthesis & Data::filterAnnual)) - return; - break; - case Category::all: - break; - } - } - pAreas[area.index].buildSurveyReport(results, dataLevel, fileLevel, precision); - } -} - -template -void Areas::buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - uint numSpace) const -{ - int count_int = count; - bool linkDataLevel = dataLevel & Category::link; - bool areaDataLevel = dataLevel & Category::area; - bool thermalAggregateDataLevel = dataLevel & Category::thermalAggregate; - if (count_int && (linkDataLevel || areaDataLevel || thermalAggregateDataLevel)) - { - assert(results.data.area != NULL - && "The area must not be null to generate a survey report"); - - auto& area = *results.data.area; - - // Filtering - if (0 == (dataLevel & Category::link)) // filter on all but links - { - switch (precision) - { - case Category::hourly: - if (!(area.filterYearByYear & Data::filterHourly)) - return; - break; - case Category::daily: - if (!(area.filterYearByYear & Data::filterDaily)) - return; - break; - case Category::weekly: - if (!(area.filterYearByYear & Data::filterWeekly)) - return; - break; - case Category::monthly: - if (!(area.filterYearByYear & Data::filterMonthly)) - return; - break; - case Category::annual: - if (!(area.filterYearByYear & Data::filterAnnual)) - return; - break; - case Category::all: - break; - } - } - - // Build the survey results for the given area - pAreas[area.index].buildAnnualSurveyReport( - results, dataLevel, fileLevel, precision, numSpace); - } -} - -template -void Areas::buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const -{ - int count_int = count; - if (count_int) - { - if (dataLevel & Category::area) - { - assert(pAreaCount == results.data.study.areas.size()); - - // Reset captions - results.data.rowCaptions.clear(); - results.data.rowCaptions.resize(pAreaCount); - - // For each area - // for (uint i = 0; i != results.data.study.areas.byIndex.size(); ++i) - for (uint i = 0; i != pAreaCount; ++i) - { - results.data.area = results.data.study.areas[i]; - uint index = results.data.area->index; - results.data.rowIndex = index; - results.data.rowCaptions[index] = results.data.area->id; - results.data.columnIndex = 0; - results.resetValuesAtLine(i); - pAreas[i].buildDigest(results, digestLevel, dataLevel); - } - } - } -} - -template -template -inline void Areas::RetrieveVariableList(PredicateT& predicate) -{ - NextType::RetrieveVariableList(predicate); -} - -template -template -inline void Areas::provideInformations(I& infos) -{ - // Begining of the node - if (VCardType::nodeDepthForGUI) - { - infos.template beginNode(); - // Next variable in the list - NextType::template provideInformations(infos); - // End of the node - infos.endNode(); - } - else - { - // Giving our VCard - infos.template addVCard(); - // Next variable in the list - NextType::template provideInformations(infos); - } -} - -template -template -inline void Areas::computeSpatialAggregateWith(O&) -{ - // Do nothing -} - -template -template -inline void Areas::computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace) -{ - assert(NULL != area); - pAreas[area->index].template computeSpatialAggregateWith(out, numSpace); -} - -template -template -const double* Areas::retrieveHourlyResultsForCurrentYear() const -{ - return nullptr; -} - -template -template -inline void Areas::retrieveResultsForArea( - typename Storage::ResultsType** result, - const Data::Area* area) -{ - pAreas[area->index].template retrieveResultsForArea(result, area); -} - -template -template -inline void Areas::retrieveResultsForThermalCluster( - typename Storage::ResultsType** result, - const Data::ThermalCluster* cluster) -{ - pAreas[cluster->parentArea->index].template retrieveResultsForThermalCluster( - result, cluster); -} - -template -template -inline void Areas::retrieveResultsForLink( - typename Storage::ResultsType** result, - const Data::AreaLink* link) -{ - pAreas[link->from->index].template retrieveResultsForLink(result, link); -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_AREA_HXX__ diff --git a/src/solver/variable/area.inc.hxx b/src/solver/variable/area.inc.hxx deleted file mode 100644 index c6475d6110..0000000000 --- a/src/solver/variable/area.inc.hxx +++ /dev/null @@ -1,286 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "variable.h" -#include "area.h" -#include - -using namespace Yuni; - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -// forward declaration -struct VCardDispatchableGenMargin; - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -template<> -Areas::~Areas() -{ - // Releasing the memory occupied by the areas - delete[] pAreas; -} - -template<> -void Areas::initializeFromStudy(Data::Study& study) -{ - // The total number of areas - pAreaCount = study.areas.size(); - - // Reserving the memory - pAreas = new NextType[pAreaCount]; - - // For each area... - uint tick = 6; - uint oldPercent = 0; - for (uint i = 0; i != pAreaCount; ++i) - { - // Instancing a new set of variables of the area - auto* currentArea = study.areas.byIndex[i]; - if (!(--tick)) - { - uint newPercent = ((i * 100u) / pAreaCount); - if (newPercent != oldPercent) - { - logs.info() << "Allocating resources " << ((i * 100u) / pAreaCount) << "%"; - oldPercent = newPercent; - } - // Reset the tick - tick = 6; - } - - // Initialize the variables - // From the study - pAreas[i].initializeFromStudy(study); - // From the area - pAreas[i].initializeFromArea(&study, currentArea); - // Does current output variable appears non applicable in areas' output files, not - // districts'. Note that digest gather area and district results. - pAreas[i].broadcastNonApplicability(not currentArea->hydro.reservoirManagement); - - // For each current area's variable, getting the print status, that is : - // is variable's column(s) printed in output (areas) reports ? - pAreas[i].getPrintStatusFromStudy(study); - - pAreas[i].supplyMaxNumberOfColumns(study); - } -} - -template<> -void Areas::simulationBegin() -{ - for (uint i = 0; i != pAreaCount; ++i) - { - pAreas[i].simulationBegin(); - } -} - -template<> -void Areas::simulationEnd() -{ - for (uint i = 0; i != pAreaCount; ++i) - { - pAreas[i].simulationEnd(); - } -} - -template<> -void Areas::hourForEachArea(State& state, uint numSpace) -{ - // For each area... - state.study.areas.each([&](Data::Area& area) { - state.area = &area; // the current area - - // Initializing the state for the current area - state.initFromAreaIndex(area.index, numSpace); - - // For each thermal cluster - for (uint j = 0; j != area.thermal.clusterCount(); ++j) - { - // Intiializing the state for the current thermal cluster - state.initFromThermalClusterIndex(j); - } - - // Variables - auto& variablesForArea = pAreas[area.index]; - variablesForArea.hourForEachArea(state, numSpace); - - // All links - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - { - state.link = i->second; - // Variables - variablesForArea.hourForEachLink(state, numSpace); - } - }); // for each area -} - -template<> -void Areas::weekForEachArea(State& state, uint numSpace) -{ - // For each area... - state.study.areas.each([&](Data::Area& area) { - state.area = &area; // the current area - - // Initializing the state for the current area - state.initFromAreaIndex(area.index, numSpace); - - auto& variablesForArea = pAreas[area.index]; - - // DTG MRG - state.dispatchableMargin - = variablesForArea - .retrieveHourlyResultsForCurrentYear(numSpace); - - variablesForArea.weekForEachArea(state, numSpace); - - // NOTE - // currently, the event is not broadcasted to thermal - // clusters and links - }); // for each area -} - -template<> -void Areas::yearBegin(uint year, uint numSpace) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].yearBegin(year, numSpace); -} - -template<> -void Areas::yearEndBuild(State& state, uint year, uint numSpace) -{ - // For each area... - state.study.areas.each([&](Data::Area& area) { - state.area = &area; // the current area - - // Initializing the state for the current area - state.initFromAreaIndex(area.index, numSpace); - - // Variables - auto& variablesForArea = pAreas[area.index]; - - // For each thermal cluster - for (uint j = 0; j != area.thermal.clusterCount(); ++j) - { - state.thermalCluster = area.thermal.clusters[j]; - state.yearEndResetThermal(); - - // Variables - variablesForArea.yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); - - // Building the end of year - state.yearEndBuildFromThermalClusterIndex(j); - - // Variables - variablesForArea.yearEndBuildForEachThermalCluster(state, year, numSpace); - } // for each thermal cluster - }); // for each area -} - -template<> -void Areas::yearEnd(uint year, uint numSpace) -{ - for (uint i = 0; i != pAreaCount; ++i) - { - // Broadcast to all areas - pAreas[i].yearEnd(year, numSpace); - } -} - -template<> -void Areas::computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) -{ - for (uint i = 0; i != pAreaCount; ++i) - { - // Broadcast to all areas - pAreas[i].computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } -} - -template<> -void Areas::weekBegin(State& state) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].weekBegin(state); -} - -template<> -void Areas::weekEnd(State& state) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].weekEnd(state); -} - -template<> -void Areas::hourBegin(uint hourInTheYear) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].hourBegin(hourInTheYear); -} - -template<> -void Areas::hourForEachLink(State& state, uint numSpace) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].hourForEachLink(state, numSpace); -} - -template<> -void Areas::hourEnd(State& state, uint hourInTheYear) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].hourEnd(state, hourInTheYear); -} - -template<> -void Areas::beforeYearByYearExport(uint year, uint numSpace) -{ - for (uint i = 0; i != pAreaCount; ++i) - pAreas[i].beforeYearByYearExport(year, numSpace); -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares diff --git a/src/solver/variable/area.memory-estimation.inc.hxx b/src/solver/variable/area.memory-estimation.inc.hxx deleted file mode 100644 index 75614864e6..0000000000 --- a/src/solver/variable/area.memory-estimation.inc.hxx +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "variable.h" -#include "area.h" -#include - -using namespace Yuni; - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -template<> -uint64_t Areas::memoryUsage() const -{ - uint64_t result = 0; - for (unsigned int i = 0; i != pAreaCount; ++i) - { - result += sizeof(NextType) + sizeof(void*); // overhead vector - result += pAreas[i].memoryUsage(); - } - return result; -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares diff --git a/src/solver/variable/bc.memory-estimation.inc.hxx b/src/solver/variable/bc.memory-estimation.inc.hxx deleted file mode 100644 index 136347c513..0000000000 --- a/src/solver/variable/bc.memory-estimation.inc.hxx +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -using namespace Yuni; - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -template<> -uint64_t BindingConstraints::memoryUsage() const -{ - uint64_t result = 0; - for (unsigned int i = 0; i != pBCcount; ++i) - { - result += sizeof(NextType) + sizeof(void*); // overhead vector - result += pBindConstraints[i].memoryUsage(); - } - return result; -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares diff --git a/src/solver/variable/bindConstraints.h b/src/solver/variable/bindConstraints.h deleted file mode 100644 index c6a21c799c..0000000000 --- a/src/solver/variable/bindConstraints.h +++ /dev/null @@ -1,171 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "state.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -struct VCardAllBindingConstraints -{ - //! Caption - static std::string Caption() - { - return "Binding constraints"; - } - //! Unit - static std::string Unit() - { - return ""; - } - - //! The short description of the variable - static std::string Description() - { - return ""; - } - - //! The expecte results - typedef Results<> ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::bindingConstraint, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & Category::bc, - //! Indentation (GUI) - nodeDepthForGUI = +1, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 0, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - //! Intermediate values - hasIntermediateValues = 0, - }; - -}; // class VCardAllBindingConstraints - -template -class BindingConstraints -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardAllBindingConstraints VCardType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - enum - { - //! How many items have we got - count = NextT::count, - }; - - template - struct Statistics - { - enum - { - count = NextType::template Statistics::count - }; - }; - -public: - - /*! - ** \brief Retrieve the list of all individual variables - ** - ** The predicate must implement the method `add(name, unit, comment)`. - */ - template - static void RetrieveVariableList(PredicateT& predicate); - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - BindingConstraints() = default; - - BindingConstraints(BindingConstraints& other) = delete; - BindingConstraints(BindingConstraints&& other) = delete; - BindingConstraints const& operator=(BindingConstraints&& other) = delete; - - //! Destructor - ~BindingConstraints() = default; - //@} - - void initializeFromStudy(Data::Study& study); - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary); - - void yearBegin(uint year, uint numSpace); - void yearEnd(uint year, uint numSpace); - - void weekBegin(State& state); - - void hourBegin(uint hourInTheYear); - void hourEnd(State& state, uint hourInTheYear); - - void buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const; - - void buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - uint numSpace) const; - - uint64_t memoryUsage() const; - - template - static void provideInformations(I& infos); - -private: - // For each binding constraint, output variable static list associated. - std::vector pBindConstraints; - // The number of counted binding constraints - uint pBCcount; - -}; // class Areas - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#include "bindConstraints.hxx" diff --git a/src/solver/variable/bindConstraints.hxx b/src/solver/variable/bindConstraints.hxx deleted file mode 100644 index 733ddecbd7..0000000000 --- a/src/solver/variable/bindConstraints.hxx +++ /dev/null @@ -1,198 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include -#include -#include "antares/study/binding_constraint/BindingConstraint.h" -#include "antares/study/fwd.h" -#include "bindConstraints.h" - -namespace Antares::Solver::Variable -{ -template -void BindingConstraints::buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const -{ - if (bool bcDataLevel = dataLevel & Category::bindingConstraint; !bcDataLevel) - return; - - for (uint i = 0; i != pBCcount; ++i) - { - const NextType& bc = pBindConstraints[i]; - - bc.buildSurveyReport(results, dataLevel, fileLevel, precision); - } -} - -template -void BindingConstraints::buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - uint numSpace) const -{ - if (bool bcDataLevel = dataLevel & Category::bindingConstraint; !bcDataLevel) - return; - - for (uint i = 0; i != pBCcount; ++i) - { - const NextType& bc = pBindConstraints[i]; - - bc.buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); - } -} - -template -template -inline void BindingConstraints::RetrieveVariableList(PredicateT& predicate) -{ - NextType::RetrieveVariableList(predicate); -} - -template -template -inline void BindingConstraints::provideInformations(I& infos) -{ - // Begining of the node - if (VCardType::nodeDepthForGUI) - { - infos.template beginNode(); - // Next variable in the list - NextType::template provideInformations(infos); - // End of the node - infos.endNode(); - } - else - { - // Giving our VCard - infos.template addVCard(); - // Next variable in the list - NextType::template provideInformations(infos); - } -} - -template -void BindingConstraints::initializeFromStudy(Data::Study& study) -{ - const std::vector InequalityBCindices - = study.bindingConstraints.getIndicesForInequalityBindingConstraints(); - - // The total number of inequality binding constraints count - // (we don't count BCs with equality sign) - pBCcount = (uint)InequalityBCindices.size(); - - // Reserving the memory - if (pBCcount > 0) - { - pBindConstraints.resize(pBCcount); - } - - for (uint i = 0; i != pBCcount; ++i) - { - NextType& bc = pBindConstraints[i]; - - bc.setBindConstraintGlobalIndex(InequalityBCindices[i]); - bc.initializeFromStudy(study); - - // Does user want to print output results related to the current binding constraint ? - bc.getPrintStatusFromStudy(study); - } - - // Here we supply the max number of columns to the variable print info collector - // This is a ugly hack (it's a work around). - // We should have a simple call to : - // NextType::supplyMaxNumberOfColumns(study); - // Instead, we have a few lines as a hack. - // What we have to do is add to the print info collector a single VariablePrintInfo - // that has a max columns size of : (nb of inequality BCs) x ResultsType::count - // But note that for now, BC output variables are chained statically (one output variable per inequality BC). - // The hack is to make the first BC output variable able to supply max columns size for all BC output variables - // with its method getMaxNumberColumns(). - // A solution would be to make BC output variables (like BindingConstMarginCost) some DYNAMIC variables. - if (pBCcount > 0) - { - NextType& bc = pBindConstraints[0]; - bc.setBindConstraintsCount(pBCcount); - bc.supplyMaxNumberOfColumns(study); - } -} - -template -void BindingConstraints::computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) -{ - for (uint i = 0; i != pBCcount; ++i) - { - // Broadcast to all constraints - pBindConstraints[i].computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } -} - -template -void BindingConstraints::yearBegin(uint year, uint numSpace) -{ - // Broadcast to all binding constraints - for (uint i = 0; i != pBCcount; ++i) - { - pBindConstraints[i].yearBegin(year, numSpace); - } -} - -template -void BindingConstraints::yearEnd(uint year, uint numSpace) -{ - // Broadcast to all binding constraints - for (uint i = 0; i != pBCcount; ++i) - { - pBindConstraints[i].yearEnd(year, numSpace); - } -} - -template -void BindingConstraints::weekBegin(State& state) -{ - for (uint i = 0; i != pBCcount; ++i) - pBindConstraints[i].weekBegin(state); -} - -template -void BindingConstraints::hourBegin(uint hourInTheYear) -{ - for (uint i = 0; i != pBCcount; ++i) - pBindConstraints[i].hourBegin(hourInTheYear); -} - -template -void BindingConstraints::hourEnd(State& state, uint hourInTheYear) -{ - for (uint i = 0; i != pBCcount; ++i) - pBindConstraints[i].hourEnd(state, hourInTheYear); -} -} // namespace Antares::Solver::Variable diff --git a/src/solver/variable/categories.h b/src/solver/variable/categories.h deleted file mode 100644 index bc576adb33..0000000000 --- a/src/solver/variable/categories.h +++ /dev/null @@ -1,319 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_CATEGORIES_H__ -#define __SOLVER_VARIABLE_CATEGORIES_H__ - -#include "constants.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Category -{ -enum DataLevel -{ - //! Data that belong to a single area - area = 1, - //! Data that belong to a thermal dispatchable cluster - thermalAggregate = 2, - //! Data that belong to a link - link = 4, - //! Data that belong to a set - setOfAreas = 8, - // Data belonging to a binding constraint - bindingConstraint = 16, - //! The maximum available level - maxDataLevel = 16, - //! All data level - allDataLevel = area | thermalAggregate | link | setOfAreas | bindingConstraint -}; - -enum File -{ - //! Values of physical variables - va = 1, - //! Reference numbers - id = 2, - //! Detailed values regarding thermal generation - de = 4, - //! Detailed values regarding RES generation - de_res = 8, - //! Detailed values regarding binding constraints - bc = 16, - //! Detailed values regarding short term storage - de_sts = 32, - //! The maximum available value - maxFileLevel = 32, - //! All file level - allFile = va | id | de | de_res | bc | de_sts, -}; - -enum Precision -{ - //! hour - hourly = 1, - //! Daily - daily = 2, - //! Week - weekly = 4, - //! Month - monthly = 8, - //! Year - annual = 16, - //! All precisions - all = hourly | daily | weekly | monthly | annual, -}; - -/*! -** \brief Column management per variable -*/ -enum ColumnManagement -{ - //! Special value for dynamic management (the number of columns can only be known at runtime) - dynamicColumns = -1, - //! No column (means 'no data') - noColumn = 0, - //! A single column for the variable (the default) - singleColumn = 1, -}; - -/*! -** \brief Digest levels -*/ -enum Digest -{ - //! No digest - digestNone = 0, - //! Only all years - digestAllYears = 1, - //! Flow (linear) - digestFlowLinear = 2, - //! Flow (Quadratic) - digestFlowQuad = 4, -}; - -/*! -** \brief Spatial clusters (bitwise) -*/ -enum SpatialAggregate -{ - //! No spatial cluster (default) - noSpatialAggregate = 0, - //! The sum must be used - spatialAggregateSum = 1, - //! The maximum must be used - spatialAggregateMax = 2, - //! Average between areas - spatialAggregateAverage = 4, - //! Sum + 1 - spatialAggregateSumThen1IfPositive = 8, - //! - spatialAggregateOr = 16, -}; - -enum SpatialAggregateMode -{ - //! Compute the aggregate each year - spatialAggregateEachYear = 1, - //! Compute the aggregate once, at the end of the simulation - spatialAggregateOnce = 2, -}; - -enum SpatialAggregatePostProcessing -{ - spatialAggregatePostProcessingPrice = 1, -}; - -/*! -** \brief Hard limit for the decimal precision according a given File precision level -*/ -static inline uint MaxDecimalPrecision(uint fileLevel) -{ - return (fileLevel != id) ? 2u : 0u; -} - -template -struct NextLevel -{ - enum - { - next = (Index != Limit) ? Index * 2 : 0, - }; -}; - -template -inline void DataLevelToStream(StreamT& out, int dataLevel) -{ - switch (dataLevel) - { - case area: - out += "area"; - break; - case thermalAggregate: - out += "thermal"; - break; - case link: - out += "link"; - break; - case setOfAreas: - out += "set of areas"; - break; - default: - out += NULL; - }; -} - -template -inline void FileLevelToStreamShort(StreamT& out, int fileLevel) -{ - switch (fileLevel) - { - case va: - out += "va"; - break; - case id: - out += "id"; - break; - case de: - out += "de"; - break; - case de_res: - out += "res"; - break; - case bc: - out += "bc"; - break; - case de_sts: - out += "sts"; - break; - default: - out += NULL; - } -} - -template -inline void FileLevelToStream(StreamT& out, int fileLevel) -{ - switch (fileLevel) - { - case va: - out += "values"; - break; - case id: - out += "id"; - break; - case de: - out += "details"; - break; - case de_res: - out += "details-res"; - break; - case bc: - out += "binding-constraints"; - break; - case de_sts: - out += "details-STstorage"; - break; - default: - out += NULL; - } -} - -template -inline void PrecisionLevelToStream(StreamT& out, int precisionLevel) -{ - switch (precisionLevel) - { - case hourly: - out += "hourly"; - break; - case daily: - out += "daily"; - break; - case weekly: - out += "weekly"; - break; - case monthly: - out += "monthly"; - break; - case annual: - out += "annual"; - break; - default: - out += NULL; - } -} - -template -struct MaxRowCount -{ - enum - { - value = 0 - }; -}; -template<> -struct MaxRowCount -{ - enum - { - value = maxHoursInAYear - }; -}; -template<> -struct MaxRowCount -{ - enum - { - value = maxDaysInAYear - }; -}; -template<> -struct MaxRowCount -{ - enum - { - value = maxWeeksInAYear - }; -}; -template<> -struct MaxRowCount -{ - enum - { - value = maxMonths - }; -}; -} // namespace Category -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_CATEGORIES_H__ diff --git a/src/solver/variable/commons/hydro.h b/src/solver/variable/commons/hydro.h deleted file mode 100644 index c1b446b8a3..0000000000 --- a/src/solver/variable/commons/hydro.h +++ /dev/null @@ -1,295 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesHydro_H__ -#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesHydro_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardTimeSeriesValuesHydro -{ - //! Caption - static std::string Caption() - { - return "H. ROR"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydro generation, thoughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardTimeSeriesValuesHydro VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal TimeSeriesValuesHydro -*/ -template -class TimeSeriesValuesHydro - : public Variable::IVariable, NextT, VCardTimeSeriesValuesHydro> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardTimeSeriesValuesHydro VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~TimeSeriesValuesHydro() - { - delete[] pValuesForTheCurrentYear; - delete[] pFatalValues; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - pFatalValues = new Matrix<>::ColumnType*[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pFatalValues[numSpace] = NULL; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // The current time-series - auto& ror = pArea->hydro.series->ror; - const unsigned int nbchro - = pArea->hydro.series->getIndex(year); - pFatalValues[numSpace] = &(ror.entry[(nbchro < ror.width ? nbchro : 0)]); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = (*pFatalValues[numSpace])[state.hourInTheYear]; - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! The attached area - Data::Area* pArea; - //! - Matrix<>::ColumnType** pFatalValues; - - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class TimeSeriesValuesHydro - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesHydro_H__ diff --git a/src/solver/variable/commons/links/links.cpp.inc.hxx b/src/solver/variable/commons/links/links.cpp.inc.hxx deleted file mode 100644 index fbb860b19e..0000000000 --- a/src/solver/variable/commons/links/links.cpp.inc.hxx +++ /dev/null @@ -1,125 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "../../variable.h" -#include -#include "../../setofareas.h" - -using namespace Yuni; - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace LINK_NAMESPACE -{ -Links::~Links() -{ - // Releasing the memory occupied by the areas - delete[] pLinks; -} - -void Links::initializeFromArea(Data::Study* study, Data::Area* area) -{ - // Assert - assert(study && "A study pointer must not be null"); - assert(area && "An area pointer must not be null"); - - pLinkCount = (uint)area->links.size(); - if (pLinkCount) - { - pLinks = new NextType[pLinkCount]; - - // For each link... - uint lnkIndex = 0; - auto end = area->links.end(); - for (auto i = area->links.begin(); i != end; ++i, ++lnkIndex) - { - // Instancing a new set of variables of the area - NextType& n = pLinks[lnkIndex]; - - // Initialize the variables - // From the study - n.initializeFromStudy(*study); - // From the area - n.initializeFromArea(study, area); - // From the link - n.initializeFromAreaLink(study, i->second); - } - } - else - pLinks = nullptr; -} - -void Links::simulationBegin() -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].simulationBegin(); - } -} - -void Links::simulationEnd() -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].simulationEnd(); - } -} - -void Links::buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const -{ - int count_int = count; - bool linkDataLevel = dataLevel & Category::link; - bool areaDataLevel = dataLevel & Category::area; - if (count_int && (linkDataLevel || areaDataLevel)) - { - if (not results.data.area->links.empty()) - { - auto end = results.data.area->links.cend(); - for (auto i = results.data.area->links.cbegin(); i != end; ++i) - { - results.data.link = i->second; - pLinks[results.data.link->indexForArea].buildDigest( - results, digestLevel, Category::link); - } - } - } -} - -void Links::beforeYearByYearExport(uint year, uint numSpace) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].beforeYearByYearExport(year, numSpace); -} - -} // namespace LINK_NAMESPACE -} // namespace Variable -} // namespace Solver -} // namespace Antares diff --git a/src/solver/variable/commons/links/links.h.inc.hxx b/src/solver/variable/commons/links/links.h.inc.hxx deleted file mode 100644 index e9b2c81158..0000000000 --- a/src/solver/variable/commons/links/links.h.inc.hxx +++ /dev/null @@ -1,234 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_INC_LINK_H__ -#define __SOLVER_VARIABLE_INC_LINK_H__ - -// NOTE : template includes are used here to reduce template instanciation -// which still seems to be really cpu/memory consuming - -#include "../../state.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace LINK_NAMESPACE -{ -struct VCardAllLinks -{ - //! Caption - static std::string Caption() - { - return "Links"; - } - //! Unit - static std::string Unit() - { - return ""; - } - //! The short description of the variable - static const char* Description() - { - return ""; - } - - //! The expecte results - using ResultsType = Results<>; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile, - //! Indentation (GUI) - nodeDepthForGUI = +1, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 0, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - //! Intermediate values - hasIntermediateValues = 0, - }; - -}; // class VCard - -class Links //: public Variable::IVariable, NextT, VCardAllLinks> -{ -public: - //! Type of the next static variable - using NextType = VariablePerLink; - //! VCard - using VCardType = VCardAllLinks; - //! Ancestor - // using AncestorType = Variable::IVariable, NextT, VCardType>; - - //! List of expected results - using ResultsType = VCardType::ResultsType; - - enum - { - //! How many items have we got - count = NextType::count, - }; - - template - struct Statistics - { - enum - { - count = NextType::template Statistics::count - }; - }; - -public: - /*! - ** \brief Retrieve the list of all individual variables - ** - ** The predicate must implement the method `add(name, unit, comment)`. - */ - template - static void RetrieveVariableList(PredicateT& predicate); - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - Links(); - //! Destructor - ~Links(); - //@} - - void initializeFromStudy(Data::Study& study); - void initializeFromArea(Data::Study*, Data::Area*); - void initializeFromThermalCluster(Data::Study*, Data::Area*, Data::ThermalCluster*); - void initializeFromAreaLink(Data::Study*, Data::AreaLink*); - - void broadcastNonApplicability(bool applyNonApplicable); - void getPrintStatusFromStudy(Data::Study& study); - void supplyMaxNumberOfColumns(Data::Study& study); - - void simulationBegin(); - void simulationEnd(); - - void yearBegin(uint year, unsigned int numSpace); - - void yearEndBuildPrepareDataForEachThermalCluster(State& state, uint year, uint numSpace); - void yearEndBuildForEachThermalCluster(State& state, uint year, uint numSpace); - - void yearEndBuild(State& state, uint year); - - void yearEnd(uint year, uint numSpace); - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary); - - void weekBegin(State& state); - - void weekForEachArea(State& state, uint numSpace); - void weekEnd(State& state); - - void hourBegin(uint hourInTheYear); - void hourForEachArea(State& state, uint numSpace); - void hourForEachLink(State& state, uint numSpace); - - void hourEnd(State& state, uint hourInTheYear); - - void buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const; - - void buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - uint numSpace) const; - - void beforeYearByYearExport(uint year, uint numSpace); - - uint64_t memoryUsage() const; - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const; - - template - static void provideInformations(I& infos); - - template - inline const double* retrieveHourlyResultsForCurrentYear(uint) const - { - return nullptr; - } - - template - void retrieveResultsForArea(typename Storage::ResultsType** result, - const Data::Area*) - { - *result = NULL; - } - - template - void retrieveResultsForThermalCluster(typename Storage::ResultsType** result, - const Data::ThermalCluster*) - { - *result = NULL; - } - - template - void retrieveResultsForLink(typename Storage::ResultsType** result, - const Data::AreaLink* link) - { - pLinks[link->indexForArea].template retrieveResultsForLink(result, link); - } - - template - void computeSpatialAggregateWith(O&, uint) - { - // Do nothing - } - -public: - //! Area list - NextType* pLinks; - //! The total number of links - uint pLinkCount; - -}; // class Links - -} // namespace LINK_NAMESPACE -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#include "links.hxx.inc.hxx" - -#endif // __SOLVER_VARIABLE_INC_LINK_H__ diff --git a/src/solver/variable/commons/links/links.hxx.inc.hxx b/src/solver/variable/commons/links/links.hxx.inc.hxx deleted file mode 100644 index 44c0405de0..0000000000 --- a/src/solver/variable/commons/links/links.hxx.inc.hxx +++ /dev/null @@ -1,304 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_INC_LINK_HXX__ -#define __SOLVER_VARIABLE_INC_LINK_HXX__ - -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace LINK_NAMESPACE -{ -inline Links::Links() -{ - // Do nothing -} - -inline void Links::initializeFromStudy([[maybe_unused]] Data::Study& study) -{ - // Do nothing -} - -inline void Links::initializeFromAreaLink(Data::Study*, Data::AreaLink*) -{ - // Nothing to do here -} - -inline void Links::initializeFromThermalCluster(Data::Study*, Data::Area*, Data::ThermalCluster*) -{ - // This method should not be called at this stage -} - -inline void Links::broadcastNonApplicability(bool applyNonApplicable) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].broadcastNonApplicability(applyNonApplicable); -} - -inline void Links::getPrintStatusFromStudy(Data::Study& study) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].getPrintStatusFromStudy(study); -} - -inline void Links::supplyMaxNumberOfColumns(Data::Study& study) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].supplyMaxNumberOfColumns(study); -} - -inline void Links::yearBegin(uint year, unsigned int numSpace) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].yearBegin(year, numSpace); -} - -inline void Links::yearEndBuildPrepareDataForEachThermalCluster(State& state, - uint year, - unsigned int numSpace) -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); - } -} - -inline void Links::yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].yearEndBuildForEachThermalCluster(state, year, numSpace); - } -} - -inline void Links::yearEndBuild(State& state, uint year) -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].yearEndBuild(state, year); - } -} - -inline void Links::yearEnd(uint year, uint numSpace) -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].yearEnd(year, numSpace); - } -} - -inline void Links::computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) -{ - for (uint i = 0; i != pLinkCount; ++i) - { - pLinks[i].computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } -} - -inline void Links::weekBegin(State& state) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].weekBegin(state); -} - -inline void Links::weekForEachArea(State&, uint numSpace) -{ - // do nothing - UNUSED_VARIABLE(numSpace); -} - -inline void Links::weekEnd(State& state) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].weekEnd(state); -} - -inline void Links::hourBegin(uint hourInTheYear) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].hourBegin(hourInTheYear); -} - -inline void Links::hourForEachArea(State& state, unsigned int numSpace) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].hourForEachArea(state, numSpace); -} - -inline void Links::hourForEachLink(State& state, unsigned int numSpace) -{ - pLinks[state.link->indexForArea].hourForEachLink(state, numSpace); -} - -inline void Links::hourEnd(State& state, uint hourInTheYear) -{ - for (uint i = 0; i != pLinkCount; ++i) - pLinks[i].hourEnd(state, hourInTheYear); -} - -inline void Links::buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const -{ - int count_int = count; - bool link_dataLevel = (dataLevel & Category::link); - if (count_int && link_dataLevel) - { - assert(results.data.link != NULL - && "The link must not be null to generate a survey report"); - - // Build the survey results for the given area - auto& link = *results.data.link; - - // Filtering - switch (precision) - { - case Category::hourly: - if (!(link.filterSynthesis & Data::filterHourly)) - return; - break; - case Category::daily: - if (!(link.filterSynthesis & Data::filterDaily)) - return; - break; - case Category::weekly: - if (!(link.filterSynthesis & Data::filterWeekly)) - return; - break; - case Category::monthly: - if (!(link.filterSynthesis & Data::filterMonthly)) - return; - break; - case Category::annual: - if (!(link.filterSynthesis & Data::filterAnnual)) - return; - break; - case Category::all: - break; - } - auto& linkOutputData = pLinks[link.indexForArea]; - linkOutputData.buildSurveyReport(results, dataLevel, fileLevel, precision); - } -} - -inline void Links::buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - uint numSpace) const -{ - int count_int = count; - bool link_dataLevel = (dataLevel & Category::link); - if (count_int && link_dataLevel) - { - assert(results.data.link != NULL - && "The link must not be null to generate a survey report"); - - auto& link = *results.data.link; - - // Filtering - switch (precision) - { - case Category::hourly: - if (not(link.filterYearByYear & Data::filterHourly)) - return; - break; - case Category::daily: - if (not(link.filterYearByYear & Data::filterDaily)) - return; - break; - case Category::weekly: - if (not(link.filterYearByYear & Data::filterWeekly)) - return; - break; - case Category::monthly: - if (not(link.filterYearByYear & Data::filterMonthly)) - return; - break; - case Category::annual: - if (not(link.filterYearByYear & Data::filterAnnual)) - return; - break; - case Category::all: - break; - } - - // Build the survey results for the given area - auto& linkOutputData = pLinks[results.data.link->indexForArea]; - linkOutputData.buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); - } -} - -template -inline void Links::provideInformations(I& infos) -{ - // Begining of the node - if (VCardType::nodeDepthForGUI) - { - infos.template beginNode(); - // Next variable in the list - NextType::template provideInformations(infos); - // End of the node - infos.endNode(); - } - else - { - // Giving our VCard - infos.template addVCard(); - // Next variable in the list - NextType::template provideInformations(infos); - } -} - -template -void Links::RetrieveVariableList(PredicateT& predicate) -{ - NextType::RetrieveVariableList(predicate); -} - -inline uint64_t Links::memoryUsage() const -{ - uint64_t result = 0; - for (uint i = 0; i != pLinkCount; ++i) - { - result += sizeof(NextType) + sizeof(void*); - result += pLinks[i].memoryUsage(); - } - return result; -} -} // namespace LINK_NAMESPACE -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_INC_LINK_HXX__ diff --git a/src/solver/variable/commons/load.h b/src/solver/variable/commons/load.h deleted file mode 100644 index 174e94624a..0000000000 --- a/src/solver/variable/commons/load.h +++ /dev/null @@ -1,291 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesLoad_H__ -#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesLoad_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardTimeSeriesValuesLoad -{ - //! Caption - static std::string Caption() - { - return "LOAD"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Load generation, thoughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardTimeSeriesValuesLoad VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal TimeSeriesValuesLoad -*/ -template -class TimeSeriesValuesLoad - : public Variable::IVariable, NextT, VCardTimeSeriesValuesLoad> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardTimeSeriesValuesLoad VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~TimeSeriesValuesLoad() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Next - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // The current time-series - // - // At this point, these values are not the raw values of the load timeseries - // see performTransformationsBeforeLaunchingSimulation() - // L* = L + DSM - // - (void)::memcpy( - pValuesForTheCurrentYear[numSpace].hour, - pArea->load.series->getColumn(year), - sizeof(double) * pArea->load.series->timeSeries.height); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! The attached area - Antares::Data::Area* pArea; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class TimeSeriesValuesLoad - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesLoad_H__ diff --git a/src/solver/variable/commons/miscGenMinusRowPSP.h b/src/solver/variable/commons/miscGenMinusRowPSP.h deleted file mode 100644 index 9ad01c85ed..0000000000 --- a/src/solver/variable/commons/miscGenMinusRowPSP.h +++ /dev/null @@ -1,289 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_MiscGenMinusRowPSP_H__ -#define __SOLVER_VARIABLE_ECONOMY_MiscGenMinusRowPSP_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardMiscGenMinusRowPSP -{ - //! Caption - static std::string Caption() - { - return "MISC. NDG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Non-dispatchable generation (not including wind and run-of-the-river)"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardMiscGenMinusRowPSP VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal MiscGenMinusRowPSP -*/ -template -class MiscGenMinusRowPSP - : public Variable::IVariable, NextT, VCardMiscGenMinusRowPSP> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardMiscGenMinusRowPSP VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~MiscGenMinusRowPSP() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Copy raw values - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - // Memcpy for the first value - (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, - area->miscGen.entry[0], - sizeof(double) * area->miscGen.height); - - { - // We must not include the CHP and the Solar. So we have to start from `2` - for (unsigned int x = 1; x != (unsigned int)Data::fhhPSP; ++x) - { - const Matrix<>::ColumnType& col = area->miscGen.entry[x]; - for (unsigned int y = 0; y != area->miscGen.height; ++y) - pValuesForTheCurrentYear[numSpace].hour[y] += col[y]; - } - } - } - - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class MiscGenMinusRowPSP - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_MiscGenMinusRowPSP_H__ diff --git a/src/solver/variable/commons/psp.h b/src/solver/variable/commons/psp.h deleted file mode 100644 index 6cfc65ba5c..0000000000 --- a/src/solver/variable/commons/psp.h +++ /dev/null @@ -1,275 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_PSP_H__ -#define __SOLVER_VARIABLE_ECONOMY_PSP_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardPSP -{ - //! Caption - static std::string Caption() - { - return "PSP"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "PSP"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardPSP VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal PSP -*/ -template -class PSP : public Variable::IVariable, NextT, VCardPSP> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardPSP VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~PSP() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Copy raw values - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, - area->miscGen.entry[Data::fhhPSP], - sizeof(double) * area->miscGen.height); - - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class PSP - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_PSP_H__ diff --git a/src/solver/variable/commons/rowBalance.h b/src/solver/variable/commons/rowBalance.h deleted file mode 100644 index f085932f75..0000000000 --- a/src/solver/variable/commons/rowBalance.h +++ /dev/null @@ -1,268 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_RowBalance_H__ -#define __SOLVER_VARIABLE_ECONOMY_RowBalance_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardRowBalance -{ - //! Caption - static std::string Caption() - { - return "ROW BAL."; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Row Balance"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardRowBalance VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateOnce, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesType; - typedef IntermediateValues IntermediateValuesBaseType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal RowBalance -*/ -template -class RowBalance : public Variable::IVariable, NextT, VCardRowBalance> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardRowBalance VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~RowBalance() - { - } - - void initializeFromStudy(Data::Study& study) - { - // Average on all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear.initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Copy raw values - unsigned int height = area->miscGen.height; - (void)::memcpy(pValuesForTheCurrentYear.hour, - area->miscGen.entry[Data::fhhRowBalance], - sizeof(double) * height); - - if (study->parameters.mode == Data::stdmAdequacy) - { - for (unsigned int h = 0; h != height; ++h) - pValuesForTheCurrentYear.hour[h] - -= area->reserves.entry[Data::fhrPrimaryReserve][h]; - } - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear.computeStatisticsForTheCurrentYear(); - - // Merge all those values with the global results - AncestorType::pResults.merge(0, pValuesForTheCurrentYear); - - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear.template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - -}; // class RowBalance - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_RowBalance_H__ diff --git a/src/solver/variable/commons/solar.h b/src/solver/variable/commons/solar.h deleted file mode 100644 index 0887f9f7f9..0000000000 --- a/src/solver/variable/commons/solar.h +++ /dev/null @@ -1,296 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesSolar_H__ -#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesSolar_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardTimeSeriesValuesSolar -{ - //! Caption - static std::string Caption() - { - return "SOLAR"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Solar generation, thoughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardTimeSeriesValuesSolar VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal TimeSeriesValuesSolar -*/ -template -class TimeSeriesValuesSolar - : public Variable::IVariable, NextT, VCardTimeSeriesValuesSolar> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardTimeSeriesValuesSolar VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~TimeSeriesValuesSolar() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - isRenewableGenerationAggregrated = study.parameters.renewableGeneration.isAggregated(); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Next - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - if (isRenewableGenerationAggregrated) - { - // The current solar time-series - (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, - pArea->solar.series->getColumn(year), - sizeof(double) * pArea->solar.series->timeSeries.height); - } - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourEnd(State& state, unsigned int hourInTheYear) - { - NextType::hourEnd(state, hourInTheYear); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! The attached area - Data::Area* pArea; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - bool isRenewableGenerationAggregrated = true; - -}; // class TimeSeriesValuesSolar - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesSolar_H__ diff --git a/src/solver/variable/commons/wind.h b/src/solver/variable/commons/wind.h deleted file mode 100644 index 369086aeee..0000000000 --- a/src/solver/variable/commons/wind.h +++ /dev/null @@ -1,290 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesWind_H__ -#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesWind_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardTimeSeriesValuesWind -{ - //! Caption - static std::string Caption() - { - return "WIND"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Wind generation, thoughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardTimeSeriesValuesWind VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal TimeSeriesValuesWind -*/ -template -class TimeSeriesValuesWind - : public Variable::IVariable, NextT, VCardTimeSeriesValuesWind> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardTimeSeriesValuesWind VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~TimeSeriesValuesWind() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - isRenewableGenerationAggregrated = study.parameters.renewableGeneration.isAggregated(); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - if (isRenewableGenerationAggregrated) - { - // The current wind time-series - (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, - pArea->wind.series->getColumn(year), - sizeof(double) * pArea->wind.series->timeSeries.height); - } - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! The attached area - Data::Area* pArea; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - bool isRenewableGenerationAggregrated = true; - -}; // class TimeSeriesValuesWind - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesWind_H__ diff --git a/src/solver/variable/constants.h b/src/solver/variable/constants.h deleted file mode 100644 index 4b05861115..0000000000 --- a/src/solver/variable/constants.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_CONSTANT_H__ -#define __SOLVER_VARIABLE_CONSTANT_H__ - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -enum Constant -{ - maxHoursInAYear = 8785, - maxDaysInAYear = 7 * 53 + 1, // 366, - maxWeeksInAYear = 53, - maxHoursInADay = 24, - maxMonths = 12, - maxDaysInAWeek = 7, - maxHoursInAWeek = 24 * 7, // 168, -}; - -template -struct PrecisionToPrintfFormat -{ - static const char* Value() - { - return "%.6f"; - } -}; -template<> -struct PrecisionToPrintfFormat<0> -{ - static const char* Value() - { - return "%.0f"; - } -}; -template<> -struct PrecisionToPrintfFormat<1> -{ - static const char* Value() - { - return "%.1f"; - } -}; -template<> -struct PrecisionToPrintfFormat<2> -{ - static const char* Value() - { - return "%.2f"; - } -}; -template<> -struct PrecisionToPrintfFormat<3> -{ - static const char* Value() - { - return "%.3f"; - } -}; -template<> -struct PrecisionToPrintfFormat<4> -{ - static const char* Value() - { - return "%.4f"; - } -}; -template<> -struct PrecisionToPrintfFormat<5> -{ - static const char* Value() - { - return "%.5f"; - } -}; - -template -static inline void AssignPrecisionToPrintfFormat(StringT& out, uint precision) -{ - switch (precision) - { - case 0: - out.assign("%.0f", 4); - break; - case 1: - out.assign("%.1f", 4); - break; - case 2: - out.assign("%.2f", 4); - break; - case 3: - out.assign("%.3f", 4); - break; - case 4: - out.assign("%.4f", 4); - break; - case 5: - out.assign("%.5f", 4); - break; - default: - out.assign("%.6f", 4); - break; - } -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_CONSTANT_H__ diff --git a/src/solver/variable/container.h b/src/solver/variable/container.h deleted file mode 100644 index 4c6b0e2f45..0000000000 --- a/src/solver/variable/container.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_LIST_H__ -#define __SOLVER_VARIABLE_LIST_H__ - -#include -#include -#include - -#include - -#include "endoflist.h" -#include "categories.h" -#include "surveyresults.h" -#include "info.h" - -namespace Antares::Solver::Variable::Container -{ -/*! -** \brief Static list for all output variables -** -** This structure is merely a static linked list with all variables -*/ -template -class List : public NextT -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! The full type of the class - typedef List ListType; - - enum - { - //! How many items have we got - count = NextT::count, - }; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default Constructor - */ - List(); - /*! - ** \brief Destructor - */ - ~List(); - //@} - - //! \name Variable initialization - //@{ - /*! - ** \brief Initialize all output variables - */ - void initializeFromStudy(Data::Study& study); - - /*! - ** \brief Initialize all output variables according a given area - */ - void initializeFromArea(Data::Study* study, Data::Area* area); - - /*! - ** \brief Initialize all output variables according a given link - */ - void initializeFromLink(Data::Study* study, Data::AreaLink* link); - - /*! - ** \brief Initialize all output variables according a given thermal cluster - */ - void initializeFromThermalCluster(Data::Study* study, - Data::Area* area, - Data::ThermalCluster* cluster); - //@} - - //! \name Simulation events - //@{ - /*! - ** \brief Notify to all variables that the simulation is about to begin - */ - void simulationBegin(); - - /*! - ** \brief Notify to all variables that the simulation has finished - */ - void simulationEnd(); - //@} - - //! \name Years events - //@{ - /*! - ** \brief Notify to all variables that a new year is about to start - ** - ** \param year The current year - */ - void yearBegin(unsigned int year, unsigned int numSpace); - - /*! - ** \brief Notify to all variables that the year is now over - ** - ** That mainly means that all variables should perform the monthly - ** aggragations. - ** \param year The current year - */ - void yearEnd(unsigned int year, unsigned int numSpace); - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary); - - template - void yearEndSpatialAggregates(V& allVars, unsigned int year, unsigned int numSpace); - - template - void yearEndSpatialAggregates(V& allVars, unsigned int year, const SetT& set); - - template - void computeSpatialAggregatesSummary(V& allVars, - std::map& numSpaceToYear, - unsigned int); - - template - void simulationEndSpatialAggregates(V& allVars); - - template - void simulationEndSpatialAggregates(V& allVars, const SetT& set); - //@} - - //! \name Hourly events - //@{ - /*! - ** \brief Notify to all variables that a new hour is about to begin - */ - void hourBegin(unsigned int hourInTheYear); - - void hourForEachArea(State& state, unsigned int numSpace); - - void hourForEachLink(State& state); - - void hourEnd(State& state, unsigned int hourInTheYear); - //@} - - //! \name Weekly events - //@{ - void weekBegin(State& state); - - void weekEnd(State& state); - //@} - - //! \name Spatial aggregation - //@{ - template - void computeSpatialAggregateWith(O& out); - - template - void computeSpatialAggregateWith(O& out, const Data::Area* area, unsigned int numSpace); - - template - void retrieveResultsForArea(typename Variable::Storage::ResultsType** result, - const Data::Area* area); - - template - void retrieveResultsForThermalCluster( - typename Variable::Storage::ResultsType** result, - const Data::ThermalCluster* cluster); - - template - void retrieveResultsForLink(typename Variable::Storage::ResultsType** result, - const Data::AreaLink* link); - //@} - - //! \name User reports - //@{ - /*! - ** \brief Ask to all variables to fullfil the report - */ - void buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const; - - void buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - unsigned int numSpace) const; - - /*! - ** \brief Ask to all variables to fullfil additional reports (like the digest for example) - ** - ** \tparam GlobalT True to write down the results of the simulation, false - ** for the results of the current year - */ - void exportSurveyResults(bool global, - const Yuni::String& output, - unsigned int numSpace, - IResultWriter& writer); - - /*! - ** \brief Ask to all variables to fullfil the digest - */ - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const; - //@} - - //! \name Memory management - //@{ - //! Get the amount of memory currently used by the class - uint64_t memoryUsage() const; - //@} - -private: - //! Pointer to the current study - Data::Study* pStudy; - -}; // class List - -} // namespace Antares::Solver::Variable::Container - - - - -#include "surveyresults/reportbuilder.hxx" -#include "container.hxx" - -#endif // __SOLVER_VARIABLE_LIST_H__ diff --git a/src/solver/variable/container.hxx b/src/solver/variable/container.hxx deleted file mode 100644 index 5217eae50e..0000000000 --- a/src/solver/variable/container.hxx +++ /dev/null @@ -1,367 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_CONTAINER_CONTAINER_HXX__ -#define __SOLVER_CONTAINER_CONTAINER_HXX__ - -#include -#include - -#include - -#define SEP Yuni::IO::Separator - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Container -{ -template -inline List::List() -{ -} - -template -inline List::~List() -{ -} - -template -inline void List::initializeFromStudy(Data::Study& study) -{ - // Store a pointer to the current study - pStudy = &study; - // Next - NextType::initializeFromStudy(study); -} - -template -inline void List::initializeFromArea(Data::Study* study, Data::Area* area) -{ - // Ask to the first variable to do it - NextType::initializeFromArea(study, area); -} - -template -inline void List::initializeFromLink(Data::Study* study, Data::AreaLink* link) -{ - // Next - NextType::initializeFromAreaLink(study, link); -} - -template -inline void List::initializeFromThermalCluster(Data::Study* study, - Data::Area* area, - Data::ThermalCluster* cluster) -{ - // Next - NextType::initializeFromThermalCluster(study, area, cluster); -} - -template -inline void List::simulationBegin() -{ - NextType::simulationBegin(); -} - -template -inline void List::simulationEnd() -{ - NextType::simulationEnd(); -} - -template -inline void List::yearBegin(unsigned int year, unsigned int numSpace) -{ - NextType::yearBegin(year, numSpace); -} - -template -inline void List::yearEnd(unsigned int year, unsigned int numSpace) -{ - NextType::yearEnd(year, numSpace); -} - -template -inline void List::computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) -{ - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); -} - -template -template -inline void List::yearEndSpatialAggregates(V& allVars, - unsigned int year, - unsigned int numSpace) -{ - // Next variable - NextType::template yearEndSpatialAggregates(allVars, year, numSpace); -} - -template -template -inline void List::yearEndSpatialAggregates(V& allVars, unsigned int year, const SetT& set) -{ - // Next variable - NextType::template yearEndSpatialAggregates(allVars, year, set); -} - -template -template -inline void List::computeSpatialAggregatesSummary( - V& allVars, - std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) -{ - // Next variable - NextType::template computeSpatialAggregatesSummary( - allVars, numSpaceToYear, nbYearsForCurrentSummary); -} - -template -template -inline void List::simulationEndSpatialAggregates(V& allVars) -{ - // Next variable - NextType::template simulationEndSpatialAggregates(allVars); -} - -template -template -inline void List::simulationEndSpatialAggregates(V& allVars, const SetT& set) -{ - // Next variable - NextType::template simulationEndSpatialAggregates(allVars, set); -} - -template -inline void List::hourBegin(unsigned int hourInTheYear) -{ - NextType::hourBegin(hourInTheYear); -} - -template -inline void List::weekBegin(State& state) -{ - NextType::weekBegin(state); -} - -template -inline void List::weekEnd(State& state) -{ - NextType::weekEnd(state); -} - -template -inline void List::hourForEachArea(State& state, unsigned int numSpace) -{ - NextType::hourForEachArea(state, numSpace); -} - -template -inline void List::hourForEachLink(State& state) -{ - NextType::hourForEachLink(state); -} - -template -inline void List::hourEnd(State& state, unsigned int hourInTheYear) -{ - NextType::hourEnd(state, hourInTheYear); -} - -template -template -inline void List::computeSpatialAggregateWith(O& out) -{ - NextType::template computeSpatialAggregateWith(out); -} - -template -template -inline void List::computeSpatialAggregateWith(O& out, - const Data::Area* area, - unsigned int numSpace) -{ - NextType::template computeSpatialAggregateWith(out, area, numSpace); -} - -template -template -inline void List::retrieveResultsForArea( - typename Variable::Storage::ResultsType** result, - const Data::Area* area) -{ - NextType::template retrieveResultsForArea(result, area); -} - -template -template -inline void List::retrieveResultsForThermalCluster( - typename Variable::Storage::ResultsType** result, - const Data::ThermalCluster* cluster) -{ - NextType::template retrieveResultsForThermalCluster(result, cluster); -} - -template -template -inline void List::retrieveResultsForLink( - typename Variable::Storage::ResultsType** result, - const Data::AreaLink* link) -{ - NextType::template retrieveResultsForLink(result, link); -} - -template -inline uint64_t List::memoryUsage() const -{ - return sizeof(ListType) + NextType::memoryUsage(); -} - -template -void List::buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const -{ - // Reset - results.data.columnIndex = 0; - - // The new filename - results.data.filename.clear(); - results.data.filename << results.data.output << SEP; - Category::FileLevelToStream(results.data.filename, fileLevel); - results.data.filename << '-'; - Category::PrecisionLevelToStream(results.data.filename, precision); - results.data.filename << ".txt"; - - // Ask to all variables - NextType::buildSurveyReport(results, dataLevel, fileLevel, precision); - - // If the column index is still equals to 0, that would mean we have nothing - // to do (there is no data to write) - if (results.data.columnIndex > 0) - results.saveToFile(dataLevel, fileLevel, precision); -} - -template -void List::buildAnnualSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision, - unsigned int numSpace) const -{ - // Reset - results.data.columnIndex = 0; - - // The new filename - results.data.filename.clear(); - results.data.filename << results.data.output << SEP; - Category::FileLevelToStream(results.data.filename, fileLevel); - results.data.filename << '-'; - Category::PrecisionLevelToStream(results.data.filename, precision); - results.data.filename.append(".txt", 4); - - // Ask to all variables - NextType::buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); - - // If the column index is still equals to 0, that would mean we have nothing - // to do (there is no data to write) - if (results.data.columnIndex > 0) - results.saveToFile(dataLevel, fileLevel, precision); -} - -template -void List::buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const -{ - // Reset - results.data.columnIndex = 0; - results.data.thermalCluster = nullptr; - results.data.area = nullptr; - results.data.link = nullptr; - results.variableCaption.clear(); - - // Building the digest - NextType::buildDigest(results, digestLevel, dataLevel); -} - -template -void List::exportSurveyResults(bool global, - const Yuni::String& output, - unsigned int numSpace, - IResultWriter& writer) -{ - using namespace Antares; - - // Infos - if (global) - { - logs.info(); // empty line - logs.checkpoint() << "Exporting the survey results..."; - } - else - logs.info() << "Exporting the annual results"; - - auto survey = std::make_shared(*pStudy, output, writer); - - // Year by year ? - survey->yearByYearResults = !global; - - if (global) - { - // alias to the type of the report builder - using Builder = SurveyReportBuilder; - // Building the survey results for each possible state - Builder::Run(*this, *survey); - - // Exporting the Grid (information about the study) - survey->exportGridInfos(); - - // Exporting the digest - // The digest must be exported after the real report because some values - // are computed at this moment. - Builder::RunDigest(*this, *survey, writer); - } - else - { - // alias to the type of the report builder - using Builder = SurveyReportBuilder; - // Building the survey results for each possible state - Builder::Run(*this, *survey, numSpace); - } -} - -} // namespace Container -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_CONTAINER_CONTAINER_H__ diff --git a/src/solver/variable/economy/STStorageCashFlowByCluster.h b/src/solver/variable/economy/STStorageCashFlowByCluster.h deleted file mode 100644 index 6ea3456132..0000000000 --- a/src/solver/variable/economy/STStorageCashFlowByCluster.h +++ /dev/null @@ -1,301 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardSTstorageCashFlowByCluster -{ - //! Caption - static std::string Caption() - { - return "STS Cashflow By Cluster"; - } - //! Unit - static std::string Unit() - { - return "CashFlow - Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Cash Flow by short term storage"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSTstorageCashFlowByCluster VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & Category::de_sts, - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Energy generated by short term storage clusters -*/ -template -class STstorageCashFlowByCluster : public Variable::IVariable, - NextT, - VCardSTstorageCashFlowByCluster> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSTstorageCashFlowByCluster VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - static constexpr int count = 1 + NextT::count; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - STstorageCashFlowByCluster() = default; - - ~STstorageCashFlowByCluster() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - nbClusters_ = area->shortTermStorage.count(); - if (nbClusters_) - { - AncestorType::pResults.resize(nbClusters_); - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[nbClusters_]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != nbClusters_; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != nbClusters_; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - pValuesForTheCurrentYear[numSpace] = nullptr; - } - - AncestorType::pResults.clear(); - } - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return nbClusters_ * ResultsType::count; - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int clusterIndex = 0; clusterIndex != nbClusters_; ++clusterIndex) - { - pValuesForTheCurrentYear[numSpace][clusterIndex].reset(); - } - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Compute all statistics from hourly results for the current year (daily, weekly, monthly, ...) - pValuesForTheCurrentYear[numSpace][clusterIndex].computeStatisticsForTheCurrentYear(); - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Merge all those values with the global results - AncestorType::pResults[clusterIndex].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][clusterIndex]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - unsigned int hourInYear = state.hourInTheYear; - for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); - ++clusterIndex) - { - const auto& stsHourlyResults = state.hourlyResults->ShortTermStorage[state.hourInTheWeek]; - // ST storage injection for the current cluster and this hour - // CashFlow[h] = (withdrawal - injection) * MRG. PRICE - pValuesForTheCurrentYear[numSpace][clusterIndex].hour[hourInYear] - = (stsHourlyResults.withdrawal[clusterIndex] - - stsHourlyResults.injection[clusterIndex]) - * (-state.hourlyResults->CoutsMarginauxHoraires[state.hourInTheWeek]); - // Note: The marginal price provided by the solver is negative (naming convention). - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Ask to build the digest to the next variable - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - inline uint64_t memoryUsage() const - { - uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) - * pNbYearsParallel; - r += sizeof(double) * nbClusters_ * maxHoursInAYear * pNbYearsParallel; - r += AncestorType::memoryUsage(); - return r; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& shortTermStorage = results.data.area->shortTermStorage; - - // Write the data for the current year - for (uint clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Write the data for the current year - const auto* cluster = shortTermStorage.storagesByIndex[clusterIndex]; - results.variableCaption = cluster->properties.name; - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][clusterIndex] - .template buildAnnualSurveyReport(results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear = nullptr; - size_t nbClusters_ = 0; - unsigned int pNbYearsParallel = 0; - -}; // class STstorageCashFlowByCluster - -} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/economy/STStorageInjectionByCluster.h b/src/solver/variable/economy/STStorageInjectionByCluster.h deleted file mode 100644 index 31ccb7912a..0000000000 --- a/src/solver/variable/economy/STStorageInjectionByCluster.h +++ /dev/null @@ -1,303 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardSTstorageInjectionByCluster -{ - //! Caption - static std::string Caption() - { - return "STS inj by plant"; - } - //! Unit - static std::string Unit() - { - return "P-injection - MW"; - } - - //! The short description of the variable - static std::string Description() - { - return "Energy injected by ST storage clusters"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSTstorageInjectionByCluster VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de_sts), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Energy generated by short term storage clusters -*/ -template -class STstorageInjectionByCluster : public Variable::IVariable, - NextT, - VCardSTstorageInjectionByCluster> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSTstorageInjectionByCluster VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> - AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - STstorageInjectionByCluster() : - pValuesForTheCurrentYear(nullptr) - { - } - - ~STstorageInjectionByCluster() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - nbClusters_ = area->shortTermStorage.count(); - if (nbClusters_) - { - AncestorType::pResults.resize(nbClusters_); - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[nbClusters_]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != nbClusters_; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != nbClusters_; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - pValuesForTheCurrentYear[numSpace] = nullptr; - } - - AncestorType::pResults.clear(); - } - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return nbClusters_ * ResultsType::count; - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != nbClusters_; ++i) - { - pValuesForTheCurrentYear[numSpace][i].reset(); - } - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Compute all statistics from hourly results for the current year (daily, weekly, monthly, ...) - pValuesForTheCurrentYear[numSpace][clusterIndex].computeStatisticsForTheCurrentYear(); - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Merge all those values with the global results - AncestorType::pResults[clusterIndex].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][clusterIndex]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); - ++clusterIndex) - { - // ST storage injection for the current cluster and this hour - pValuesForTheCurrentYear[numSpace][clusterIndex].hour[state.hourInTheYear] - = state.hourlyResults->ShortTermStorage[state.hourInTheWeek].injection[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Ask to build the digest to the next variable - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - inline uint64_t memoryUsage() const - { - uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) - * pNbYearsParallel; - r += sizeof(double) * nbClusters_ * maxHoursInAYear * pNbYearsParallel; - r += AncestorType::memoryUsage(); - return r; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& shortTermStorage = results.data.area->shortTermStorage; - - // Write the data for the current year - for (uint clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Write the data for the current year - const auto* cluster = shortTermStorage.storagesByIndex[clusterIndex]; - results.variableCaption = cluster->properties.name; - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][clusterIndex] - .template buildAnnualSurveyReport(results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t nbClusters_; - unsigned int pNbYearsParallel; - -}; // class STstorageInjectionByCluster - -} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/economy/STStorageLevelsByCluster.h b/src/solver/variable/economy/STStorageLevelsByCluster.h deleted file mode 100644 index 2e220e08ab..0000000000 --- a/src/solver/variable/economy/STStorageLevelsByCluster.h +++ /dev/null @@ -1,303 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardSTstorageLevelsByCluster -{ - //! Caption - static std::string Caption() - { - return "STS lvl by plant"; - } - //! Unit - static std::string Unit() - { - return "Levels - MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Levels by ST storage clusters"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSTstorageLevelsByCluster VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de_sts), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Energy generated by short term storage clusters -*/ -template -class STstorageLevelsByCluster - : public Variable:: - IVariable, NextT, VCardSTstorageLevelsByCluster> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSTstorageLevelsByCluster VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> - AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - STstorageLevelsByCluster() : - pValuesForTheCurrentYear(nullptr) - { - } - - ~STstorageLevelsByCluster() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - nbClusters_ = area->shortTermStorage.count(); - if (nbClusters_) - { - AncestorType::pResults.resize(nbClusters_); - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[nbClusters_]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != nbClusters_; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != nbClusters_; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - pValuesForTheCurrentYear[numSpace] = nullptr; - } - - AncestorType::pResults.clear(); - } - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return nbClusters_ * ResultsType::count; - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != nbClusters_; ++i) - { - pValuesForTheCurrentYear[numSpace][i].reset(); - } - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Compute all statistics from hourly results for the current year (daily, weekly, monthly, ...) - pValuesForTheCurrentYear[numSpace][clusterIndex].computeAveragesForCurrentYearFromHourlyResults(); - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Merge all those values with the global results - AncestorType::pResults[clusterIndex].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][clusterIndex]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); - ++clusterIndex) - { - // ST storage levels for the current cluster and this hour - pValuesForTheCurrentYear[numSpace][clusterIndex].hour[state.hourInTheYear] - = state.hourlyResults->ShortTermStorage[state.hourInTheWeek].level[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Ask to build the digest to the next variable - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - inline uint64_t memoryUsage() const - { - uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) - * pNbYearsParallel; - r += sizeof(double) * nbClusters_ * maxHoursInAYear * pNbYearsParallel; - r += AncestorType::memoryUsage(); - return r; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& shortTermStorage = results.data.area->shortTermStorage; - - // Write the data for the current year - for (uint clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Write the data for the current year - const auto* cluster = shortTermStorage.storagesByIndex[clusterIndex]; - results.variableCaption = cluster->properties.name; - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][clusterIndex].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t nbClusters_; - unsigned int pNbYearsParallel; - -}; // class STstorageLevelsByCluster - -} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/economy/STStorageWithdrawalByCluster.h b/src/solver/variable/economy/STStorageWithdrawalByCluster.h deleted file mode 100644 index e0887b64d8..0000000000 --- a/src/solver/variable/economy/STStorageWithdrawalByCluster.h +++ /dev/null @@ -1,303 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardSTstorageWithdrawalByCluster -{ - //! Caption - static std::string Caption() - { - return "STS withdrawal by plant"; - } - //! Unit - static std::string Unit() - { - return "P-withdrawal - MW"; - } - - //! The short description of the variable - static std::string Description() - { - return "Energy withdrawn by ST storage clusters"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSTstorageWithdrawalByCluster VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de_sts), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Energy generated by short term storage clusters -*/ -template -class STstorageWithdrawalByCluster - : public Variable:: - IVariable, NextT, VCardSTstorageWithdrawalByCluster> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSTstorageWithdrawalByCluster VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> - AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - STstorageWithdrawalByCluster() : - pValuesForTheCurrentYear(nullptr) - { - } - - ~STstorageWithdrawalByCluster() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - nbClusters_ = area->shortTermStorage.count(); - if (nbClusters_) - { - AncestorType::pResults.resize(nbClusters_); - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[nbClusters_]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != nbClusters_; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != nbClusters_; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - pValuesForTheCurrentYear[numSpace] = nullptr; - } - - AncestorType::pResults.clear(); - } - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return nbClusters_ * ResultsType::count; - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != nbClusters_; ++i) - { - pValuesForTheCurrentYear[numSpace][i].reset(); - } - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Compute all statistics from hourly results for the current year (daily, weekly, monthly, ...) - pValuesForTheCurrentYear[numSpace][clusterIndex].computeStatisticsForTheCurrentYear(); - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Merge all those values with the global results - AncestorType::pResults[clusterIndex].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][clusterIndex]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); - ++clusterIndex) - { - // ST storage withdrawal for the current cluster and this hour - pValuesForTheCurrentYear[numSpace][clusterIndex].hour[state.hourInTheYear] - = state.hourlyResults->ShortTermStorage[state.hourInTheWeek].withdrawal[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Ask to build the digest to the next variable - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - inline uint64_t memoryUsage() const - { - uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) - * pNbYearsParallel; - r += sizeof(double) * nbClusters_ * maxHoursInAYear * pNbYearsParallel; - r += AncestorType::memoryUsage(); - return r; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& shortTermStorage = results.data.area->shortTermStorage; - - // Write the data for the current year - for (uint clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) - { - // Write the data for the current year - const auto* cluster = shortTermStorage.storagesByIndex[clusterIndex]; - results.variableCaption = cluster->properties.name; - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][clusterIndex].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t nbClusters_; - unsigned int pNbYearsParallel; - -}; // class STstorageWithdrawalByCluster - -} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h deleted file mode 100644 index b961c8dbf7..0000000000 --- a/src/solver/variable/economy/all.h +++ /dev/null @@ -1,302 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_ALL_H__ -#define __SOLVER_VARIABLE_ECONOMY_ALL_H__ - -#include "../variable.h" -#include "../area.h" -#include "../setofareas.h" -#include "../bindConstraints.h" - -#include "price.h" -#include "balance.h" -#include "../commons/load.h" -#include "../commons/wind.h" -#include "../commons/hydro.h" -#include "../commons/rowBalance.h" -#include "../commons/psp.h" -#include "../commons/miscGenMinusRowPSP.h" -#include "../commons/solar.h" -#include "../commons/join.h" -#include "../commons/spatial-aggregate.h" - -// For General values -#include "dispatchableGeneration.h" -#include "thermalAirPollutantEmissions.h" -#include "renewableGeneration.h" -#include "overallCost.h" -#include "operatingCost.h" -#include "nonProportionalCost.h" -#include "nbOfDispatchedUnits.h" -#include "hydrostorage.h" -#include "pumping.h" -#include "reservoirlevel.h" -#include "inflow.h" -#include "overflow.h" -#include "waterValue.h" -#include "hydroCost.h" -#include "shortTermStorage.h" -#include "unsupliedEnergy.h" -#include "domesticUnsuppliedEnergy.h" -#include "localMatchingRuleViolations.h" -#include "spilledEnergyAfterCSR.h" -#include "dtgMarginAfterCsr.h" -#include "spilledEnergy.h" - -#include "lold.h" -#include "lolp.h" -#include "max-mrg.h" - -#include "avail-dispatchable-generation.h" -#include "dispatchable-generation-margin.h" - -// By thermal plant -#include "productionByDispatchablePlant.h" -#include "npCostByDispatchablePlant.h" -#include "nbOfDispatchedUnitsByPlant.h" -#include "profitByPlant.h" - -// By RES plant -#include "productionByRenewablePlant.h" - -// Short term storage output variables by cluster -#include "STStorageInjectionByCluster.h" -#include "STStorageWithdrawalByCluster.h" -#include "STStorageLevelsByCluster.h" -#include "STStorageCashFlowByCluster.h" - -// Output variables associated to links -#include "links/flowLinear.h" -#include "links/flowLinearAbs.h" -#include "links/loopFlow.h" -#include "links/flowQuad.h" -#include "links/hurdleCosts.h" -#include "links/congestionFee.h" -#include "links/congestionFeeAbs.h" -#include "links/marginalCost.h" -#include "links/congestionProbability.h" - -// Output variables associated to binding constraints -#include "bindingConstraints/bindingConstraintsMarginalCost.h" - -namespace Antares::Solver::Variable::Economy -{ -/*! -** \brief All variables for a single link (economy) -*/ -typedef FlowLinear // Flow linear - >>>>>>>> - VariablePerLink; -// forward declaration -class Links; - -/*! -** \brief All variables for a single area (economy) -*/ -typedef // Prices - OverallCost // Overall Cost (Op. Cost + Unsupplied Eng.) - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - VariablesPerArea; - -/*! -** \brief All variables for a single set of areas (economy) -*/ -typedef // Prices - Common::SpatialAggregate< - OverallCost, - Common::SpatialAggregate< - OperatingCost, - Common::SpatialAggregate< - Price, - // Thermal pollutants - Common::SpatialAggregate< - ThermalAirPollutantEmissions, - // Production by thermal cluster - Common::SpatialAggregate< - Balance, - // Misc Gen. - Common::SpatialAggregate< - RowBalance, - Common::SpatialAggregate< - PSP, - Common::SpatialAggregate< - MiscGenMinusRowPSP, - // Time series - Common::SpatialAggregate< - TimeSeriesValuesLoad, - Common::SpatialAggregate< - TimeSeriesValuesHydro, - Common::SpatialAggregate< - TimeSeriesValuesWind, - Common::SpatialAggregate< - TimeSeriesValuesSolar, - // Other - Common::SpatialAggregate< - DispatchableGeneration, - Common::SpatialAggregate< - RenewableGeneration, - Common::SpatialAggregate< - HydroStorage, - Common::SpatialAggregate< - Pumping, - Common::SpatialAggregate< - ReservoirLevel, - Common::SpatialAggregate< - Inflows, - Common::SpatialAggregate< - Overflows, - Common::SpatialAggregate< - WaterValue, - Common::SpatialAggregate< - HydroCost, - Common::SpatialAggregate< - ShortTermStorageByGroup, - Common::SpatialAggregate< - UnsupliedEnergy, - Common::SpatialAggregate< - DomesticUnsuppliedEnergy, - Common::SpatialAggregate< - LMRViolations, - Common::SpatialAggregate< - SpilledEnergy, - Common::SpatialAggregate< - SpilledEnergyAfterCSR, - // LOLD - Common::SpatialAggregate< - LOLD, - Common::SpatialAggregate< - LOLP, - Common::SpatialAggregate< - AvailableDispatchGen, - Common::SpatialAggregate< - DispatchableGenMargin, - Common::SpatialAggregate< - DtgMarginCsr, - Common::SpatialAggregate< - Marge, - - // Detail Prices - Common::SpatialAggregate< - NonProportionalCost, // MBO - // 13/05/2014 - // - - // refs: - // #21 - - // Number Of Dispatched Units - Common::SpatialAggregate< - NbOfDispatchedUnits // MBO - // 25/02/2016 - // - - // refs: - // #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - VariablesPerSetOfAreas; - -typedef BindingConstMarginCost< // Marginal cost for a binding constraint - Container::EndOfList // End of variable list - > - - VariablesPerBindingConstraints; - -typedef Variable::Join< - // Variables for each area / links attached to the areas - Variable::Areas, - // Variables for each set of areas - Variable::SetsOfAreas, - // Variables for each binding constraint - Variable::BindingConstraints> - ItemList; - -/*! -** \brief All variables for a simulation (economy) -*/ -typedef Container::List AllVariables; - -} // namespace Antares::Solver::Variable::Economy - -// post include -#include "links.h" - -#endif // __SOLVER_VARIABLE_ECONOMY_ALL_H__ diff --git a/src/solver/variable/economy/area.cpp b/src/solver/variable/economy/area.cpp deleted file mode 100644 index bfcd9af7dd..0000000000 --- a/src/solver/variable/economy/area.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "all.h" - -#define NEXTTYPE Economy::VariablesPerArea -#include "../area.inc.hxx" diff --git a/src/solver/variable/economy/area.memory-estimation.cpp b/src/solver/variable/economy/area.memory-estimation.cpp deleted file mode 100644 index 534b0d5c91..0000000000 --- a/src/solver/variable/economy/area.memory-estimation.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "all.h" - -using NEXTTYPE = Solver::Variable::Economy::VariablesPerArea; -#include "../area.memory-estimation.inc.hxx" diff --git a/src/solver/variable/economy/avail-dispatchable-generation.h b/src/solver/variable/economy/avail-dispatchable-generation.h deleted file mode 100644 index 2df9c4fb60..0000000000 --- a/src/solver/variable/economy/avail-dispatchable-generation.h +++ /dev/null @@ -1,297 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_AvailableDispatchGen_H__ -#define __SOLVER_VARIABLE_ECONOMY_AvailableDispatchGen_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardAvailableDispatchGen -{ - //! Caption - static std::string Caption() - { - return "AVL DTG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Available dispatchable generation"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardAvailableDispatchGen VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal AvailableDispatchGen -*/ -template -class AvailableDispatchGen - : public Variable::IVariable, NextT, VCardAvailableDispatchGen> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardAvailableDispatchGen VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~AvailableDispatchGen() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average thoughout all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void addThermalClusterList(Data::ThermalClusterList& list, unsigned int year, unsigned int numSpace) - { - for (auto& [name, cluster] : list) - { - const auto& availableProduction = cluster->series->getAvailablePowerYearly(year); - for (unsigned int hour = 0; hour != cluster->series->timeSeries.height; ++hour) - pValuesForTheCurrentYear[numSpace].hour[hour] += availableProduction[hour]; - } - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Somme de toutes les productions disponibles pour l'ensemble des - // paliers thermiques (+must-run) - pValuesForTheCurrentYear[numSpace].reset(); - addThermalClusterList(pArea->thermal.list, year, numSpace); - addThermalClusterList(pArea->thermal.mustrunList, year, numSpace); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - // - Data::Area* pArea; - unsigned int pNbYearsParallel; - -}; // class AvailableDispatchGen - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_AvailableDispatchGen_H__ diff --git a/src/solver/variable/economy/balance.h b/src/solver/variable/economy/balance.h deleted file mode 100644 index 39ee9f853a..0000000000 --- a/src/solver/variable/economy/balance.h +++ /dev/null @@ -1,306 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_BALANCE_H__ -#define __SOLVER_VARIABLE_ECONOMY_BALANCE_H__ - -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardBalance -{ - //! Caption - static std::string Caption() - { - return "BALANCE"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - //! The short description of the variable - static std::string Description() - { - return "Nodal energy balance, throughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardBalance VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal Balance -*/ -template -class Balance : public Variable::IVariable, NextT, VCardBalance> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardBalance VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~Balance() - { - delete[] pValuesForTheCurrentYear; - delete[] bilanPays; - delete[] pInterco; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - bilanPays = nullptr; - pInterco = nullptr; - bilanPays = new double[pNbYearsParallel]; - pInterco = new long[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - bilanPays[numSpace] = 0.; - pInterco[numSpace] = 0; - } - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // A single reset is enough - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - bilanPays[numSpace] = 0.; - pInterco[numSpace] = state.problemeHebdo->IndexDebutIntercoOrigine[state.area->index]; - while (pInterco[numSpace] >= 0) - { - bilanPays[numSpace] += state.ntc.ValeurDuFlux[pInterco[numSpace]]; - pInterco[numSpace] - = state.problemeHebdo->IndexSuivantIntercoOrigine[pInterco[numSpace]]; - } - pInterco[numSpace] = state.problemeHebdo->IndexDebutIntercoExtremite[state.area->index]; - while (pInterco[numSpace] >= 0) - { - bilanPays[numSpace] -= state.ntc.ValeurDuFlux[pInterco[numSpace]]; - pInterco[numSpace] - = state.problemeHebdo->IndexSuivantIntercoExtremite[pInterco[numSpace]]; - } - - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = bilanPays[numSpace]; - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - double* bilanPays; - long* pInterco; - - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class Balance - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_BALANCE_H__ diff --git a/src/solver/variable/economy/bc.memory-estimation.cpp b/src/solver/variable/economy/bc.memory-estimation.cpp deleted file mode 100644 index 6af9ebcb85..0000000000 --- a/src/solver/variable/economy/bc.memory-estimation.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "all.h" - -using bc_next_type = Solver::Variable::Economy::VariablesPerBindingConstraints; -#include "../bc.memory-estimation.inc.hxx" \ No newline at end of file diff --git a/src/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h b/src/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h deleted file mode 100644 index c6836a0a01..0000000000 --- a/src/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h +++ /dev/null @@ -1,405 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../../variable.h" -#include "antares/study/binding_constraint/BindingConstraint.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardBindingConstMarginCost -{ - //! Caption - static std::string Caption() - { - return "BC. MARG. COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Marginal cost for binding constraints"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::bindingConstraint, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::bc), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable - columnCount = 1, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 1, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/* - Marginal cost associated to binding constraints : - Suppose that the BC is hourly, - - if binding constraint is not saturated (rhs is not reached) for a given hour, the value is 0; - - if binding constraint is saturated (rhs is reached), the value is the total benefit (�/MW) for - the system that would result in increasing the BC's rhs of 1 MW. -*/ -template -class BindingConstMarginCost - : public Variable::IVariable, NextT, VCardBindingConstMarginCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardBindingConstMarginCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - BindingConstMarginCost() = default; - - ~BindingConstMarginCost() - { - if (pValuesForTheCurrentYear) - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Statistics thoughout all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Set the associated binding constraint - associatedBC_ = study.bindingConstraints.activeContraints()[bindConstraintGlobalIndex_]; - - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void setBindConstraintGlobalIndex(uint bc_index) - { - bindConstraintGlobalIndex_ = bc_index; - } - - void setBindConstraintsCount(uint bcCount) - { - nbCount_ = bcCount; - } - - size_t getMaxNumberColumns() const - { - return nbCount_ * ResultsType::count; - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - if (!isInitialized()) - return; - - // Compute statistics for the current year depending on - // the BC type (hourly, daily, weekly) - using namespace Data; - switch (associatedBC_->type()) - { - case BindingConstraint::typeHourly: - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); - break; - case BindingConstraint::typeDaily: - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromDailyResults(); - break; - case BindingConstraint::typeWeekly: - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromWeeklyResults(); - break; - case BindingConstraint::typeUnknown: - case BindingConstraint::typeMax: - break; - } - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void weekBegin(State& state) - { - if (!isInitialized()) - return; - - auto numSpace = state.numSpace; - // For daily binding constraints, getting daily marginal price - using namespace Data; - switch (associatedBC_->type()) - { - case BindingConstraint::typeHourly: - case BindingConstraint::typeUnknown: - case BindingConstraint::typeMax: - return; - - case BindingConstraint::typeDaily: - { - int dayInTheYear = state.weekInTheYear * 7; - for (int dayInTheWeek = 0; dayInTheWeek < 7; dayInTheWeek++) - { - pValuesForTheCurrentYear[numSpace].day[dayInTheYear] - -= state.problemeHebdo - ->ResultatsContraintesCouplantes[bindConstraintGlobalIndex_] - .variablesDuales[dayInTheWeek]; - - dayInTheYear++; - } - break; - } - - // For weekly binding constraints, getting weekly marginal price - case BindingConstraint::typeWeekly: - { - uint weekInTheYear = state.weekInTheYear; - double weeklyValue - = -state.problemeHebdo->ResultatsContraintesCouplantes[bindConstraintGlobalIndex_] - .variablesDuales[0]; - - pValuesForTheCurrentYear[numSpace].week[weekInTheYear] = weeklyValue; - - int dayInTheYear = state.weekInTheYear * 7; - for (int dayInTheWeek = 0; dayInTheWeek < 7; dayInTheWeek++) - { - pValuesForTheCurrentYear[numSpace].day[dayInTheYear] = weeklyValue; - dayInTheYear++; - } - break; - } - } - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourEnd(State& state, unsigned int hourInTheYear) - { - if (!isInitialized()) - return; - - auto numSpace = state.numSpace; - if (associatedBC_->type() == Data::BindingConstraint::typeHourly) - { - pValuesForTheCurrentYear[numSpace][hourInTheYear] - -= state.problemeHebdo->ResultatsContraintesCouplantes[bindConstraintGlobalIndex_] - .variablesDuales[state.hourInTheWeek]; - } - - NextType::hourEnd(state, hourInTheYear); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport( - SurveyResults& results, - int fileLevel, - int precision /* printed results : hourly, daily, weekly, ...*/, - unsigned int numSpace) const - { - if (!(precision & associatedBC_->yearByYearFilter())) - return; - - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA[0] = isCurrentOutputNonApplicable(precision); - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = getBindConstraintCaption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - - void buildSurveyReport(SurveyResults& results, - int dataLevel, - int fileLevel, - int precision) const - { - // Building syntheses results - // ------------------------------ - if (!(precision & associatedBC_->yearByYearFilter())) - return; - - // And only if we match the current data level _and_ precision level - if ((dataLevel & VCardType::categoryDataLevel) && (fileLevel & VCardType::categoryFileLevel) - && (precision & VCardType::precision)) - { - results.isPrinted = AncestorType::isPrinted; - results.isCurrentVarNA[0] = isCurrentOutputNonApplicable(precision); - results.variableCaption = getBindConstraintCaption(); - - VariableAccessorType::template BuildSurveyReport( - results, AncestorType::pResults, dataLevel, fileLevel, precision, false); - } - } - -private: - // Private methods - // --------------- - std::string getBindConstraintCaption() const - { - std::string mathOperator(Antares::Data::BindingConstraint::MathOperatorToCString(associatedBC_->operatorType())); - return std::string() + associatedBC_->name().c_str() + " (" + mathOperator + ")"; - } - - bool isInitialized() - { - return (bindConstraintGlobalIndex_ >= 0) && associatedBC_; - } - - bool isCurrentOutputNonApplicable(int precision) const - { - using namespace Antares::Data; - // The current marginal prices to print becomes non applicable if they have a precision - // (hour, day, week, ...) smaller than the associated binding constraint granularity. - // Ex : if the BC is daily and we try to print hourly associated marginal prices, - // then these prices are set to N/A - switch (associatedBC_->type()) - { - case BindingConstraint::typeUnknown: - case BindingConstraint::typeMax: - return true; - default: - const auto precision_bc = 1 << (associatedBC_->type() - 1); - return precision < precision_bc; - } - } - - // Private data mambers - // ---------------------- - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear = nullptr; - unsigned int pNbYearsParallel = 0; - std::shared_ptr associatedBC_ = nullptr; - int bindConstraintGlobalIndex_ = -1; - uint nbCount_ = 0; // Number of inequality BCs - -}; // class BindingConstMarginCost - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares diff --git a/src/solver/variable/economy/dispatchable-generation-margin.h b/src/solver/variable/economy/dispatchable-generation-margin.h deleted file mode 100644 index 5bf3ac9297..0000000000 --- a/src/solver/variable/economy/dispatchable-generation-margin.h +++ /dev/null @@ -1,296 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_DispatchableGenMargin_H__ -#define __SOLVER_VARIABLE_ECONOMY_DispatchableGenMargin_H__ - -#include "../variable.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardDispatchableGenMargin -{ - //! Caption - static std::string Caption() - { - return "DTG MRG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Dispatchable Generation Margin"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardDispatchableGenMargin VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal DispatchableGenMargin -*/ -template -class DispatchableGenMargin - : public Variable::IVariable, NextT, VCardDispatchableGenMargin> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardDispatchableGenMargin VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~DispatchableGenMargin() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average thoughout all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - += state.scratchpad->dispatchableGenerationMargin[state.hourInTheWeek]; - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - template - inline const double* retrieveHourlyResultsForCurrentYear(unsigned int numSpace) const - { - typedef RetrieveResultsAssignment< - Yuni::Static::Type::StrictlyEqual::Yes> - AssignT; - return (AssignT::Yes) - ? Memory::RawPointer(pValuesForTheCurrentYear[numSpace].hour) - : NextType::template retrieveHourlyResultsForCurrentYear(numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - Data::Area* pArea; - unsigned int pNbYearsParallel; - -}; // class DispatchableGenMargin - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_DispatchableGenMargin_H__ diff --git a/src/solver/variable/economy/dispatchableGeneration.h b/src/solver/variable/economy/dispatchableGeneration.h deleted file mode 100644 index c9a7b7c202..0000000000 --- a/src/solver/variable/economy/dispatchableGeneration.h +++ /dev/null @@ -1,327 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_DispatchableGeneration_H__ -#define __SOLVER_VARIABLE_ECONOMY_DispatchableGeneration_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardDispatchableGeneration -{ - //! Caption - static std::string Caption() - { - return "Dispatch. Gen."; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Value of all the dispatchable generation throughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardDispatchableGeneration VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 10, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType[columnCount]; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - - struct Multiple - { - static std::string Caption(const unsigned int indx) - { - switch (indx) - { - case 0: - return "NUCLEAR"; - case 1: - return "LIGNITE"; - case 2: - return "COAL"; - case 3: - return "GAS"; - case 4: - return "OIL"; - case 5: - return "MIX. FUEL"; - case 6: - return "MISC. DTG"; - case 7: - return "MISC. DTG 2"; - case 8: - return "MISC. DTG 3"; - case 9: - return "MISC. DTG 4"; - - default: - return ""; - } - } - static std::string Unit([[maybe_unused]] const unsigned int indx) - { - return VCardDispatchableGeneration::Unit(); - } - }; -}; // class VCard - -/*! -** \brief Marginal DispatchableGeneration -*/ -template -class DispatchableGeneration - : public Variable::IVariable, NextT, VCardDispatchableGeneration> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardDispatchableGeneration VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~DispatchableGeneration() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - { - results[i].initializeFromStudy(study); - results[i].reset(); - } - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - VariableAccessorType::template ComputeStatistics( - pValuesForTheCurrentYear[numSpace]); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - VariableAccessorType::ComputeSummary( - pValuesForTheCurrentYear[numSpace], AncestorType::pResults, numSpaceToYear[numSpace]); - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - auto area = state.area; - auto& thermal = state.thermal; - for (uint clusterIndex = 0; clusterIndex != state.area->thermal.clusterCount(); - ++clusterIndex) - { - const auto* thermalCluster = area->thermal.clusters[clusterIndex]; - pValuesForTheCurrentYear[numSpace][thermalCluster->groupID][state.hourInTheYear] - += thermal[area->index].thermalClustersProductions[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // The current variable is actually a multiple-variable. - results.isCurrentVarNA = AncestorType::isNonApplicable; - - for (uint i = 0; i != VCardType::columnCount; ++i) - { - if (AncestorType::isPrinted[i]) - { - // Write the data for the current year - results.variableCaption = VCardType::Multiple::Caption(i); - results.variableUnit = VCardType::Multiple::Unit(i); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - results.isCurrentVarNA++; - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class DispatchableGeneration - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_DispatchableGeneration_H__ diff --git a/src/solver/variable/economy/domesticUnsuppliedEnergy.h b/src/solver/variable/economy/domesticUnsuppliedEnergy.h deleted file mode 100644 index a9db294bc4..0000000000 --- a/src/solver/variable/economy/domesticUnsuppliedEnergy.h +++ /dev/null @@ -1,284 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ -#define __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardDomesticUnsuppliedEnergy -{ - //! Caption - static std::string Caption() - { - return "DENS"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - //! The short description of the variable - static std::string Description() - { - return "Domestic Unsupplied Energy (demand that cannot be satisfied without " - "interconnections/links)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardDomesticUnsuppliedEnergy VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall DomesticUnsuppliedEnergy emissions expected from all -** the thermal dispatchable clusters -*/ -template -class DomesticUnsuppliedEnergy - : public Variable::IVariable, NextT, VCardDomesticUnsuppliedEnergy> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardDomesticUnsuppliedEnergy VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~DomesticUnsuppliedEnergy() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Total DomesticUnsuppliedEnergy emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDENS[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class DomesticUnsuppliedEnergy - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ diff --git a/src/solver/variable/economy/dtgMarginAfterCsr.h b/src/solver/variable/economy/dtgMarginAfterCsr.h deleted file mode 100644 index f16a4fd2bc..0000000000 --- a/src/solver/variable/economy/dtgMarginAfterCsr.h +++ /dev/null @@ -1,272 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ -#define __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardDtgMarginCsr -{ - //! Caption - static std::string Caption() - { - return "DTG MRG CSR"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - //! The short description of the variable - static std::string Description() - { - return "Dispatchable Generation Margin (after CSR optimization)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardDtgMarginCsr VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall DtgMarginCsr emissions expected from all -** the thermal dispatchable clusters -*/ -template -class DtgMarginCsr : public Variable::IVariable, NextT, VCardDtgMarginCsr> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardDtgMarginCsr VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - - ~DtgMarginCsr() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Total DtgMarginCsr - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class DtgMarginCsr - -} // namespace Antares::Solver::Variable::Economy - -#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ diff --git a/src/solver/variable/economy/hydroCost.h b/src/solver/variable/economy/hydroCost.h deleted file mode 100644 index d359f080e6..0000000000 --- a/src/solver/variable/economy/hydroCost.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_HydroCost_H__ -#define __SOLVER_VARIABLE_ECONOMY_HydroCost_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardHydroCost -{ - //! Caption - static std::string Caption() - { - return "H. COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydro Cost throughout all MC years, of all the thermal dispatchable clusters"; - } - - //! The expecte results - typedef Results>>>, - R::AllYears::Average> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardHydroCost VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Hydro costs -*/ -template -class HydroCost : public Variable::IVariable, NextT, VCardHydroCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardHydroCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~HydroCost() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Setting the pumping efficiency - pPumpRatio = area->hydro.pumpingEfficiency; - - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Hydro costs : storage and pumping - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += state.hourlyResults->valeurH2oHoraire[state.hourInTheWeek] - * (state.hourlyResults->TurbinageHoraire[state.hourInTheWeek] - - pPumpRatio * state.hourlyResults->PompageHoraire[state.hourInTheWeek]); - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - double pPumpRatio; - -}; // class HydroCost - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_HydroCost_H__ diff --git a/src/solver/variable/economy/hydrostorage.h b/src/solver/variable/economy/hydrostorage.h deleted file mode 100644 index 61e77c35b7..0000000000 --- a/src/solver/variable/economy/hydrostorage.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_HydroStorage_H__ -#define __SOLVER_VARIABLE_ECONOMY_HydroStorage_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardHydroStorage -{ - //! Caption - static std::string Caption() - { - return "H. STOR"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydro Storage Generation"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardHydroStorage VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall HydroStorage emissions expected from all -** the thermal dispatchable clusters -*/ -template -class HydroStorage : public Variable::IVariable, NextT, VCardHydroStorage> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardHydroStorage VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~HydroStorage() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily, weekly, monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Total HydroStorage emissions - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = - // Current Hydro Storage generation - state.hourlyResults->TurbinageHoraire[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class HydroStorage - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_HydroStorage_H__ diff --git a/src/solver/variable/economy/inflow.h b/src/solver/variable/economy/inflow.h deleted file mode 100644 index 21ab8c531d..0000000000 --- a/src/solver/variable/economy/inflow.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_Inflows_H__ -#define __SOLVER_VARIABLE_ECONOMY_Inflows_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardInflows -{ - //! Caption - static std::string Caption() - { - return "H. INFL"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydraulic inflows"; - } - - //! The expected results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardInflows VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Inflows -*/ -template -class Inflows : public Variable::IVariable, NextT, VCardInflows> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardInflows VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~Inflows() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Next - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily, weekly, monthly, annual). - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Retrieving the inflows - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - = state.problemeHebdo->CaracteristiquesHydrauliques[pArea->index] - .ApportNaturelHoraire[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! The attached area - Antares::Data::Area* pArea; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class Inflows - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_Inflows_H__ diff --git a/src/solver/variable/economy/links.cpp b/src/solver/variable/economy/links.cpp deleted file mode 100644 index 0f0dde8bf0..0000000000 --- a/src/solver/variable/economy/links.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "links.h" -#include "../commons/links/links.cpp.inc.hxx" diff --git a/src/solver/variable/economy/links.h b/src/solver/variable/economy/links.h deleted file mode 100644 index ccd1b3cf93..0000000000 --- a/src/solver/variable/economy/links.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_LINK_H__ -#define __SOLVER_VARIABLE_ECONOMY_LINK_H__ - -#ifdef LINK_NAMESPACE -#undef LINK_NAMESPACE -#endif -#define LINK_NAMESPACE Economy - -#include -#include "all.h" -#include "../commons/links/links.h.inc.hxx" - -#endif // __SOLVER_VARIABLE_ECONOMY_LINK_H__ diff --git a/src/solver/variable/economy/links/congestionFee.h b/src/solver/variable/economy/links/congestionFee.h deleted file mode 100644 index ebd09a8854..0000000000 --- a/src/solver/variable/economy/links/congestionFee.h +++ /dev/null @@ -1,290 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_CongestionFee_H__ -#define __SOLVER_VARIABLE_ECONOMY_CongestionFee_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardCongestionFee -{ - //! Caption - static std::string Caption() - { - return "CONG. FEE (ALG.)"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Congestion fee collected throughout all MC years (Alg.)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal CongestionFee -*/ -template -class CongestionFee : public Variable::IVariable, NextT, VCardCongestionFee> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardCongestionFee VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~CongestionFee() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(uint year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { -#define UPSTREAM_PRICE \ - state.problemeHebdo->ResultatsHoraires[state.link->from->index] \ - .CoutsMarginauxHoraires[state.hourInTheWeek] -#define DOWNSTREAM_PRICE \ - state.problemeHebdo->ResultatsHoraires[state.link->with->index] \ - .CoutsMarginauxHoraires[state.hourInTheWeek] - - // Congestion Fee - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - = state.ntc.ValeurDuFlux[state.link->index] * (UPSTREAM_PRICE - DOWNSTREAM_PRICE); - // Next item in the list - NextType::hourForEachLink(state, numSpace); - -#undef UPSTREAM_PRICE -#undef DOWNSTREAM_PRICE - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class CongestionFee - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_CongestionFee_H__ diff --git a/src/solver/variable/economy/links/congestionFeeAbs.h b/src/solver/variable/economy/links/congestionFeeAbs.h deleted file mode 100644 index 37bba69e88..0000000000 --- a/src/solver/variable/economy/links/congestionFeeAbs.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_CongestionFeeAbs_H__ -#define __SOLVER_VARIABLE_ECONOMY_CongestionFeeAbs_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardCongestionFeeAbs -{ - //! Caption - static std::string Caption() - { - return "CONG. FEE (ABS.)"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Congestion fee collected throughout all MC years (Absolute value)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal CongestionFeeAbs -*/ -template -class CongestionFeeAbs - : public Variable::IVariable, NextT, VCardCongestionFeeAbs> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardCongestionFeeAbs VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~CongestionFeeAbs() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { -#define UPSTREAM_PRICE \ - state.problemeHebdo->ResultatsHoraires[state.link->from->index] \ - .CoutsMarginauxHoraires[state.hourInTheWeek] -#define DOWNSTREAM_PRICE \ - state.problemeHebdo->ResultatsHoraires[state.link->with->index] \ - .CoutsMarginauxHoraires[state.hourInTheWeek] - - // Congestion Fee - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = Yuni::Math::Abs( - state.ntc.ValeurDuFlux[state.link->index] * (UPSTREAM_PRICE - DOWNSTREAM_PRICE)); - // Next item in the list - NextType::hourForEachLink(state, numSpace); - -#undef UPSTREAM_PRICE -#undef DOWNSTREAM_PRICE - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class CongestionFeeAbs - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_CongestionFeeAbs_H__ diff --git a/src/solver/variable/economy/links/congestionProbability.h b/src/solver/variable/economy/links/congestionProbability.h deleted file mode 100644 index 6e81772f41..0000000000 --- a/src/solver/variable/economy/links/congestionProbability.h +++ /dev/null @@ -1,362 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_CongestionProbability_H__ -#define __SOLVER_VARIABLE_ECONOMY_CongestionProbability_H__ - -#include "../../variable.h" -#include - -namespace Antares::Solver::Variable::Economy -{ -struct VCardCongestionProbability -{ - //! Caption - static std::string Caption() - { - return "CONG. PROB. (+/-)"; - } - //! Unit - static std::string Unit() - { - return "%"; - } - - //! The short description of the variable - static std::string Description() - { - return "Probability for the line to be congested in the upstream-downstream way"; - } - - //! The expecte results - typedef Results> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 2, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType[columnCount]; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - struct Multiple - { - static std::string Caption(uint indx) - { - switch (indx) - { - case 0: - return "CONG. PROB +"; - case 1: - return "CONG. PROB -"; - default: - return ""; - } - } - - static std::string Unit([[maybe_unused]] const unsigned int indx) - { - return VCardCongestionProbability::Unit(); - } - }; - -}; // class VCard - -/*! -** \brief Marginal CongestionProbability -*/ -template -class CongestionProbability - : public Variable::IVariable, NextT, VCardCongestionProbability> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardCongestionProbability VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~CongestionProbability() - { - delete[] pValuesForTheCurrentYear; - delete[] pValuesForYearLocalReport; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - yearsWeight = study.parameters.getYearsWeight(); - yearsWeightSum = study.parameters.getYearsWeightSum(); - - // Average on all years - for (uint i = 0; i != VCardType::columnCount; ++i) - { - AncestorType::pResults[i].initializeFromStudy(study); - AncestorType::pResults[i].reset(); - } - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); - - pValuesForYearLocalReport = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForYearLocalReport[numSpace][i].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - { - pValuesForTheCurrentYear[numSpace][0].reset(); - pValuesForTheCurrentYear[numSpace][1].reset(); - } - - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Next variable - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset - pValuesForTheCurrentYear[numSpace][0].reset(); - pValuesForTheCurrentYear[numSpace][1].reset(); - - pValuesForYearLocalReport[numSpace][0].reset(); - pValuesForYearLocalReport[numSpace][1].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(uint year, uint numSpace) - { - for (uint i = 0; i != VCardType::columnCount; ++i) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace][i].computeProbabilitiesForTheCurrentYear(); - } - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (uint i = 0; i != VCardType::columnCount; ++i) - { - // Merge all those values with the global results - AncestorType::pResults[i].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][i]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - // Ratio take into account MC year weight - float ratio = yearsWeight[state.year] / yearsWeightSum; - - assert(state.link != NULL); - const auto& linkDirectCapa = state.link->directCapacities; - const auto& linkIndirectCapa = state.link->indirectCapacities; - const int tsIndex = NumeroChroniquesTireesParInterconnexion[numSpace][state.link->index] - .TransmissionCapacities; - // CONG. PROB + - if (state.ntc.ValeurDuFlux[state.link->index] - > +linkDirectCapa.entry[tsIndex][state.hourInTheYear] - 10e-6) - pValuesForTheCurrentYear[numSpace][0].hour[state.hourInTheYear] += 100.0 * ratio; - // CONG. PROB - - if (state.ntc.ValeurDuFlux[state.link->index] - < -linkIndirectCapa.entry[tsIndex][state.hourInTheYear] + 10e-6) - pValuesForTheCurrentYear[numSpace][1].hour[state.hourInTheYear] += 100.0 * ratio; - - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void beforeYearByYearExport(uint /*year*/, uint numSpace) - { - for (uint i = 0; i != VCardType::columnCount; ++i) - { - for (uint h = 0; h != maxHoursInAYear; ++h) - pValuesForYearLocalReport[numSpace][i].hour[h] - = (pValuesForTheCurrentYear[numSpace][i].hour[h] > 0.) ? 100. : 0.; - - for (uint d = 0; d != maxDaysInAYear; ++d) - pValuesForYearLocalReport[numSpace][i].day[d] - = (pValuesForTheCurrentYear[numSpace][i].day[d] > 0.) ? 100. : 0.; - - for (uint w = 0; w != maxWeeksInAYear; ++w) - pValuesForYearLocalReport[numSpace][i].week[w] - = (pValuesForTheCurrentYear[numSpace][i].week[w] > 0.) ? 100. : 0.; - - for (uint m = 0; m != maxMonths; ++m) - pValuesForYearLocalReport[numSpace][i].month[m] - = (pValuesForTheCurrentYear[numSpace][i].month[m] > 0.) ? 100. : 0.; - - pValuesForYearLocalReport[numSpace][i].year - = (pValuesForTheCurrentYear[numSpace][i].year > 0.) ? 100. : 0.; - } - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint column, - uint numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint numSpace) const - { - // The current variable is actually a multiple-variable. - results.isCurrentVarNA = AncestorType::isNonApplicable; - - for (uint i = 0; i != VCardType::columnCount; ++i) - { - if (AncestorType::isPrinted[i]) - { - // Write the data for the current year - results.variableCaption = VCardType::Multiple::Caption(i); - results.variableUnit = VCardType::Multiple::Unit(i); - pValuesForYearLocalReport[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - results.isCurrentVarNA++; - } - } - -private: - std::vector yearsWeight; - float yearsWeightSum; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - typename VCardType::IntermediateValuesType pValuesForYearLocalReport; - unsigned int pNbYearsParallel; - -}; // class CongestionProbability - -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_CongestionProbability_H__ diff --git a/src/solver/variable/economy/links/flowLinear.h b/src/solver/variable/economy/links/flowLinear.h deleted file mode 100644 index cbdef3fdab..0000000000 --- a/src/solver/variable/economy/links/flowLinear.h +++ /dev/null @@ -1,296 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_FlowLinear_H__ -#define __SOLVER_VARIABLE_ECONOMY_FlowLinear_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardFlowLinear -{ - //! Caption - static std::string Caption() - { - return "FLOW LIN."; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Flow assessed, over all MC years, through linear optimization"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal FlowLinear -*/ -template -class FlowLinear : public Variable::IVariable, NextT, VCardFlowLinear> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardFlowLinear VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~FlowLinear() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - // Flow assessed over all MC years (linear) - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += state.ntc.ValeurDuFlux[state.link->index]; - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - if (dataLevel & Category::link) - { - if (digestLevel & Category::digestFlowLinear) - { - results.data.matrix - .entry[results.data.link->from->index][results.data.link->with->index] - = AncestorType::pResults.avgdata.allYears; - results.data.matrix - .entry[results.data.link->with->index][results.data.link->from->index] - = -AncestorType::pResults.avgdata.allYears; - } - } - - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class FlowLinear - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_FlowLinear_H__ diff --git a/src/solver/variable/economy/links/flowLinearAbs.h b/src/solver/variable/economy/links/flowLinearAbs.h deleted file mode 100644 index 99e4f2d64c..0000000000 --- a/src/solver/variable/economy/links/flowLinearAbs.h +++ /dev/null @@ -1,284 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_FlowLinearAbs_H__ -#define __SOLVER_VARIABLE_ECONOMY_FlowLinearAbs_H__ - -#include "../../variable.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardFlowLinearAbs -{ - //! Caption - static std::string Caption() - { - return "UCAP LIN."; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Used capacity assessed, over all MC years, through linear optimization"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal FlowLinearAbs -*/ -template -class FlowLinearAbs : public Variable::IVariable, NextT, VCardFlowLinearAbs> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardFlowLinearAbs VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~FlowLinearAbs() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - // Flow assessed over all MC years (linear) - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += Yuni::Math::Abs(state.ntc.ValeurDuFlux[state.link->index]); - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class FlowLinearAbs - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_FlowLinearAbs_H__ diff --git a/src/solver/variable/economy/links/flowQuad.h b/src/solver/variable/economy/links/flowQuad.h deleted file mode 100644 index 135b6364ca..0000000000 --- a/src/solver/variable/economy/links/flowQuad.h +++ /dev/null @@ -1,287 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_FlowQuad_H__ -#define __SOLVER_VARIABLE_ECONOMY_FlowQuad_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardFlowQuad -{ - //! Caption - static std::string Caption() - { - return "FLOW QUAD."; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Flow (quad.)"; - } - - //! The expecte results - typedef Results> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal FlowQuad -*/ -template -class FlowQuad : public Variable::IVariable, NextT, VCardFlowQuad> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardFlowQuad VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~FlowQuad() - { - } - - void initializeFromStudy(Data::Study& study) - { - // Average on all years - pNbHours = study.runtime->rangeLimits.hour[Data::rangeEnd] + 1; - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear.initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - assert(link && "invalid interconnection"); - pLinkGlobalIndex = link->index; - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - pValuesForTheCurrentYear.reset(); - - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Flow assessed over all MC years (linear) - (void)::memcpy( - pValuesForTheCurrentYear.hour, - transitMoyenInterconnexionsRecalculQuadratique[pLinkGlobalIndex].data(), - sizeof(double) * pNbHours); - - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear.computeStatisticsForTheCurrentYear(); - // Merge all those values with the global results - AncestorType::pResults.merge(0, pValuesForTheCurrentYear); - - // Next - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(uint year, unsigned int numSpace) - { - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - if (dataLevel & Category::link) - { - if (digestLevel & Category::digestFlowQuad) - { - results.data.matrix - .entry[results.data.link->from->index][results.data.link->with->index] - = AncestorType::pResults.rawdata.allYears; - results.data.matrix - .entry[results.data.link->with->index][results.data.link->from->index] - = -AncestorType::pResults.rawdata.allYears; - } - } - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint) const - { - return pValuesForTheCurrentYear.hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear.template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - uint pLinkGlobalIndex; - uint pNbHours; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - -}; // class FlowQuad - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_FlowQuad_H__ diff --git a/src/solver/variable/economy/links/hurdleCosts.h b/src/solver/variable/economy/links/hurdleCosts.h deleted file mode 100644 index 40f0c3e710..0000000000 --- a/src/solver/variable/economy/links/hurdleCosts.h +++ /dev/null @@ -1,333 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_HURDLE_COSTS_H__ -#define __SOLVER_VARIABLE_ECONOMY_HURDLE_COSTS_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardHurdleCosts -{ - //! Caption - static std::string Caption() - { - return "HURDLE COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hurdle costs, over all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal HurdleCosts -*/ -template -class HurdleCosts : public Variable::IVariable, NextT, VCardHurdleCosts> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardHurdleCosts VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~HurdleCosts() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - // Flow assessed over all MC years (linear) - if (state.link->useHurdlesCost) - { - const double flowLinear = state.ntc.ValeurDuFlux[state.link->index]; - - if (state.link->useLoopFlow) - { - const double loopFlow = state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] - .ValeurDeLoopFlowOrigineVersExtremite[state.link->index]; - if (flowLinear - loopFlow > 0.) - { - const double hurdleCostDirect - = (flowLinear - loopFlow) - * state.link->parameters - .entry[Data::fhlHurdlesCostDirect][state.hourInTheYear]; - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += hurdleCostDirect; - // Incrementing annual system cost (to be printed in output in a separate file) - state.annualSystemCost += hurdleCostDirect; - } - else - { - const double hurdleCostIndirect - = -(flowLinear - loopFlow) - * state.link->parameters - .entry[Data::fhlHurdlesCostIndirect][state.hourInTheYear]; - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += hurdleCostIndirect; - // Incrementing annual system cost (to be printed in output into a separate - // file) - state.annualSystemCost += hurdleCostIndirect; - } - } - else - { - if (flowLinear > 0.) - { - const double hurdleCostDirect - = flowLinear - * state.link->parameters - .entry[Data::fhlHurdlesCostDirect][state.hourInTheYear]; - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += hurdleCostDirect; - // Incrementing annual system cost (to be printed in output in a separate file) - state.annualSystemCost += hurdleCostDirect; - } - else - { - const double hurdleCostIndirect - = -flowLinear - * state.link->parameters - .entry[Data::fhlHurdlesCostIndirect][state.hourInTheYear]; - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - += hurdleCostIndirect; - // Incrementing annual system cost (to be printed in output into a separate - // file) - state.annualSystemCost += hurdleCostIndirect; - } - } - } - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; -}; // class HurdleCosts - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_HURDLE_COSTS_H__ diff --git a/src/solver/variable/economy/links/loopFlow.h b/src/solver/variable/economy/links/loopFlow.h deleted file mode 100644 index 4efc510af0..0000000000 --- a/src/solver/variable/economy/links/loopFlow.h +++ /dev/null @@ -1,282 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_LoopFlow_H__ -#define __SOLVER_VARIABLE_ECONOMY_LoopFlow_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardLoopFlow -{ - //! Caption - static std::string Caption() - { - return "LOOP FLOW"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Loop flow"; - } - - //! The expecte results - typedef Results> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesType; - -}; // class VCard - -/*! -** \brief LoopFlow -*/ -template -class LoopFlow : public Variable::IVariable, NextT, VCardLoopFlow> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardLoopFlow VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~LoopFlow() - { - } - - void initializeFromStudy(Data::Study& study) - { - // Average on all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear.initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - if (link->useLoopFlow) - { - // Flow assessed over all MC years (linear) - unsigned int height = link->parameters.height; - (void)::memcpy(pValuesForTheCurrentYear.hour, - link->parameters[Data::fhlLoopFlow], - sizeof(double) * height); - } - - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear.computeStatisticsForTheCurrentYear(); - // Merge all those values with the global results - AncestorType::pResults.merge(0, pValuesForTheCurrentYear); - - // Next - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(uint year, unsigned int numSpace) - { - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint) const - { - return pValuesForTheCurrentYear.hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear.template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - -}; // class LoopFlow - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_LoopFlow_H__ diff --git a/src/solver/variable/economy/links/marginalCost.h b/src/solver/variable/economy/links/marginalCost.h deleted file mode 100644 index 7ffdd30246..0000000000 --- a/src/solver/variable/economy/links/marginalCost.h +++ /dev/null @@ -1,294 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_MarginalCost_H__ -#define __SOLVER_VARIABLE_ECONOMY_MarginalCost_H__ - -#include "../../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardMarginalCost -{ - //! Caption - static std::string Caption() - { - return "MARG. COST"; - } - //! Unit - static std::string Unit() - { - return "Euro/MW"; - } - - //! The short description of the variable - static std::string Description() - { - return "Decrease of the overall operating cost expected by a 1MW capacity reinforcement"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - enum - { - //! Data Level - categoryDataLevel = Category::link, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Marginal MarginalCost -*/ -template -class MarginalCost : public Variable::IVariable, NextT, VCardMarginalCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardMarginalCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~MarginalCost() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average on all years - AncestorType::pResults.initializeFromStudy(study); - AncestorType::pResults.reset(); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourForEachLink(State& state, unsigned int numSpace) - { - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = Yuni::Math::Abs( - state.problemeHebdo->VariablesDualesDesContraintesDeNTC[state.hourInTheWeek] - .VariableDualeParInterconnexion[state.link->index]); - - // This value should be reset to zero if (flow_lowerbound) < flow < (flow_upperbound) (with - // signed values) - double flow - = state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek].ValeurDuFlux[state.link->index]; - double flow_lowerbound = -state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] - .ValeurDeNTCExtremiteVersOrigine[state.link->index]; - double flow_upperbound = state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] - .ValeurDeNTCOrigineVersExtremite[state.link->index]; - - if (flow - 0.001 > flow_lowerbound && flow + 0.001 < flow_upperbound) - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 0.; - - // Next item in the list - NextType::hourForEachLink(state, numSpace); - } - - void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Next - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - uint numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - uint numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class MarginalCost - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_MarginalCost_H__ diff --git a/src/solver/variable/economy/localMatchingRuleViolations.h b/src/solver/variable/economy/localMatchingRuleViolations.h deleted file mode 100644 index cba0651d31..0000000000 --- a/src/solver/variable/economy/localMatchingRuleViolations.h +++ /dev/null @@ -1,269 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ -#define __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardLMRViolations -{ - //! Caption - static std::string Caption() - { - return "LMR VIOL."; - } - //! Unit - static std::string Unit() - { - return " "; - } - - //! The short description of the variable - static std::string Description() - { - return "Local Matching Rule is violated more than the provided threshold"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardLMRViolations VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall CO2 emissions expected from all -** the thermal dispatchable clusters -*/ -template -class LMRViolations : public Variable::IVariable, NextT, VCardLMRViolations> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardLMRViolations VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - - ~LMRViolations() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Total LocalMatchingRule Violations - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesLmrViolations[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class LMRViolations - -} // namespace Antares::Solver::Variable::Economy - -#endif // __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ diff --git a/src/solver/variable/economy/lold.h b/src/solver/variable/economy/lold.h deleted file mode 100644 index 7b0ae19ba7..0000000000 --- a/src/solver/variable/economy/lold.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_LOLD_H__ -#define __SOLVER_VARIABLE_ECONOMY_LOLD_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardLOLD -{ - //! Caption - static std::string Caption() - { - return "LOLD"; - } - //! Unit - static std::string Unit() - { - return "Hours"; - } - - //! The short description of the variable - static std::string Description() - { - return "LOLD"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardUnsupliedEnergy VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSumThen1IfPositive, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief -*/ -template -class LOLD : public Variable::IVariable, NextT, VCardLOLD> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardLOLD VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~LOLD() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // LOLD - if (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] > 0.5) - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 1.; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class LOLD - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_LOLD_H__ diff --git a/src/solver/variable/economy/lolp.h b/src/solver/variable/economy/lolp.h deleted file mode 100644 index 0b11ef4286..0000000000 --- a/src/solver/variable/economy/lolp.h +++ /dev/null @@ -1,278 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_LOLP_H__ -#define __SOLVER_VARIABLE_ECONOMY_LOLP_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardLOLP -{ - //! Caption - static std::string Caption() - { - return "LOLP"; - } - //! Unit - static std::string Unit() - { - return "%"; - } - - //! The short description of the variable - static std::string Description() - { - return "LOLP"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardLOLP VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateOr, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief -*/ -template -class LOLP : public Variable::IVariable, NextT, VCardLOLP> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardLOLP VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~LOLP() - { - delete[] pValuesForTheCurrentYear; - } - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsOrForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // LOLP - if (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] > 0.) - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 100; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class LOLP - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_LOLP_H__ diff --git a/src/solver/variable/economy/max-mrg.cpp b/src/solver/variable/economy/max-mrg.cpp index 80f0bbcfb7..7cb565037f 100644 --- a/src/solver/variable/economy/max-mrg.cpp +++ b/src/solver/variable/economy/max-mrg.cpp @@ -1,51 +1,42 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/variable/economy/max-mrg.h" + #include -#include -#include "max-mrg.h" + #include +#include using namespace Yuni; -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy +namespace Antares::Solver::Variable::Economy { template struct SpillageSelector { template - static auto Value(const State&, const U& weeklyResults, uint) - -> decltype(weeklyResults.ValeursHorairesDeDefaillanceNegative) + static auto Value(const State&, + const U& weeklyResults, + uint) -> decltype(weeklyResults.ValeursHorairesDeDefaillanceNegative) { return weeklyResults.ValeursHorairesDeDefaillanceNegative; } @@ -66,6 +57,7 @@ inline void PrepareMaxMRGFor(const State& state, double* opmrg, uint numSpace) { assert(168 + state.hourInTheYear <= HOURS_PER_YEAR); assert(opmrg && "Invalid OP.MRG target"); + enum { offset = 0, @@ -100,21 +92,26 @@ inline void PrepareMaxMRGFor(const State& state, double* opmrg, uint numSpace) double WH = 0.; { // H.STOR - auto& H = weeklyResults.TurbinageHoraire; for (uint i = offset; i != endHour; ++i) + { WH += H[i]; + } } - if (Math::Zero(WH)) // no hydro + if (Utils::isZero(WH)) // no hydro { for (uint i = offset; i != endHour; ++i) + { opmrg[i] = +S[i] + M[i] - D[i]; + } return; } // initialisation for (uint i = offset; i != endHour; ++i) + { OI[i] = +S[i] + M[i] - D[i]; + } } double bottom = +std::numeric_limits::max(); @@ -124,18 +121,21 @@ inline void PrepareMaxMRGFor(const State& state, double* opmrg, uint numSpace) { double oii = OI[i]; if (oii > top) + { top = oii; + } if (oii < bottom) + { bottom = oii; + } } double ecart = 1.; uint loop = 100; // arbitrary - maximum number of iterations - // ref to the study calendar - auto& calendar = state.study.calendar; // Pmax - const auto& P = area.hydro.maxPower[Data::PartHydro::genMaxP]; + const uint y = problem.year; + const auto& P = area.hydro.series->maxHourlyGenPower; do { @@ -148,22 +148,26 @@ inline void PrepareMaxMRGFor(const State& state, double* opmrg, uint numSpace) assert(i < HOURS_PER_YEAR && "calendar overflow"); if (niveau > OI[i]) { - uint dayYear = calendar.hours[i + state.hourInTheYear].dayYear; - opmrg[i] = Math::Min(niveau, OI[i] + P[dayYear] - H[i]); + opmrg[i] = std::min(niveau, + OI[i] + P.getCoefficient(y, i + state.hourInTheYear) - H[i]); SM += opmrg[i] - OI[i]; } else { - opmrg[i] = Math::Max(niveau, OI[i] - H[i]); + opmrg[i] = std::max(niveau, OI[i] - H[i]); SP += OI[i] - opmrg[i]; } } ecart = SP - SM; if (ecart > 0) + { bottom = niveau; + } else + { top = niveau; + } if (!--loop) { @@ -177,12 +181,13 @@ inline void PrepareMaxMRGFor(const State& state, double* opmrg, uint numSpace) void PrepareMaxMRG(const State& state, double* opmrg, uint numSpace) { if (state.simplexRunNeeded) + { PrepareMaxMRGFor(state, opmrg, numSpace); + } else + { PrepareMaxMRGFor(state, opmrg, numSpace); + } } -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/economy/max-mrg.h b/src/solver/variable/economy/max-mrg.h deleted file mode 100644 index fb912d0cfc..0000000000 --- a/src/solver/variable/economy/max-mrg.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_MARGE_H__ -#define __SOLVER_VARIABLE_ECONOMY_MARGE_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardMARGE -{ - //! Caption - static std::string Caption() - { - return "MAX MRG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Maximum margin throughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardMARGE VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Prepare MAX.MRG results for a given week -*/ -void PrepareMaxMRG(const State& state, double* opmrg, uint numSpace); - -/*! -** \brief Max MRG -*/ -template -class Marge : public Variable::IVariable, NextT, VCardMARGE> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardMARGE VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~Marge() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Next - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - // Merge all those values with the global results - // AncestorType::pResults.merge(year, pValuesForTheCurrentYear); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void weekForEachArea(State& state, unsigned int numSpace) - { - double* rawhourly = Memory::RawPointer(pValuesForTheCurrentYear[numSpace].hour); - PrepareMaxMRG(state, rawhourly + state.hourInTheYear, numSpace); - - // next - NextType::weekForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class Marge - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_MARGE_H__ diff --git a/src/solver/variable/economy/nbOfDispatchedUnits.h b/src/solver/variable/economy/nbOfDispatchedUnits.h deleted file mode 100644 index e4e654cd65..0000000000 --- a/src/solver/variable/economy/nbOfDispatchedUnits.h +++ /dev/null @@ -1,295 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnits_H__ -#define __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnits_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardNbOfDispatchedUnits -{ - //! Caption - static std::string Caption() - { - return "NODU"; - } - //! Unit - static std::string Unit() - { - return " "; - } - - //! The short description of the variable - static std::string Description() - { - return "Number Of Dispatched Units throughout all MC years, of all the thermal " - "dispatchable clusters"; - } - - //! The expecte results - typedef Results>>>, - R::AllYears::Average // The - > - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardNbOfDispatchedUnits VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OperatingCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class NbOfDispatchedUnits - : public Variable::IVariable, NextT, VCardNbOfDispatchedUnits> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardNbOfDispatchedUnits VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~NbOfDispatchedUnits() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; - i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; - ++i) - { - pValuesForTheCurrentYear[numSpace][i] - += state.thermalClusterDispatchedUnitsCountForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class NbOfDispatchedUnits - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnits_H__ diff --git a/src/solver/variable/economy/nbOfDispatchedUnitsByPlant.h b/src/solver/variable/economy/nbOfDispatchedUnitsByPlant.h deleted file mode 100644 index 1e4735d29e..0000000000 --- a/src/solver/variable/economy/nbOfDispatchedUnitsByPlant.h +++ /dev/null @@ -1,360 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnitsByPlant_H__ -#define __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnitsByPlant_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardNbOfDispatchedUnitsByPlant -{ - //! Caption - static std::string Caption() - { - return "NODU by plant"; - } - //! Unit - static std::string Unit() - { - return "NODU"; - } - - //! The short description of the variable - static std::string Description() - { - return "Number of Dispatchable Units by plant"; - } - - //! The expected results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardNbOfDispatchedUnitsByPlant VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - // typedef IntermediateValues IntermediateValuesType; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OperatingCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class NbOfDispatchedUnitsByPlant : public Variable::IVariable, - NextT, - VCardNbOfDispatchedUnitsByPlant> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardNbOfDispatchedUnitsByPlant VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - NbOfDispatchedUnitsByPlant() : pValuesForTheCurrentYear(NULL), pSize(0) - { - } - - ~NbOfDispatchedUnitsByPlant() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - pSize = area->thermal.clusterCount(); - if (pSize) - { - AncestorType::pResults.resize(pSize); - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[pSize]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != pSize; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != pSize; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] = nullptr; - - AncestorType::pResults.clear(); - } - - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return pSize * ResultsType::count; - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != pSize; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildPrepareDataForEachThermalCluster(State& state, - uint year, - unsigned int numSpace) - { - for (unsigned int i = 0; i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; ++i) - { - state.thermalClusterDispatchedUnitsCountForYear[i] += static_cast( - pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i]); - } - - // Next variable - NextType::yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; - i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; - ++i) - { - pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i] - = state.thermalClusterDispatchedUnitsCountForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Merge all results for all thermal clusters - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); - } - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Merge all those values with the global results - AncestorType::pResults[i].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][i]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - auto area = state.area; - auto& thermal = state.thermal; - for (uint clusterIndex = 0; clusterIndex != state.area->thermal.clusterCount(); - ++clusterIndex) - { - const auto* thermalCluster = area->thermal.clusters[clusterIndex]; - pValuesForTheCurrentYear[numSpace][thermalCluster->areaWideIndex] - .hour[state.hourInTheYear] - = thermal[area->index].numberOfUnitsONbyCluster[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace]->hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& thermal = results.data.area->thermal; - - // Write the data for the current year - for (uint i = 0; i < pSize; ++i) - { - // Write the data for the current year - results.variableCaption = thermal.clusters[i]->name(); // VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t pSize; - unsigned int pNbYearsParallel; - -}; // class NbOfDispatchedUnitsByPlant - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnitsByPlant_H__ diff --git a/src/solver/variable/economy/nonProportionalCost.h b/src/solver/variable/economy/nonProportionalCost.h deleted file mode 100644 index 37757da7cb..0000000000 --- a/src/solver/variable/economy/nonProportionalCost.h +++ /dev/null @@ -1,295 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_NonProportionalCost_H__ -#define __SOLVER_VARIABLE_ECONOMY_NonProportionalCost_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardNonProportionalCost -{ - //! Caption - static std::string Caption() - { - return "NP COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Non Proportional Cost throughout all MC years, of all the thermal dispatchable " - "clusters"; - } - - //! The expecte results - typedef Results>>>, - R::AllYears::Average // The - > - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardNonProportionalCost VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OperatingCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class NonProportionalCost - : public Variable::IVariable, NextT, VCardNonProportionalCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardNonProportionalCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~NonProportionalCost() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; - i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; - ++i) - { - pValuesForTheCurrentYear[numSpace][i] - += state.thermalClusterNonProportionalCostForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class NonProportionalCost - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_NonProportionalCost_H__ diff --git a/src/solver/variable/economy/npCostByDispatchablePlant.h b/src/solver/variable/economy/npCostByDispatchablePlant.h deleted file mode 100644 index d28ce151d5..0000000000 --- a/src/solver/variable/economy/npCostByDispatchablePlant.h +++ /dev/null @@ -1,338 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_NonProportionalCostByDispatchablePlant_H__ -#define __SOLVER_VARIABLE_ECONOMY_NonProportionalCostByDispatchablePlant_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardNonProportionalCostByDispatchablePlant -{ - //! Caption - static std::string Caption() - { - return "NP Cost by plant"; - } - //! Unit - static std::string Unit() - { - return "NP Cost - Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Non proportional costs by all the clusters"; - } - - //! The expected results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardNonProportionalCostByDispatchablePlant VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - // typedef IntermediateValues IntermediateValuesType; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OperatingCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class NonProportionalCostByDispatchablePlant - : public Variable::IVariable, - NextT, - VCardNonProportionalCostByDispatchablePlant> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardNonProportionalCostByDispatchablePlant VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> - AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - NonProportionalCostByDispatchablePlant() : pValuesForTheCurrentYear(NULL), pSize(0) - { - } - - ~NonProportionalCostByDispatchablePlant() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - pSize = area->thermal.clusterCount(); - if (pSize) - { - AncestorType::pResults.resize(pSize); - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[pSize]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != pSize; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != pSize; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] = nullptr; - - AncestorType::pResults.clear(); - } - - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return pSize * ResultsType::count; - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != pSize; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; - i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; - ++i) - { - pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i] - = state.thermalClusterNonProportionalCostForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Merge all results for all thermal clusters - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); - } - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Merge all those values with the global results - AncestorType::pResults[i].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][i]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace]->hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& thermal = results.data.area->thermal; - - // Write the data for the current year - for (uint i = 0; i < pSize; ++i) - { - // Write the data for the current year - results.variableCaption = thermal.clusters[i]->name(); // VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t pSize; - unsigned int pNbYearsParallel; - -}; // class NonProportionalCostByDispatchablePlant - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_NonProportionalCostByDispatchablePlant_H__ diff --git a/src/solver/variable/economy/operatingCost.h b/src/solver/variable/economy/operatingCost.h deleted file mode 100644 index 066589229c..0000000000 --- a/src/solver/variable/economy/operatingCost.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_OperatingCost_H__ -#define __SOLVER_VARIABLE_ECONOMY_OperatingCost_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardOperatingCost -{ - //! Caption - static std::string Caption() - { - return "OP. COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Operating Cost throughout all MC years, of all the thermal dispatchable clusters"; - } - - //! The expecte results - typedef Results>>>, - R::AllYears::Average // The - > - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardOperatingCost VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OperatingCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class OperatingCost : public Variable::IVariable, NextT, VCardOperatingCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardOperatingCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~OperatingCost() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; - i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; - ++i) - { - pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterOperatingCostForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class OperatingCost - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_OperatingCost_H__ diff --git a/src/solver/variable/economy/overallCost.h b/src/solver/variable/economy/overallCost.h deleted file mode 100644 index 6760bb4311..0000000000 --- a/src/solver/variable/economy/overallCost.h +++ /dev/null @@ -1,309 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_OverallCost_H__ -#define __SOLVER_VARIABLE_ECONOMY_OverallCost_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardOverallCost -{ - //! Caption - static std::string Caption() - { - return "OV. COST"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Overall Cost throughout all MC years"; - } - - //! The expecte results - typedef Results, - R::AllYears::Average // Use these values for spatial cluster - > - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardOverallCost VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OverallCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class OverallCost : public Variable::IVariable, NextT, VCardOverallCost> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardOverallCost VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~OverallCost() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) - { - // Get end year calculations - for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; - i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; - ++i) - { - pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterOperatingCostForYear[i]; - // Incrementing annual system cost (to be printed in output into a separate file) - state.annualSystemCost += state.thermalClusterOperatingCostForYear[i]; - } - - // Next variable - NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - const double costForSpilledOrUnsuppliedEnergy = - // Total UnsupliedEnergy emissions - (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] - * state.area->thermal.unsuppliedEnergyCost) - + (state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek] - * state.area->thermal.spilledEnergyCost) - // Current hydro storage and pumping generation costs - + (state.hourlyResults->valeurH2oHoraire[state.hourInTheWeek] - * (state.hourlyResults->TurbinageHoraire[state.hourInTheWeek] - - state.area->hydro.pumpingEfficiency - * state.hourlyResults->PompageHoraire[state.hourInTheWeek])); - - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] += costForSpilledOrUnsuppliedEnergy; - - // Incrementing annual system cost (to be printed in output into a separate file) - state.annualSystemCost += costForSpilledOrUnsuppliedEnergy; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class OverallCost - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_OverallCost_H__ diff --git a/src/solver/variable/economy/overflow.h b/src/solver/variable/economy/overflow.h deleted file mode 100644 index 4cde149a68..0000000000 --- a/src/solver/variable/economy/overflow.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_Overflow_H__ -#define __SOLVER_VARIABLE_ECONOMY_Overflow_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardOverflow -{ - //! Caption - static std::string Caption() - { - return "H. OVFL"; - } - //! Unit - static std::string Unit() - { - return "%"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydro overflow"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardOverflow VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 1, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Reservoir level -*/ -template -class Overflows : public Variable::IVariable, NextT, VCardOverflow> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardOverflow VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~Overflows() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily, weekly, monthly, annual). - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Retrieving hourly reservoir levels of week simulation - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - = state.hourlyResults->debordementsHoraires[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class HydroLevel - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_Overflow_H__ diff --git a/src/solver/variable/economy/price.h b/src/solver/variable/economy/price.h deleted file mode 100644 index de651a5124..0000000000 --- a/src/solver/variable/economy/price.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_Price_H__ -#define __SOLVER_VARIABLE_ECONOMY_Price_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardPrice -{ - //! Caption - static std::string Caption() - { - return "MRG. PRICE"; - } - //! Unit - static std::string Unit() - { - return "Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Marginal Price, throughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardPrice VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateAverage, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = Category::spatialAggregatePostProcessingPrice, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Marginal Price -*/ -template -class Price : public Variable::IVariable, NextT, VCardPrice> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardPrice VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~Price() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Average thoughout all years - InitializeResultsFromStudy(AncestorType::pResults, study); - - // Intermediate values - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(uint year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(uint year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(uint hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Marginal Price - // Note: The marginal price provided by the solver is negative - // (naming convention). - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - -= state.hourlyResults->CoutsMarginauxHoraires[state.hourInTheWeek]; - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - uint, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class Price - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_Price_H__ diff --git a/src/solver/variable/economy/productionByDispatchablePlant.h b/src/solver/variable/economy/productionByDispatchablePlant.h deleted file mode 100644 index a43fbe31bf..0000000000 --- a/src/solver/variable/economy/productionByDispatchablePlant.h +++ /dev/null @@ -1,391 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_ProductionByDispatchablePlant_H__ -#define __SOLVER_VARIABLE_ECONOMY_ProductionByDispatchablePlant_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardProductionByDispatchablePlant -{ - //! Caption - static std::string Caption() - { - return "DTG by plant"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Energy generated by all the clusters"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardProductionByDispatchablePlant VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Energy generated by all thermal dispatchable clusters -*/ -template -class ProductionByDispatchablePlant - : public Variable:: - IVariable, NextT, VCardProductionByDispatchablePlant> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardProductionByDispatchablePlant VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> - AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ProductionByDispatchablePlant() : - pValuesForTheCurrentYear(nullptr), pminOfTheClusterForYear(nullptr), pSize(0) - { - } - - ~ProductionByDispatchablePlant() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pminOfTheClusterForYear[numSpace]; - delete[] pminOfTheClusterForYear; - } - - void initializeFromStudy(Data::Study& study) - { - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - pminOfTheClusterForYear = new double*[pNbYearsParallel]; - - // Get the area - pSize = area->thermal.clusterCount(); - if (pSize) - { - AncestorType::pResults.resize(pSize); - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[pSize]; - - // Minimum power values of the cluster for the whole year - from the solver in the - // accurate mode not to be displayed in the output \todo think of a better place like - // the DispatchableMarginForAllAreas done at the beginning of the year - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pminOfTheClusterForYear[numSpace] = new double[pSize * maxHoursInAYear]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != pSize; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != pSize; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - pValuesForTheCurrentYear[numSpace] = nullptr; - pminOfTheClusterForYear[numSpace] = nullptr; - } - - AncestorType::pResults.clear(); - } - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return pSize * ResultsType::count; - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != pSize; ++i) - { - pValuesForTheCurrentYear[numSpace][i].reset(); - - for (unsigned int j = 0; j != maxHoursInAYear; ++j) - { - pminOfTheClusterForYear[numSpace][i * maxHoursInAYear + j] = 0; - } - } - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildPrepareDataForEachThermalCluster(State& state, - uint year, - unsigned int numSpace) - { - for (unsigned int i = 0; i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; ++i) - { - state.thermalClusterProductionForYear[i] - += pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i]; - state.thermalClusterPMinOfTheClusterForYear[i] - += pminOfTheClusterForYear[numSpace] - [(state.thermalCluster->areaWideIndex * maxHoursInAYear) - + i]; - } - - // Next variable - NextType::yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Merge all results for all thermal clusters - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); - } - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Merge all those values with the global results - AncestorType::pResults[i].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][i]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - auto& area = state.area; - auto& thermal = state.thermal; - for (uint clusterIndex = 0; clusterIndex != state.area->thermal.clusterCount(); - ++clusterIndex) - { - const auto* thermalCluster = area->thermal.clusters[clusterIndex]; - // Production for this hour - pValuesForTheCurrentYear[numSpace][thermalCluster->areaWideIndex] - .hour[state.hourInTheYear] - += thermal[area->index].thermalClustersProductions[clusterIndex]; - - pminOfTheClusterForYear[numSpace][(thermalCluster->areaWideIndex * maxHoursInAYear) - + state.hourInTheYear] - = thermal[area->index].PMinOfClusters[clusterIndex]; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Ask to build the digest to the next variable - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - inline uint64_t memoryUsage() const - { - uint64_t r = (sizeof(IntermediateValues) * pSize + IntermediateValues::MemoryUsage()) - * pNbYearsParallel; - r += sizeof(double) * pSize * maxHoursInAYear * pNbYearsParallel; - r += AncestorType::memoryUsage(); - return r; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& thermal = results.data.area->thermal; - - // Write the data for the current year - for (uint i = 0; i < pSize; ++i) - { - // Write the data for the current year - results.variableCaption = thermal.clusters[i]->name(); // VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - double** pminOfTheClusterForYear; - size_t pSize; - unsigned int pNbYearsParallel; - -}; // class ProductionByDispatchablePlant - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_ProductionByDispatchablePlant_H__ diff --git a/src/solver/variable/economy/productionByRenewablePlant.h b/src/solver/variable/economy/productionByRenewablePlant.h deleted file mode 100644 index f0ab02e886..0000000000 --- a/src/solver/variable/economy/productionByRenewablePlant.h +++ /dev/null @@ -1,351 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_ProductionByRenewablePlant_H__ -#define __SOLVER_VARIABLE_ECONOMY_ProductionByRenewablePlant_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardProductionByRenewablePlant -{ - //! Caption - static std::string Caption() - { - return "RES generation by plant"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Energy generated by all the RES clusters"; - } - - //! The expecte results - typedef Results> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardProductionByRenewablePlant VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de_res), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; - -}; // class VCard - -/*! -** \brief Energy generated by all renewable clusters -*/ -template -class ProductionByRenewablePlant : public Variable::IVariable, - NextT, - VCardProductionByRenewablePlant> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardProductionByRenewablePlant VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ProductionByRenewablePlant() : pValuesForTheCurrentYear(nullptr), pSize(0) - { - } - - ~ProductionByRenewablePlant() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - pSize = area->renewable.clusterCount(); - if (pSize) - { - AncestorType::pResults.resize(pSize); - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[pSize]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != pSize; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != pSize; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - { - pValuesForTheCurrentYear[numSpace] = nullptr; - } - - AncestorType::pResults.clear(); - } - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return pSize * ResultsType::count; - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != pSize; ++i) - { - pValuesForTheCurrentYear[numSpace][i].reset(); - } - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuildPrepareDataForEachThermalCluster(State& state, - uint year, - unsigned int numSpace) - { - // Next variable - NextType::yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Merge all results for all renewable clusters - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); - } - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int i = 0; i < pSize; ++i) - { - // Merge all those values with the global results - AncestorType::pResults[i].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][i]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - for (uint clusterIndex = 0; clusterIndex != state.area->renewable.clusterCount(); ++clusterIndex) - { - const auto* renewableCluster = state.area->renewable.clusters[clusterIndex]; - double renewableClusterProduction = renewableCluster->valueAtTimeStep(state.hourInTheYear, state.year); - - pValuesForTheCurrentYear[numSpace][renewableCluster->areaWideIndex].hour[state.hourInTheYear] - += renewableClusterProduction; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const - { - // Ask to build the digest to the next variable - NextType::buildDigest(results, digestLevel, dataLevel); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - inline uint64_t memoryUsage() const - { - uint64_t r = (sizeof(IntermediateValues) * pSize + IntermediateValues::MemoryUsage()) - * pNbYearsParallel; - r += sizeof(double) * pSize * maxHoursInAYear * pNbYearsParallel; - r += AncestorType::memoryUsage(); - return r; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& renewable = results.data.area->renewable; - // Write the data for the current year - for (uint i = 0; i < pSize; ++i) - { - // Write the data for the current year - results.variableCaption = renewable.clusters[i]->name(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t pSize; - unsigned int pNbYearsParallel; -}; // class ProductionByRenewablePlant - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_ProductionByRenewablePlant_H__ diff --git a/src/solver/variable/economy/profitByPlant.h b/src/solver/variable/economy/profitByPlant.h deleted file mode 100644 index 3438b8b387..0000000000 --- a/src/solver/variable/economy/profitByPlant.h +++ /dev/null @@ -1,335 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#pragma once - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardProfitByPlant -{ - //! Caption - static std::string Caption() - { - return "Profit by plant"; - } - //! Unit - static std::string Unit() - { - return "Profit - Euro"; - } - - //! The short description of the variable - static std::string Description() - { - return "Profit for thermal units"; - } - - //! The expected results - typedef Results> - ResultsType; - - //! The VCard to look for calculating spatial aggregates - typedef VCardProfitByPlant VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::de), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable - columnCount = Category::dynamicColumns, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesDeepType; - typedef IntermediateValues* IntermediateValuesBaseType; - typedef IntermediateValuesBaseType* IntermediateValuesType; -}; // class VCard - -/*! -** \brief C02 Average value of the overrall OperatingCost emissions expected from all -** the thermal dispatchable clusters -*/ -template -class ProfitByPlant : public Variable::IVariable, NextT, VCardProfitByPlant> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardProfitByPlant VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ProfitByPlant() : pValuesForTheCurrentYear(nullptr), pNbClustersOfArea(0) - { - } - - ~ProfitByPlant() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - delete[] pValuesForTheCurrentYear[numSpace]; - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - // Next - NextType::initializeFromStudy(study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Get the number of years in parallel - pNbYearsParallel = study->maxNbYearsInParallel; - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - - // Get the area - pNbClustersOfArea = area->thermal.clusterCount(); - if (pNbClustersOfArea) - { - AncestorType::pResults.resize(pNbClustersOfArea); - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] - = new VCardType::IntermediateValuesDeepType[pNbClustersOfArea]; - - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - for (unsigned int i = 0; i != pNbClustersOfArea; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); - - for (unsigned int i = 0; i != pNbClustersOfArea; ++i) - { - AncestorType::pResults[i].initializeFromStudy(*study); - AncestorType::pResults[i].reset(); - } - } - else - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace] = nullptr; - - AncestorType::pResults.clear(); - } - - // Next - NextType::initializeFromArea(study, area); - } - - size_t getMaxNumberColumns() const - { - return pNbClustersOfArea * ResultsType::count; - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != pNbClustersOfArea; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Merge all results for all thermal clusters - { - for (unsigned int i = 0; i < pNbClustersOfArea; ++i) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); - } - } - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - for (unsigned int i = 0; i < pNbClustersOfArea; ++i) - { - // Merge all those values with the global results - AncestorType::pResults[i].merge(numSpaceToYear[numSpace], - pValuesForTheCurrentYear[numSpace][i]); - } - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Useful local variables - auto area = state.area; - auto& thermal = state.thermal; - std::vector areaMarginalCosts = state.hourlyResults->CoutsMarginauxHoraires; - uint hourInTheWeek = state.hourInTheWeek; - uint hourInTheYear = state.hourInTheYear; - - for (uint clusterIndex = 0; clusterIndex != state.area->thermal.clusterCount(); - ++clusterIndex) - { - auto* cluster = state.area->thermal.clusters[clusterIndex]; - double hourlyClusterProduction - = thermal[area->index].thermalClustersProductions[clusterIndex]; - uint tsIndex = cluster->series->timeseriesNumbers[0][state.year]; - // Thermal cluster profit - pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex].hour[hourInTheYear] - = (hourlyClusterProduction - cluster->PthetaInf[hourInTheYear]) - * (-areaMarginalCosts[hourInTheWeek] - - cluster->getMarginalCost(tsIndex, hourInTheYear)); - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace]->hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - assert(NULL != results.data.area); - const auto& thermal = results.data.area->thermal; - - // Write the data for the current year - for (uint i = 0; i < pNbClustersOfArea; ++i) - { - // Write the data for the current year - results.variableCaption = thermal.clusters[i]->name(); // VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - size_t pNbClustersOfArea; - unsigned int pNbYearsParallel; - -}; // class - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares diff --git a/src/solver/variable/economy/pumping.h b/src/solver/variable/economy/pumping.h deleted file mode 100644 index eff385af2b..0000000000 --- a/src/solver/variable/economy/pumping.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_Pumping_H__ -#define __SOLVER_VARIABLE_ECONOMY_Pumping_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardPumping -{ - //! Caption - static std::string Caption() - { - return "H. PUMP"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydraulic pumping"; - } - - //! The expected results - typedef Results>>>> - ResultsType; - - //! The VCard to look for calculating spatial aggregates - typedef VCardPumping VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Reservoir level -*/ -template -class Pumping : public Variable::IVariable, NextT, VCardPumping> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardPumping VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~Pumping() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - pArea = area; - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - // Next - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily, weekly, monthly, annual). - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Retrieving the hourly pumping energy - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - = state.hourlyResults->PompageHoraire[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! The attached area - Antares::Data::Area* pArea; - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class Pumping - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_Pumping_H__ diff --git a/src/solver/variable/economy/renewableGeneration.h b/src/solver/variable/economy/renewableGeneration.h deleted file mode 100644 index 631a85c038..0000000000 --- a/src/solver/variable/economy/renewableGeneration.h +++ /dev/null @@ -1,326 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_RenewableGeneration_H__ -#define __SOLVER_VARIABLE_ECONOMY_RenewableGeneration_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardRenewableGeneration -{ - //! Caption - static std::string Caption() - { - return "Renewable Gen."; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Value of all the renewable generation throughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardRenewableGeneration VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 9, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType[columnCount]; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - - struct Multiple - { - static std::string Caption(const unsigned int indx) - { - switch (indx) - { - case 0: - return "WIND OFFSHORE"; - case 1: - return "WIND ONSHORE"; - case 2: - return "SOLAR CONCRT."; - case 3: - return "SOLAR PV"; - case 4: - return "SOLAR ROOFT"; - case 5: - return "RENW. 1"; - case 6: - return "RENW. 2"; - case 7: - return "RENW. 3"; - case 8: - return "RENW. 4"; - default: - return ""; - } - } - - static std::string Unit([[maybe_unused]] const unsigned int indx) - { - return VCardRenewableGeneration::Unit(); - } - }; -}; // class VCard - -/*! -** \brief Marginal RenewableGeneration -*/ -template -class RenewableGeneration - : public Variable::IVariable, NextT, VCardRenewableGeneration> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardRenewableGeneration VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~RenewableGeneration() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - { - results[i].initializeFromStudy(study); - results[i].reset(); - } - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - VariableAccessorType::template ComputeStatistics( - pValuesForTheCurrentYear[numSpace]); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - VariableAccessorType::ComputeSummary( - pValuesForTheCurrentYear[numSpace], AncestorType::pResults, numSpaceToYear[numSpace]); - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - for (uint clusterIndex = 0; clusterIndex != state.area->renewable.clusterCount(); - ++clusterIndex) - { - const auto* renewableCluster = state.area->renewable.clusters[clusterIndex]; - double renewableClusterProduction - = renewableCluster->valueAtTimeStep(state.hourInTheYear, state.year); - - pValuesForTheCurrentYear[numSpace][renewableCluster->groupID][state.hourInTheYear] - += renewableClusterProduction; - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // The current variable is actually a multiple-variable. - results.isCurrentVarNA = AncestorType::isNonApplicable; - - for (uint i = 0; i != VCardType::columnCount; ++i) - { - if (AncestorType::isPrinted[i]) - { - // Write the data for the current year - results.variableCaption = VCardType::Multiple::Caption(i); - results.variableUnit = VCardType::Multiple::Unit(i); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - results.isCurrentVarNA++; - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class RenewableGeneration - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_RenewableGeneration_H__ diff --git a/src/solver/variable/economy/reservoirlevel.h b/src/solver/variable/economy/reservoirlevel.h deleted file mode 100644 index a874f64f26..0000000000 --- a/src/solver/variable/economy/reservoirlevel.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_ReservoirLevel_H__ -#define __SOLVER_VARIABLE_ECONOMY_ReservoirLevel_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardReservoirLevel -{ - //! Caption - static std::string Caption() - { - return "H. LEV"; - } - //! Unit - static std::string Unit() - { - return "%"; - } - - //! The short description of the variable - static std::string Description() - { - return "Hydro Level"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardReservoirLevel VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable - isPossiblyNonApplicable = 1, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Reservoir level -*/ -template -class ReservoirLevel : public Variable::IVariable, NextT, VCardReservoirLevel> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardReservoirLevel VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~ReservoirLevel() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily, weekly, monthly, annual). - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Retrieving hourly reservoir levels of week simulation - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - = state.hourlyResults->niveauxHoraires[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class HydroLevel - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_ReservoirLevel_H__ diff --git a/src/solver/variable/economy/shortTermStorage.h b/src/solver/variable/economy/shortTermStorage.h deleted file mode 100644 index 959d4a49be..0000000000 --- a/src/solver/variable/economy/shortTermStorage.h +++ /dev/null @@ -1,296 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#pragma once - -#include "../variable.h" -#include "antares/study/parts/short-term-storage/STStorageOutputCaptions.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardShortTermStorage -{ - //! Caption - static std::string Caption() - { - return "ST storage"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Value of all short term storage throughout all MC years"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardShortTermStorage VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 27, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType[columnCount]; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - - struct Multiple - { - static std::string Caption(const unsigned int indx) - { - return Antares::Data::ShortTermStorage::getVariableCaptionFromColumnIndex(indx); - } - - static std::string Unit(const unsigned int indx) - { - if (indx % 3 == 2) // Level - return "MWh"; - else // Injection, withdrawal - return "MW"; - } - }; -}; // class VCard - -template -class ShortTermStorageByGroup - : public Variable::IVariable, NextT, VCardShortTermStorage> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardShortTermStorage VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~ShortTermStorageByGroup() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - { - results[i].initializeFromStudy(study); - results[i].reset(); - } - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Here we perform time-aggregations : - // --------------------------------- - // For a given MC year, from hourly results we compute daily, weekly, monthly and annual - // results by aggregation operations (averages or sums). - // Caution : - // - level results are stored in columns of which indices satisfy : col_index % 3 == 2. - // They are time-aggregated by means of averages - // - injection and withdrawal results are stored in columns of which indices - // satisfy : col_index % 3 != 2. - // They are time-aggregated by means of sums. - - for (unsigned int col_index = 0; col_index != VCardType::columnCount; ++col_index) - { - bool isAnInjectionColumn = (col_index % 3) == 0; - bool isAnWithdrawalColumn = (col_index % 3) == 1; - bool isALevelColumn = (col_index % 3) == 2; - - if (isALevelColumn) - pValuesForTheCurrentYear[numSpace][col_index].computeAveragesForCurrentYearFromHourlyResults(); - if (isAnInjectionColumn || isAnWithdrawalColumn) - pValuesForTheCurrentYear[numSpace][col_index].computeStatisticsForTheCurrentYear(); - } - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - // Here we compute synthesis : - // for each interval of any time period results (hourly, daily, weekly, ...), - // we compute the average over all MC years : - // For instance : - // - we compute the average of the results of the first hour over all MC years - // - or we compute the average of the results of the n-th day over all MC years - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[numSpace], - AncestorType::pResults, - numSpaceToYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - using namespace Antares::Data::ShortTermStorage; - for (uint stsIndex = 0; stsIndex < state.area->shortTermStorage.count(); stsIndex++) - { - const auto* cluster = state.area->shortTermStorage.storagesByIndex[stsIndex]; - const uint group = groupIndex(cluster->properties.group); - - // Injection - pValuesForTheCurrentYear[numSpace][3 * group][state.hourInTheYear] - += state.hourlyResults->ShortTermStorage[state.hourInTheWeek].injection[stsIndex]; - - // Withdrawal - pValuesForTheCurrentYear[numSpace][3 * group + 1][state.hourInTheYear] - += state.hourlyResults->ShortTermStorage[state.hourInTheWeek].withdrawal[stsIndex]; - - // Levels - pValuesForTheCurrentYear[numSpace][3 * group + 2][state.hourInTheYear] - += state.hourlyResults->ShortTermStorage[state.hourInTheWeek].level[stsIndex]; - } - - // Next item in the list - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // The current variable is actually a multiple-variable. - results.isCurrentVarNA = AncestorType::isNonApplicable; - - for (uint i = 0; i != VCardType::columnCount; ++i) - { - if (AncestorType::isPrinted[i]) - { - // Write the data for the current year - results.variableCaption = VCardType::Multiple::Caption(i); - results.variableUnit = VCardType::Multiple::Unit(i); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - results.isCurrentVarNA++; - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class ShortTermStorageByGroup - -} // namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/economy/spilledEnergy.h b/src/solver/variable/economy/spilledEnergy.h deleted file mode 100644 index ae40798a9c..0000000000 --- a/src/solver/variable/economy/spilledEnergy.h +++ /dev/null @@ -1,284 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_SpilledEnergy_H__ -#define __SOLVER_VARIABLE_ECONOMY_SpilledEnergy_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardSpilledEnergy -{ - //! Caption - static std::string Caption() - { - return "SPIL. ENRG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Spilled Energy (generation that cannot be satisfied)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSpilledEnergy VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall SpilledEnergy emissions expected from all -** the thermal dispatchable clusters -*/ -template -class SpilledEnergy : public Variable::IVariable, NextT, VCardSpilledEnergy> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSpilledEnergy VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~SpilledEnergy() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - assert(state.hourlyResults && "Invalid pointer to simplex results"); - - // Total SpilledEnergy emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class SpilledEnergy - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_SpilledEnergy_H__ diff --git a/src/solver/variable/economy/spilledEnergyAfterCSR.h b/src/solver/variable/economy/spilledEnergyAfterCSR.h deleted file mode 100644 index c36ae1aee5..0000000000 --- a/src/solver/variable/economy/spilledEnergyAfterCSR.h +++ /dev/null @@ -1,274 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ -#define __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ - -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardSpilledEnergyAfterCSR -{ - //! Caption - static std::string Caption() - { - return "SPIL. ENRG. CSR"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - //! The short description of the variable - static std::string Description() - { - return "Spilled Energy After CSR Optimization (generation that cannot be satisfied) " - "after CSR optimization"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardSpilledEnergyAfterCSR VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall SpilledEnergyAfterCSR emissions expected from all -** the thermal dispatchable clusters -*/ -template -class SpilledEnergyAfterCSR - : public Variable::IVariable, NextT, VCardSpilledEnergyAfterCSR> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardSpilledEnergyAfterCSR VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - - ~SpilledEnergyAfterCSR() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Total SpilledEnergyAfterCSR emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesSpilledEnergyAfterCSR[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class SpilledEnergyAfterCSR - -} // namespace Antares::Solver::Variable::Economy - -#endif // __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ diff --git a/src/solver/variable/economy/thermalAirPollutantEmissions.h b/src/solver/variable/economy/thermalAirPollutantEmissions.h deleted file mode 100644 index 1579dc64d0..0000000000 --- a/src/solver/variable/economy/thermalAirPollutantEmissions.h +++ /dev/null @@ -1,304 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_thermalAirPollutantEmissions_H__ -#define __SOLVER_VARIABLE_ECONOMY_thermalAirPollutantEmissions_H__ - -#include -#include "../variable.h" - -namespace Antares::Solver::Variable::Economy -{ -struct VCardThermalAirPollutantEmissions -{ - //! Caption not used: several columns - static std::string Caption() - { - return ""; - } - //! Unit - static std::string Unit() - { - return "Tons"; - } - - //! The short description of the variable - static std::string Description() - { - return "Overall pollutant emissions expected from all the thermal clusters"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardThermalAirPollutantEmissions VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = Antares::Data::Pollutant::POLLUTANT_MAX, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType[columnCount]; - typedef IntermediateValuesBaseType* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - - struct Multiple - { - static std::string Caption(const unsigned int indx) - { - if (indx < Antares::Data::Pollutant::POLLUTANT_MAX) - return Antares::Data::Pollutant::getPollutantName(indx).c_str(); - - return ""; - } - - static std::string Unit([[maybe_unused]] const unsigned int indx) - { - return VCardThermalAirPollutantEmissions::Unit(); - } - }; -}; // class VCard - -/*! -** \brief Marginal ThermalAirPollutantEmissions -*/ -template -class ThermalAirPollutantEmissions : public Variable::IVariable, - NextT, - VCardThermalAirPollutantEmissions> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardThermalAirPollutantEmissions VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~ThermalAirPollutantEmissions() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - { - results[i].initializeFromStudy(study); - results[i].reset(); - } - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - for (unsigned int i = 0; i != VCardType::columnCount; ++i) - pValuesForTheCurrentYear[numSpace][i].reset(); - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - VariableAccessorType::template ComputeStatistics( - pValuesForTheCurrentYear[numSpace]); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - VariableAccessorType::ComputeSummary( - pValuesForTheCurrentYear[numSpace], AncestorType::pResults, numSpaceToYear[numSpace]); - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - auto area = state.area; - auto& thermal = state.thermal; - for (uint clusterIndex = 0; clusterIndex != area->thermal.clusterCount(); ++clusterIndex) - { - auto* thermalCluster = area->thermal.clusters[clusterIndex]; - - // Multiply every pollutant factor with production - for (int i = 0; i < Antares::Data::Pollutant::POLLUTANT_MAX; i++) - { - pValuesForTheCurrentYear[numSpace][i][state.hourInTheYear] - += thermalCluster->emissions.factors[i] - * thermal[state.area->index].thermalClustersProductions[clusterIndex]; - } - } - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int column, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace][column].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // The current variable is actually a multiple-variable. - results.isCurrentVarNA = AncestorType::isNonApplicable; - - for (uint i = 0; i != VCardType::columnCount; ++i) - { - if (AncestorType::isPrinted[i]) - { - // Write the data for the current year - results.variableCaption = VCardType::Multiple::Caption(i); - results.variableUnit = VCardType::Multiple::Unit(i); - pValuesForTheCurrentYear[numSpace][i].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - results.isCurrentVarNA++; - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class ThermalAirPollutantEmissions - -} // namespace Antares::Solver::Variable::Economy - -#endif // __SOLVER_VARIABLE_ECONOMY_thermalAirPollutantEmissions_H__ diff --git a/src/solver/variable/economy/unsupliedEnergy.h b/src/solver/variable/economy/unsupliedEnergy.h deleted file mode 100644 index 040cd90799..0000000000 --- a/src/solver/variable/economy/unsupliedEnergy.h +++ /dev/null @@ -1,284 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ -#define __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardUnsupliedEnergy -{ - //! Caption - static std::string Caption() - { - return "UNSP. ENRG"; - } - //! Unit - static std::string Unit() - { - return "MWh"; - } - //! The short description of the variable - static std::string Description() - { - return "Unsuplied Energy (demand that cannot be satisfied)"; - } - - //! The expecte results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardUnsupliedEnergy VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::spatialAggregateSum, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 0, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief C02 Average value of the overrall UnsupliedEnergy emissions expected from all -** the thermal dispatchable clusters -*/ -template -class UnsupliedEnergy - : public Variable::IVariable, NextT, VCardUnsupliedEnergy> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardUnsupliedEnergy VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~UnsupliedEnergy() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - // Intermediate values - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily,weekly,monthly) - pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Total UnsupliedEnergy emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = - // Current Hydro Storage generation - state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class UnsupliedEnergy - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ diff --git a/src/solver/variable/economy/waterValue.h b/src/solver/variable/economy/waterValue.h deleted file mode 100644 index 4749477cce..0000000000 --- a/src/solver/variable/economy/waterValue.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_ECONOMY_WaterValue_H__ -#define __SOLVER_VARIABLE_ECONOMY_WaterValue_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardWaterValue -{ - //! Caption - static std::string Caption() - { - return "H. VAL"; - } - //! Unit - static std::string Unit() - { - return "Euro/MWh"; - } - - //! The short description of the variable - static std::string Description() - { - return "Water value"; - } - - //! The expected results - typedef Results>>>> - ResultsType; - - //! The VCard to look for for calculating spatial aggregates - typedef VCardWaterValue VCardForSpatialAggregate; - - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 2, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 1, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = 1, - }; - - typedef IntermediateValues IntermediateValuesBaseType; - typedef IntermediateValues* IntermediateValuesType; - - typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; - -}; // class VCard - -/*! -** \brief Water values -*/ -template -class WaterValue : public Variable::IVariable, NextT, VCardWaterValue> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardWaterValue VCardType; - //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; - - //! List of expected results - typedef typename VCardType::ResultsType ResultsType; - - typedef VariableAccessor VariableAccessorType; - - enum - { - //! How many items have we got - count = 1 + NextT::count, - }; - - template - struct Statistics - { - enum - { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), - }; - }; - -public: - ~WaterValue() - { - delete[] pValuesForTheCurrentYear; - } - - void initializeFromStudy(Data::Study& study) - { - pNbYearsParallel = study.maxNbYearsInParallel; - - InitializeResultsFromStudy(AncestorType::pResults, study); - - pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); - - // Next - NextType::initializeFromStudy(study); - } - - template - static void InitializeResultsFromStudy(R& results, Data::Study& study) - { - VariableAccessorType::InitializeAndReset(results, study); - } - - void initializeFromArea(Data::Study* study, Data::Area* area) - { - // Next - NextType::initializeFromArea(study, area); - } - - void initializeFromLink(Data::Study* study, Data::AreaLink* link) - { - // Next - NextType::initializeFromAreaLink(study, link); - } - - void simulationBegin() - { - for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) - pValuesForTheCurrentYear[numSpace].reset(); - // Next - NextType::simulationBegin(); - } - - void simulationEnd() - { - NextType::simulationEnd(); - } - - void yearBegin(unsigned int year, unsigned int numSpace) - { - // Reset the values for the current year - pValuesForTheCurrentYear[numSpace].reset(); - - // Next variable - NextType::yearBegin(year, numSpace); - } - - void yearEndBuild(State& state, unsigned int year) - { - // Next variable - NextType::yearEndBuild(state, year); - } - - void yearEnd(unsigned int year, unsigned int numSpace) - { - // Compute all statistics for the current year (daily, weekly, monthly, annual). - pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); - - // Next variable - NextType::yearEnd(year, numSpace); - } - - void computeSummary(std::map& numSpaceToYear, - unsigned int nbYearsForCurrentSummary) - { - for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) - { - // Merge all those values with the global results - AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, - pValuesForTheCurrentYear[numSpace]); - } - - // Next variable - NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - } - - void hourBegin(unsigned int hourInTheYear) - { - // Next variable - NextType::hourBegin(hourInTheYear); - } - - void hourForEachArea(State& state, unsigned int numSpace) - { - // Retrieving hourly water values of week simulation - pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] - = state.hourlyResults->valeurH2oHoraire[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( - unsigned int, - unsigned int numSpace) const - { - return pValuesForTheCurrentYear[numSpace].hour; - } - - void localBuildAnnualSurveyReport(SurveyResults& results, - int fileLevel, - int precision, - unsigned int numSpace) const - { - // Initializing external pointer on current variable non applicable status - results.isCurrentVarNA = AncestorType::isNonApplicable; - - if (AncestorType::isPrinted[0]) - { - // Write the data for the current year - results.variableCaption = VCardType::Caption(); - results.variableUnit = VCardType::Unit(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class WaterValue - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_WaterValue_H__ diff --git a/src/solver/variable/include/antares/solver/variable/adequacy/all.h b/src/solver/variable/include/antares/solver/variable/adequacy/all.h new file mode 100644 index 0000000000..b02c210476 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/adequacy/all.h @@ -0,0 +1,227 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ADEQUACY_ALL_H__ +#define __SOLVER_VARIABLE_ADEQUACY_ALL_H__ + +#include "antares/solver/variable/adequacy/links.h" +#include "antares/solver/variable/adequacy/overallCost.h" +#include "antares/solver/variable/adequacy/spilledEnergy.h" +#include "antares/solver/variable/area.h" +#include "antares/solver/variable/bindConstraints.h" +#include "antares/solver/variable/commons/hydro.h" +#include "antares/solver/variable/commons/join.h" +#include "antares/solver/variable/commons/load.h" +#include "antares/solver/variable/commons/miscGenMinusRowPSP.h" +#include "antares/solver/variable/commons/psp.h" +#include "antares/solver/variable/commons/rowBalance.h" +#include "antares/solver/variable/commons/solar.h" +#include "antares/solver/variable/commons/spatial-aggregate.h" +#include "antares/solver/variable/commons/wind.h" +#include "antares/solver/variable/economy/STSbyGroup.h" +#include "antares/solver/variable/economy/STStorageInjectionByCluster.h" +#include "antares/solver/variable/economy/STStorageLevelsByCluster.h" +#include "antares/solver/variable/economy/STStorageWithdrawalByCluster.h" +#include "antares/solver/variable/economy/avail-dispatchable-generation.h" +#include "antares/solver/variable/economy/balance.h" +#include "antares/solver/variable/economy/dispatchable-generation-margin.h" +#include "antares/solver/variable/economy/dispatchableGeneration.h" +#include "antares/solver/variable/economy/hydroCost.h" +#include "antares/solver/variable/economy/hydrostorage.h" +#include "antares/solver/variable/economy/inflow.h" +#include "antares/solver/variable/economy/lold.h" +#include "antares/solver/variable/economy/lolp.h" +#include "antares/solver/variable/economy/max-mrg.h" +#include "antares/solver/variable/economy/operatingCost.h" +#include "antares/solver/variable/economy/overflow.h" +#include "antares/solver/variable/economy/price.h" +#include "antares/solver/variable/economy/productionByDispatchablePlant.h" +#include "antares/solver/variable/economy/productionByRenewablePlant.h" +#include "antares/solver/variable/economy/pumping.h" +#include "antares/solver/variable/economy/renewableGeneration.h" +#include "antares/solver/variable/economy/reservoirlevel.h" +#include "antares/solver/variable/economy/thermalAirPollutantEmissions.h" +#include "antares/solver/variable/economy/unsupliedEnergy.h" +#include "antares/solver/variable/economy/waterValue.h" +#include "antares/solver/variable/setofareas.h" +#include "antares/solver/variable/variable.h" + +// Output variables associated to binding constraints +#include "antares/solver/variable//economy/bindingConstraints/bindingConstraintsMarginalCost.h" + +// By thermal plant +#include "../economy/profitByPlant.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Adequacy +{ +/*! +** \brief All variables for a single area (economy) +*/ +typedef // Prices + Variable::Adequacy::OverallCost // Overall Cost (Op. Cost + Unsupplied Eng.) + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + VariablesPerArea; + +/*! +** \brief All variables for a single set of areas (economy) +*/ +typedef // Prices + Common::SpatialAggregate< + Variable::Adequacy::OverallCost, + Common::SpatialAggregate< + Variable::Economy::OperatingCost, + Common::SpatialAggregate< + Variable::Economy::Price, + // pollutant + Common::SpatialAggregate< + Variable::Economy::ThermalAirPollutantEmissions, + // Production by thermal cluster + Common::SpatialAggregate< + Variable::Economy::Balance, + // Misc Gen. + Common::SpatialAggregate< + Variable::Economy::RowBalance, + Common::SpatialAggregate< + Variable::Economy::PSP, + Common::SpatialAggregate< + Variable::Economy::MiscGenMinusRowPSP, + // Time series + Common::SpatialAggregate< + Variable::Economy::TimeSeriesValuesLoad, + Common::SpatialAggregate< + Variable::Economy::TimeSeriesValuesHydro, + Common::SpatialAggregate< + Variable::Economy::TimeSeriesValuesWind, + Common::SpatialAggregate< + Variable::Economy::TimeSeriesValuesSolar, + // Other + Common::SpatialAggregate< + Variable::Economy::DispatchableGeneration, + Common::SpatialAggregate< + Variable::Economy::RenewableGeneration, + Common::SpatialAggregate< + Variable::Economy::HydroStorage, + Common::SpatialAggregate< + Variable::Economy::Pumping, + Common::SpatialAggregate< + Variable::Economy::ReservoirLevel, + Common::SpatialAggregate< + Variable::Economy::Inflows, + Common::SpatialAggregate< + Variable::Economy::Overflows, + Common::SpatialAggregate< + Variable::Economy::WaterValue, + Common::SpatialAggregate< + Variable::Economy::HydroCost, + Common::SpatialAggregate< + Variable::Economy::UnsupliedEnergy, + Common::SpatialAggregate< + Variable::Adequacy::SpilledEnergy, + // LOLD + Common::SpatialAggregate< + Variable::Economy::LOLD, + Common::SpatialAggregate< + Variable::Economy::LOLP, + + Common::SpatialAggregate< + Variable::Economy::AvailableDispatchGen, + Common::SpatialAggregate< + Variable::Economy::DispatchableGenMargin, + Common::SpatialAggregate< + Variable::Economy:: + Marge>>>>>>>>>>>>>>>>>>>>>>>>>>>> + VariablesPerSetOfAreas; + +typedef Variable::Economy::BindingConstMarginCost< // Marginal cost for a binding constraint + Container::EndOfList // End of variable list + > + + VariablesPerBindingConstraints; + +typedef Variable::Join< + // Variables for each area / links attached to the areas + Variable::Areas, + // Variables for each set of areas + Variable::Join, + // Variables for each binding constraint + Variable::BindingConstraints>> + ItemList; + +/*! +** \brief All variables for a simulation (economy) +*/ +typedef Container::List AllVariables; + +} // namespace Adequacy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ADEQUACY_ALL_H__ diff --git a/src/solver/variable/include/antares/solver/variable/adequacy/links.h b/src/solver/variable/include/antares/solver/variable/adequacy/links.h new file mode 100644 index 0000000000..c4bf3c313b --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/adequacy/links.h @@ -0,0 +1,58 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_VARIABLE_ADEQUACY_LINK_H__ +#define __SOLVER_VARIABLE_ADEQUACY_LINK_H__ + +#include + +// TODO SL: should be moved to common +#include "antares/solver/variable//commons/links/links.h" +#include "antares/solver/variable/economy/links/congestionFee.h" +#include "antares/solver/variable/economy/links/congestionFeeAbs.h" +#include "antares/solver/variable/economy/links/congestionProbability.h" +#include "antares/solver/variable/economy/links/flowLinear.h" +#include "antares/solver/variable/economy/links/flowLinearAbs.h" +#include "antares/solver/variable/economy/links/flowQuad.h" +#include "antares/solver/variable/economy/links/hurdleCosts.h" +#include "antares/solver/variable/economy/links/marginalCost.h" + +namespace Antares::Solver::Variable::Adequacy +{ +/*! +** \brief All variables for a single link. +* +* # +*/ +using VariablePerLink = Economy::FlowLinear // Flow linear + >>>>>>>; + +using Links = Antares::Solver::Variable::Links; + +} // namespace Antares::Solver::Variable::Adequacy + +#endif // __SOLVER_VARIABLE_ADEQUACY_LINK_H__ diff --git a/src/solver/variable/include/antares/solver/variable/adequacy/overallCost.h b/src/solver/variable/include/antares/solver/variable/adequacy/overallCost.h new file mode 100644 index 0000000000..f730a3d865 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/adequacy/overallCost.h @@ -0,0 +1,310 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ADEQUACY_OverallCost_H__ +#define __SOLVER_VARIABLE_ADEQUACY_OverallCost_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Adequacy +{ +struct VCardOverallCost +{ + //! Caption + static std::string Caption() + { + return "OV. COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Overall Cost throughout all MC years"; + } + + //! The expecte results + typedef Results, + R::AllYears::Average // Use these values for spatial cluster + > + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardOverallCost VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OverallCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class OverallCost: public Variable::IVariable, NextT, VCardOverallCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardOverallCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~OverallCost() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = 0; i < state.study.runtime->rangeLimits.hour[Data::rangeCount]; ++i) + { + pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterOperatingCostForYear[i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + auto area = state.area; + auto& thermal = state.thermal; + // Total UnsupliedEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] += + // Current Hydro Storage generation + (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] + * area->thermal.unsuppliedEnergyCost) + + ((state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek] + + state.resSpilled.entry[area->index][state.hourInTheWeek]) + * area->thermal.spilledEnergyCost); + + // Hydro costs : water value and pumping + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + += state.problemeHebdo->CaracteristiquesHydrauliques[state.area->index] + .WeeklyWaterValueStateRegular + * (state.hourlyResults->TurbinageHoraire[state.hourInTheWeek] + - area->hydro.pumpingEfficiency + * state.hourlyResults->PompageHoraire[state.hourInTheWeek]); + + // Thermal costs + for (auto& cluster: area->thermal.list.each_enabled()) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + += thermal[area->index].thermalClustersOperatingCost[cluster->areaWideIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; +}; // class OverallCost + +} // namespace Adequacy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ADEQUACY_OverallCost_H__ diff --git a/src/solver/variable/include/antares/solver/variable/adequacy/spilledEnergy.h b/src/solver/variable/include/antares/solver/variable/adequacy/spilledEnergy.h new file mode 100644 index 0000000000..7d447e1697 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/adequacy/spilledEnergy.h @@ -0,0 +1,283 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ADEQUACY_SpilledEnergy_H__ +#define __SOLVER_VARIABLE_ADEQUACY_SpilledEnergy_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Adequacy +{ +struct VCardSpilledEnergy +{ + //! Caption + static std::string Caption() + { + return "SPIL. ENRG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Spilled Energy (generation that cannot be satisfied)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSpilledEnergy VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall SpilledEnergy emissions expected from all +** the thermal dispatchable clusters +*/ +template +class SpilledEnergy: public Variable::IVariable, NextT, VCardSpilledEnergy> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSpilledEnergy VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~SpilledEnergy() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + assert(state.hourlyResults && "Invalid pointer to simplex results"); + + // Total SpilledEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = +state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek] + + state.resSpilled.entry[state.area->index][state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class SpilledEnergy + +} // namespace Adequacy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ADEQUACY_SpilledEnergy_H__ diff --git a/src/solver/variable/include/antares/solver/variable/area.h b/src/solver/variable/include/antares/solver/variable/area.h new file mode 100644 index 0000000000..9328c27ba8 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/area.h @@ -0,0 +1,224 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_AREA_H__ +#define __SOLVER_VARIABLE_AREA_H__ + +#include "state.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +struct VCardAllAreas +{ + //! Caption + static std::string Caption() + { + return "Areas"; + } + + //! Unit + static std::string Unit() + { + return ""; + } + + //! The short description of the variable + static std::string Description() + { + return ""; + } + + //! The expecte results + typedef Results<> ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & Category::FileLevel::de; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +1; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 0; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 0; + +}; // class VCard + +template +class Areas //: public Variable::IVariable, NextT, VCardAllAreas> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardAllAreas VCardType; + //! Ancestor + // typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + enum + { + //! How many items have we got + count = NextT::count, + }; + + template + struct Statistics + { + enum + { + count = NextType::template Statistics < CDataLevel, + CFile > ::count + }; + }; + +public: + /*! + ** \brief Retrieve the list of all individual variables + ** + ** The predicate must implement the method `add(name, unit, comment)`. + */ + template + static void RetrieveVariableList(PredicateT& predicate); + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + Areas(); + //! Destructor + ~Areas(); + //@} + + void initializeFromStudy(Data::Study& study); + void initializeFromArea(Data::Study*, Data::Area*); + void initializeFromThermalCluster(Data::Study*, Data::Area*, Data::ThermalCluster*); + void initializeFromAreaLink(Data::Study*, Data::AreaLink*); + + void simulationBegin(); + void simulationEnd(); + + void yearBegin(uint year, uint numSpace); + // void yearEndBuildPrepareDataForEachThermalCluster(State& state, uint year); + // void yearEndBuildForEachThermalCluster(State& state, uint year); + + void yearEndBuild(State& state, uint year, uint numSpace); + + void yearEnd(uint year, uint numSpace); + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary); + + void hourBegin(uint hourInTheYear); + + void hourForEachArea(State& state, uint numSpace); + void hourForEachLink(State& state, uint numSpace); + + void hourEnd(State& state, uint hourInTheYear); + + void weekBegin(State& state); + void weekForEachArea(State& state, uint numSpace); + void weekEnd(State& state); + + void buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const; + + void buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + uint numSpace) const; + + void buildDigest(SurveyResults&, int digestLevel, int dataLevel) const; + + void beforeYearByYearExport(uint year, uint numSpace); + + uint64_t memoryUsage() const; + + template + static void provideInformations(I& infos); + + template + void yearEndSpatialAggregates(V&, uint, uint) + { + // do nothing + } + + template + void computeSpatialAggregatesSummary(V&, std::map&, unsigned int) + { + // do nothing + } + + template + void simulationEndSpatialAggregates(V&) + { + // do nothing + } + + template + void computeSpatialAggregateWith(O& out); + + template + void computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace); + + template + const double* retrieveHourlyResultsForCurrentYear() const; + + template + void retrieveResultsForArea(typename Storage::ResultsType** result, + const Data::Area* area); + + template + void retrieveResultsForThermalCluster(typename Storage::ResultsType** result, + const Data::ThermalCluster* cluster); + + template + void retrieveResultsForLink(typename Storage::ResultsType** result, + const Data::AreaLink* link); + +private: + //! Area list + NextType* pAreas; + //! The number of areas + uint pAreaCount; + +}; // class Areas + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#include "area.hxx" + +#endif // __SOLVER_VARIABLE_AREA_H__ diff --git a/src/solver/variable/include/antares/solver/variable/area.hxx b/src/solver/variable/include/antares/solver/variable/area.hxx new file mode 100644 index 0000000000..d3b34bb973 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/area.hxx @@ -0,0 +1,558 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_AREA_HXX__ +#define __SOLVER_VARIABLE_AREA_HXX__ + +#include +#include "antares/solver/variable/economy/dispatchable-generation-margin.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +template +inline Areas::Areas() +{ + // Do nothing +} + +template +inline void Areas::initializeFromArea(Data::Study*, Data::Area*) +{ + // Nothing to do here + // This method is called by initializeFromStudy() to all children +} + +template +inline void Areas::initializeFromAreaLink(Data::Study*, Data::AreaLink*) +{ + // Nothing to do here +} + +template +inline void Areas::initializeFromThermalCluster(Data::Study*, + Data::Area*, + Data::ThermalCluster*) +{ + // This method should not be called at this point +} + +template +void Areas::buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const +{ + int count_int = count; + bool linkDataLevel = dataLevel & Category::DataLevel::link; + bool areaDataLevel = dataLevel & Category::DataLevel::area; + bool thermalAggregateDataLevel = dataLevel & Category::DataLevel::thermalAggregate; + if (count_int && (linkDataLevel || areaDataLevel || thermalAggregateDataLevel)) + { + assert(results.data.area != NULL + && "The area must not be null to generate a survey report"); + + // Build the survey results for the given area + auto& area = *results.data.area; + + // Filtering + if (0 == (dataLevel & Category::DataLevel::link)) // filter on all but links + { + switch (precision) + { + case Category::hourly: + if (not(area.filterSynthesis & Data::filterHourly)) + { + return; + } + break; + case Category::daily: + if (not(area.filterSynthesis & Data::filterDaily)) + { + return; + } + break; + case Category::weekly: + if (not(area.filterSynthesis & Data::filterWeekly)) + { + return; + } + break; + case Category::monthly: + if (not(area.filterSynthesis & Data::filterMonthly)) + { + return; + } + break; + case Category::annual: + if (not(area.filterSynthesis & Data::filterAnnual)) + { + return; + } + break; + case Category::all: + break; + } + } + pAreas[area.index].buildSurveyReport(results, dataLevel, fileLevel, precision); + } +} + +template +void Areas::buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + uint numSpace) const +{ + int count_int = count; + bool linkDataLevel = dataLevel & Category::DataLevel::link; + bool areaDataLevel = dataLevel & Category::DataLevel::area; + bool thermalAggregateDataLevel = dataLevel & Category::DataLevel::thermalAggregate; + if (count_int && (linkDataLevel || areaDataLevel || thermalAggregateDataLevel)) + { + assert(results.data.area != NULL + && "The area must not be null to generate a survey report"); + + auto& area = *results.data.area; + + // Filtering + if (0 == (dataLevel & Category::DataLevel::link)) // filter on all but links + { + switch (precision) + { + case Category::hourly: + if (!(area.filterYearByYear & Data::filterHourly)) + { + return; + } + break; + case Category::daily: + if (!(area.filterYearByYear & Data::filterDaily)) + { + return; + } + break; + case Category::weekly: + if (!(area.filterYearByYear & Data::filterWeekly)) + { + return; + } + break; + case Category::monthly: + if (!(area.filterYearByYear & Data::filterMonthly)) + { + return; + } + break; + case Category::annual: + if (!(area.filterYearByYear & Data::filterAnnual)) + { + return; + } + break; + case Category::all: + break; + } + } + + // Build the survey results for the given area + pAreas[area.index].buildAnnualSurveyReport(results, + dataLevel, + fileLevel, + precision, + numSpace); + } +} + +template +void Areas::buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const +{ + int count_int = count; + if (count_int) + { + if (dataLevel & Category::DataLevel::area) + { + assert(pAreaCount == results.data.study.areas.size()); + + // Reset captions + results.data.rowCaptions.clear(); + results.data.rowCaptions.resize(pAreaCount); + + // For each area + // for (uint i = 0; i != results.data.study.areas.byIndex.size(); ++i) + for (uint i = 0; i != pAreaCount; ++i) + { + results.data.area = results.data.study.areas[i]; + uint index = results.data.area->index; + results.data.rowIndex = index; + results.data.rowCaptions[index] = results.data.area->id; + results.data.columnIndex = 0; + results.resetValuesAtLine(i); + pAreas[i].buildDigest(results, digestLevel, dataLevel); + } + } + } +} + +template +template +inline void Areas::RetrieveVariableList(PredicateT& predicate) +{ + NextType::RetrieveVariableList(predicate); +} + +template +template +inline void Areas::provideInformations(I& infos) +{ + // Begining of the node + if (VCardType::nodeDepthForGUI) + { + infos.template beginNode(); + // Next variable in the list + NextType::template provideInformations(infos); + // End of the node + infos.endNode(); + } + else + { + // Giving our VCard + infos.template addVCard(); + // Next variable in the list + NextType::template provideInformations(infos); + } +} + +template +template +inline void Areas::computeSpatialAggregateWith(O&) +{ + // Do nothing +} + +template +template +inline void Areas::computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace) +{ + assert(NULL != area); + pAreas[area->index].template computeSpatialAggregateWith(out, numSpace); +} + +template +template +const double* Areas::retrieveHourlyResultsForCurrentYear() const +{ + return nullptr; +} + +template +template +inline void Areas::retrieveResultsForArea( + typename Storage::ResultsType** result, + const Data::Area* area) +{ + pAreas[area->index].template retrieveResultsForArea(result, area); +} + +template +template +inline void Areas::retrieveResultsForThermalCluster( + typename Storage::ResultsType** result, + const Data::ThermalCluster* cluster) +{ + pAreas[cluster->parentArea->index] + .template retrieveResultsForThermalCluster(result, cluster); +} + +template +template +inline void Areas::retrieveResultsForLink( + typename Storage::ResultsType** result, + const Data::AreaLink* link) +{ + pAreas[link->from->index].template retrieveResultsForLink(result, link); +} + +template +Areas::~Areas() +{ + // Releasing the memory occupied by the areas + delete[] pAreas; +} + +template +void Areas::initializeFromStudy(Data::Study& study) +{ + // The total number of areas + pAreaCount = study.areas.size(); + + // Reserving the memory + pAreas = new NextType[pAreaCount]; + + // For each area... + uint tick = 6; + uint oldPercent = 0; + for (uint i = 0; i != pAreaCount; ++i) + { + // Instancing a new set of variables of the area + auto* currentArea = study.areas.byIndex[i]; + if (!(--tick)) + { + uint newPercent = ((i * 100u) / pAreaCount); + if (newPercent != oldPercent) + { + logs.info() << "Allocating resources " << ((i * 100u) / pAreaCount) << "%"; + oldPercent = newPercent; + } + // Reset the tick + tick = 6; + } + + // Initialize the variables + // From the study + pAreas[i].initializeFromStudy(study); + // From the area + pAreas[i].initializeFromArea(&study, currentArea); + // Does current output variable appears non applicable in areas' output files, not + // districts'. Note that digest gather area and district results. + pAreas[i].broadcastNonApplicability(not currentArea->hydro.reservoirManagement); + + // For each current area's variable, getting the print status, that is : + // is variable's column(s) printed in output (areas) reports ? + pAreas[i].getPrintStatusFromStudy(study); + + pAreas[i].supplyMaxNumberOfColumns(study); + } +} + +template +void Areas::simulationBegin() +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].simulationBegin(); + } +} + +template +void Areas::simulationEnd() +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].simulationEnd(); + } +} + +template +void Areas::hourForEachArea(State& state, uint numSpace) +{ + // For each area... + state.study.areas.each( + [this, &state, &numSpace](Data::Area& area) + { + state.area = &area; // the current area + + // Initializing the state for the current area + state.initFromAreaIndex(area.index, numSpace); + + for (const auto& cluster: area.thermal.list.each_enabled()) + { + // Intiializing the state for the current thermal cluster + state.initFromThermalClusterIndex(cluster->areaWideIndex); + } + + // Variables + auto& variablesForArea = pAreas[area.index]; + variablesForArea.hourForEachArea(state, numSpace); + + // All links + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + state.link = i->second; + // Variables + variablesForArea.hourForEachLink(state, numSpace); + } + }); // for each area +} + +template +void Areas::weekForEachArea(State& state, uint numSpace) +{ + // For each area... + state.study.areas.each( + [this, &state, &numSpace](Data::Area& area) + { + state.area = &area; // the current area + + // Initializing the state for the current area + state.initFromAreaIndex(area.index, numSpace); + + auto& variablesForArea = pAreas[area.index]; + + // DTG MRG + state.dispatchableMargin = variablesForArea.template retrieveHourlyResultsForCurrentYear< + Economy::VCardDispatchableGenMargin>(numSpace); + + variablesForArea.weekForEachArea(state, numSpace); + + // NOTE + // currently, the event is not broadcasted to thermal + // clusters and links + }); // for each area +} + +template +void Areas::yearBegin(uint year, uint numSpace) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].yearBegin(year, numSpace); + } +} + +template +void Areas::yearEndBuild(State& state, uint year, uint numSpace) +{ + // For each area... + state.study.areas.each( + [this, &state, &year, &numSpace](Data::Area& area) + { + state.area = &area; // the current area + + // Initializing the state for the current area + state.initFromAreaIndex(area.index, numSpace); + + // Variables + auto& variablesForArea = pAreas[area.index]; + + for (const auto& cluster: area.thermal.list.each_enabled()) + { + state.thermalCluster = cluster.get(); + state.yearEndResetThermal(); + + // Variables + variablesForArea.yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); + + // Building the end of year + state.yearEndBuildFromThermalClusterIndex(cluster->areaWideIndex); + + // Variables + variablesForArea.yearEndBuildForEachThermalCluster(state, year, numSpace); + } // for each thermal cluster + }); // for each area +} + +template +void Areas::yearEnd(uint year, uint numSpace) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + // Broadcast to all areas + pAreas[i].yearEnd(year, numSpace); + } +} + +template +void Areas::computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + // Broadcast to all areas + pAreas[i].computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } +} + +template +void Areas::weekBegin(State& state) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].weekBegin(state); + } +} + +template +void Areas::weekEnd(State& state) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].weekEnd(state); + } +} + +template +void Areas::hourBegin(uint hourInTheYear) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].hourBegin(hourInTheYear); + } +} + +template +void Areas::hourForEachLink(State& state, uint numSpace) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].hourForEachLink(state, numSpace); + } +} + +template +void Areas::hourEnd(State& state, uint hourInTheYear) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].hourEnd(state, hourInTheYear); + } +} + +template +void Areas::beforeYearByYearExport(uint year, uint numSpace) +{ + for (uint i = 0; i != pAreaCount; ++i) + { + pAreas[i].beforeYearByYearExport(year, numSpace); + } +} + +template +uint64_t Areas::memoryUsage() const +{ + uint64_t result = 0; + for (unsigned int i = 0; i != pAreaCount; ++i) + { + result += sizeof(NextType) + sizeof(void*); // overhead vector + result += pAreas[i].memoryUsage(); + } + return result; +} + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_AREA_HXX__ diff --git a/src/solver/variable/include/antares/solver/variable/bindConstraints.h b/src/solver/variable/include/antares/solver/variable/bindConstraints.h new file mode 100644 index 0000000000..b10d7e9186 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/bindConstraints.h @@ -0,0 +1,202 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "state.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +struct VCardAllBindingConstraints +{ + //! Caption + static std::string Caption() + { + return "Binding constraints"; + } + + //! Unit + static std::string Unit() + { + return ""; + } + + //! The short description of the variable + static std::string Description() + { + return ""; + } + + //! The expecte results + typedef Results<> ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::bindingConstraint; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & Category::FileLevel::bc; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +1; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 0; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 0; + +}; // class VCardAllBindingConstraints + +template +class BindingConstraints +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardAllBindingConstraints VCardType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + enum + { + //! How many items have we got + count = NextT::count, + }; + + template + struct Statistics + { + enum + { + count = NextType::template Statistics < CDataLevel, + CFile > ::count + }; + }; + +public: + /*! + ** \brief Retrieve the list of all individual variables + ** + ** The predicate must implement the method `add(name, unit, comment)`. + */ + template + static void RetrieveVariableList(PredicateT& predicate); + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + BindingConstraints() = default; + + BindingConstraints(BindingConstraints& other) = delete; + BindingConstraints(BindingConstraints&& other) = delete; + const BindingConstraints& operator=(BindingConstraints&& other) = delete; + + //! Destructor + ~BindingConstraints() = default; + //@} + + void initializeFromStudy(Data::Study& study); + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary); + + void simulationBegin(); + void simulationEnd(); + + void yearBegin(uint year, uint numSpace); + void yearEnd(uint year, uint numSpace); + + void yearEndBuild(State& state, uint year, uint numSpace); + + void weekBegin(State& state); + void weekEnd(State& state); + void weekForEachArea(State&, unsigned int numSpace); + void hourForEachArea(State&, unsigned int numSpace); + + void hourBegin(uint hourInTheYear); + void hourEnd(State& state, uint hourInTheYear); + + void buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const; + + void buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + uint numSpace) const; + + uint64_t memoryUsage() const; + + template + void yearEndSpatialAggregates(V&, uint, uint) + { + // do nothing + } + + template + static void provideInformations(I& infos); + + template + void retrieveResultsForArea(typename Storage::ResultsType** result, + const Data::Area* area); + void buildDigest(SurveyResults&, int digestLevel, int dataLevel) const; + + template + void simulationEndSpatialAggregates(V& allVars); + + template + void retrieveResultsForLink(typename Storage::ResultsType** result, + const Data::AreaLink* link); + + template + void retrieveResultsForThermalCluster(typename Storage::ResultsType** result, + const Data::ThermalCluster* cluster); + template + void computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace); + template + void computeSpatialAggregatesSummary(V& allVars, + std::map& numSpaceToYear, + unsigned int); + + void beforeYearByYearExport(uint year, uint numSpace); + +private: + // For each binding constraint, output variable static list associated. + std::vector pBindConstraints; + // The number of counted binding constraints + uint pBCcount; + +}; // class Areas + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#include "bindConstraints.hxx" diff --git a/src/solver/variable/include/antares/solver/variable/bindConstraints.hxx b/src/solver/variable/include/antares/solver/variable/bindConstraints.hxx new file mode 100644 index 0000000000..63738c4f5c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/bindConstraints.hxx @@ -0,0 +1,341 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include + +#include "antares/study/binding_constraint/BindingConstraint.h" +#include "antares/study/fwd.h" + +#include "bindConstraints.h" + +namespace Antares::Solver::Variable +{ +template +void BindingConstraints::buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const +{ + if (bool bcDataLevel = dataLevel & Category::DataLevel::bindingConstraint; !bcDataLevel) + { + return; + } + + for (uint i = 0; i != pBCcount; ++i) + { + const NextType& bc = pBindConstraints[i]; + + bc.buildSurveyReport(results, dataLevel, fileLevel, precision); + } +} + +template +void BindingConstraints::buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + uint numSpace) const +{ + if (bool bcDataLevel = dataLevel & Category::DataLevel::bindingConstraint; !bcDataLevel) + { + return; + } + + for (uint i = 0; i != pBCcount; ++i) + { + const NextType& bc = pBindConstraints[i]; + + bc.buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); + } +} + +template +template +inline void BindingConstraints::RetrieveVariableList(PredicateT& predicate) +{ + NextType::RetrieveVariableList(predicate); +} + +template +template +inline void BindingConstraints::provideInformations(I& infos) +{ + // Begining of the node + if (VCardType::nodeDepthForGUI) + { + infos.template beginNode(); + // Next variable in the list + NextType::template provideInformations(infos); + // End of the node + infos.endNode(); + } + else + { + // Giving our VCard + infos.template addVCard(); + // Next variable in the list + NextType::template provideInformations(infos); + } +} + +template +void BindingConstraints::simulationBegin() +{ + for (auto& bc: pBindConstraints) + { + bc.simulationBegin(); + } +} + +template +void BindingConstraints::simulationEnd() +{ + for (auto& bc: pBindConstraints) + { + bc.simulationEnd(); + } +} + +template +void BindingConstraints::yearEndBuild(State& /*state*/, uint /*year*/, uint /*numSpace*/) +{ +} + +template +void BindingConstraints::initializeFromStudy(Data::Study& study) +{ + const std::vector> + inequalityByPtr = study.bindingConstraints.getPtrForInequalityBindingConstraints(); + + // The total number of inequality binding constraints count + // (we don't count BCs with equality sign) + pBCcount = (uint)inequalityByPtr.size(); + + // Reserving the memory + if (pBCcount > 0) + { + pBindConstraints.resize(pBCcount); + } + + for (uint i = 0; i != pBCcount; ++i) + { + NextType& bc = pBindConstraints[i]; + + bc.setAssociatedBindConstraint(inequalityByPtr[i]); + bc.initializeFromStudy(study); + + // Does user want to print output results related to the current binding constraint ? + bc.getPrintStatusFromStudy(study); + } + + // Here we supply the max number of columns to the variable print info collector + // This is a ugly hack (it's a work around). + // We should have a simple call to : + // NextType::supplyMaxNumberOfColumns(study); + // Instead, we have a few lines as a hack. + // What we have to do is add to the print info collector a single VariablePrintInfo + // that has a max columns size of : (nb of inequality BCs) x ResultsType::count + // But note that for now, BC output variables are chained statically (one output variable per + // inequality BC). The hack is to make the first BC output variable able to supply max columns + // size for all BC output variables with its method getMaxNumberColumns(). A solution would be + // to make BC output variables (like BindingConstMarginCost) some DYNAMIC variables. + if (pBCcount > 0) + { + NextType& bc = pBindConstraints[0]; + bc.setBindConstraintsCount(pBCcount); + bc.supplyMaxNumberOfColumns(study); + } +} + +template +void BindingConstraints::computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) +{ + for (uint i = 0; i != pBCcount; ++i) + { + // Broadcast to all constraints + pBindConstraints[i].computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } +} + +template +void BindingConstraints::yearBegin(uint year, uint numSpace) +{ + // Broadcast to all binding constraints + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].yearBegin(year, numSpace); + } +} + +template +void BindingConstraints::yearEnd(uint year, uint numSpace) +{ + // Broadcast to all binding constraints + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].yearEnd(year, numSpace); + } +} + +template +void BindingConstraints::weekBegin(State& state) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].weekBegin(state); + } +} + +template +void BindingConstraints::weekEnd(State& state) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].weekEnd(state); + } +} + +template +void BindingConstraints::hourBegin(uint hourInTheYear) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].hourBegin(hourInTheYear); + } +} + +template +void BindingConstraints::hourEnd(State& state, uint hourInTheYear) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].hourEnd(state, hourInTheYear); + } +} + +template +uint64_t BindingConstraints::memoryUsage() const +{ + uint64_t result = 0; + for (unsigned int i = 0; i != pBCcount; ++i) + { + result += sizeof(NextType) + sizeof(void*); // overhead vector + result += pBindConstraints[i].memoryUsage(); + } + return result; +} + +template +void BindingConstraints::weekForEachArea(State& state, unsigned int numSpace) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].weekForEachArea(state, numSpace); + } +} + +template +void BindingConstraints::hourForEachArea(State& state, unsigned int numSpace) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].hourForEachArea(state, numSpace); + } +} + +template +template +inline void BindingConstraints::retrieveResultsForArea( + typename Storage::ResultsType** result, + const Data::Area* area) +{ + NextType::template retrieveResultsForArea(result, area); +} + +template +void BindingConstraints::buildDigest(SurveyResults& results, + int digestLevel, + int dataLevel) const +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].buildDigest(results, digestLevel, dataLevel); + } +} + +template +template +void BindingConstraints::simulationEndSpatialAggregates(V& allVars) +{ + NextType::template simulationEndSpatialAggregates(allVars); +} + +template +template +void BindingConstraints::computeSpatialAggregatesSummary( + V& allVars, + std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) +{ + NextType::template computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); +} + +template +void BindingConstraints::beforeYearByYearExport(uint year, uint numSpace) +{ + for (uint i = 0; i != pBCcount; ++i) + { + pBindConstraints[i].beforeYearByYearExport(year, numSpace); + } +} + +template +template +inline void BindingConstraints::computeSpatialAggregateWith(O& out, + const Data::Area* area, + uint numSpace) +{ + NextType::template computeSpatialAggregateWith(out, area, numSpace); +} + +template +template +inline void BindingConstraints::retrieveResultsForLink( + typename Storage::ResultsType** result, + const Data::AreaLink* link) +{ + NextType::template retrieveResultsForLink(result, link); +} + +template +template +inline void BindingConstraints::retrieveResultsForThermalCluster( + typename Storage::ResultsType** result, + const Data::ThermalCluster* cluster) +{ + NextType::template retrieveResultsForThermalCluster(result, cluster); +} +} // namespace Antares::Solver::Variable diff --git a/src/solver/variable/include/antares/solver/variable/categories.h b/src/solver/variable/include/antares/solver/variable/categories.h new file mode 100644 index 0000000000..3c2df86b22 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/categories.h @@ -0,0 +1,265 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_CATEGORIES_H__ +#define __SOLVER_VARIABLE_CATEGORIES_H__ + +#include + +namespace Antares::Solver::Variable::Category +{ +namespace DataLevel +{ +//! Data that belong to a single area +constexpr uint8_t area = 1; +//! Data that belong to a thermal dispatchable cluster +constexpr uint8_t thermalAggregate = 2; +//! Data that belong to a link +constexpr uint8_t link = 4; +//! Data that belong to a set +constexpr uint8_t setOfAreas = 8; +// Data belonging to a binding constraint +constexpr uint8_t bindingConstraint = 16; +//! The maximum available level +constexpr uint8_t maxDataLevel = 16; +} // namespace DataLevel + +namespace FileLevel +{ +//! Values of physical variables +constexpr uint8_t va = 1; +//! Reference numbers +constexpr uint8_t id = 2; +//! Detailed values regarding thermal generation +constexpr uint8_t de = 4; +//! Detailed values regarding RES generation +constexpr uint8_t de_res = 8; +//! Detailed values regarding binding constraints +constexpr uint8_t bc = 16; +//! Detailed values regarding short term storage +constexpr uint8_t de_sts = 32; +//! The maximum available value +constexpr uint8_t maxFileLevel = 32; +//! All file level +constexpr uint8_t allFile = va | id | de | de_res | bc | de_sts; +}; // namespace FileLevel + +enum Precision +{ + //! hour + hourly = 1, + //! Daily + daily = 2, + //! Week + weekly = 4, + //! Month + monthly = 8, + //! Year + annual = 16, + //! All precisions + all = hourly | daily | weekly | monthly | annual, +}; + +/*! +** \brief Column management per variable +*/ +enum ColumnManagement +{ + //! Special value for dynamic management (the number of columns can only be known at runtime) + dynamicColumns = -1, + //! No column (means 'no data') + noColumn = 0, + //! A single column for the variable (the default) + singleColumn = 1, +}; + +/*! +** \brief Digest levels +*/ +enum Digest +{ + //! No digest + digestNone = 0, + //! Only all years + digestAllYears = 1, + //! Flow (linear) + digestFlowLinear = 2, + //! Flow (Quadratic) + digestFlowQuad = 4, +}; + +/*! +** \brief Spatial clusters (bitwise) +*/ +enum SpatialAggregate +{ + //! No spatial cluster (default) + noSpatialAggregate = 0, + //! The sum must be used + spatialAggregateSum = 1, + //! The maximum must be used + spatialAggregateMax = 2, + //! Average between areas + spatialAggregateAverage = 4, + //! Sum + 1 + spatialAggregateSumThen1IfPositive = 8, + //! + spatialAggregateOr = 16, +}; + +enum SpatialAggregateMode +{ + //! Compute the aggregate each year + spatialAggregateEachYear = 1, + //! Compute the aggregate once, at the end of the simulation + spatialAggregateOnce = 2, +}; + +enum SpatialAggregatePostProcessing +{ + spatialAggregatePostProcessingPrice = 1, +}; + +/*! +** \brief Hard limit for the decimal precision according a given File precision level +*/ +static inline uint MaxDecimalPrecision(uint fileLevel) +{ + return (fileLevel != FileLevel::id) ? 2u : 0u; +} + +template +struct NextLevel +{ + enum + { + next = (Index != Limit) ? Index * 2 : 0, + }; +}; + +template +inline void DataLevelToStream(StreamT& out, int dataLevel) +{ + switch (dataLevel) + { + using namespace DataLevel; + case area: + out += "area"; + break; + case thermalAggregate: + out += "thermal"; + break; + case link: + out += "link"; + break; + case setOfAreas: + out += "set of areas"; + break; + default: + out += NULL; + }; +} + +template +inline void FileLevelToStreamShort(StreamT& out, int fileLevel) +{ + switch (fileLevel) + { + using namespace FileLevel; + case va: + out += "va"; + break; + case id: + out += "id"; + break; + case de: + out += "de"; + break; + case de_res: + out += "res"; + break; + case bc: + out += "bc"; + break; + case de_sts: + out += "sts"; + break; + default: + out += NULL; + } +} + +template +inline void FileLevelToStream(StreamT& out, int fileLevel) +{ + switch (fileLevel) + { + using namespace FileLevel; + case va: + out += "values"; + break; + case id: + out += "id"; + break; + case de: + out += "details"; + break; + case de_res: + out += "details-res"; + break; + case bc: + out += "binding-constraints"; + break; + case de_sts: + out += "details-STstorage"; + break; + default: + out += NULL; + } +} + +template +inline void PrecisionLevelToStream(StreamT& out, int precisionLevel) +{ + switch (precisionLevel) + { + case hourly: + out += "hourly"; + break; + case daily: + out += "daily"; + break; + case weekly: + out += "weekly"; + break; + case monthly: + out += "monthly"; + break; + case annual: + out += "annual"; + break; + default: + out += NULL; + } +} + +} // namespace Antares::Solver::Variable::Category + +#endif // __SOLVER_VARIABLE_CATEGORIES_H__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/hydro.h b/src/solver/variable/include/antares/solver/variable/commons/hydro.h new file mode 100644 index 0000000000..e0ebdd41e5 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/hydro.h @@ -0,0 +1,294 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesHydro_H__ +#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesHydro_H__ + +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardTimeSeriesValuesHydro +{ + //! Caption + static std::string Caption() + { + return "H. ROR"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydro generation, thoughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardTimeSeriesValuesHydro VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal TimeSeriesValuesHydro +*/ +template +class TimeSeriesValuesHydro + : public Variable::IVariable, NextT, VCardTimeSeriesValuesHydro> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardTimeSeriesValuesHydro VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~TimeSeriesValuesHydro() + { + delete[] pValuesForTheCurrentYear; + delete[] pFatalValues; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + pFatalValues = new Matrix<>::ColumnType*[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pFatalValues[numSpace] = NULL; + } + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // The current time-series + auto& ror = pArea->hydro.series->ror; + const unsigned int nbchro = ror.getSeriesIndex(year); + pFatalValues[numSpace] = &(ror.timeSeries.entry[nbchro]); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = (*pFatalValues[numSpace]) + [state.hourInTheYear]; + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! The attached area + Data::Area* pArea; + //! + Matrix<>::ColumnType** pFatalValues; + + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class TimeSeriesValuesHydro + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesHydro_H__ diff --git a/src/solver/variable/commons/join.h b/src/solver/variable/include/antares/solver/variable/commons/join.h similarity index 75% rename from src/solver/variable/commons/join.h rename to src/solver/variable/include/antares/solver/variable/commons/join.h index 8770302bbe..de27416213 100644 --- a/src/solver/variable/commons/join.h +++ b/src/solver/variable/include/antares/solver/variable/commons/join.h @@ -1,34 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_ECONOMY_Join_H__ #define __SOLVER_VARIABLE_ECONOMY_Join_H__ -#include "../variable.h" -#include "../../simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" namespace Antares { @@ -43,6 +37,7 @@ struct VCardJoin { return ""; } + //! Unit static std::string Unit() { @@ -63,50 +58,45 @@ struct VCardJoin >>>>> ResultsType; - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & (Category::id | Category::va), - //! Precision (views) - precision = Category::all, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = 0, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 0, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - //! Intermediate values - hasIntermediateValues = 0, - - }; + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 0; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 0; }; // class VCard /*! ** \brief Join */ -template -class Join : public Variable::IVariable, Yuni::Default, VCardJoin>, - public LeftT, - public RightT, - public BindConstT +template +class Join: public Variable::IVariable, Yuni::Default, VCardJoin>, + public LeftT, + public RightT { public: typedef LeftT LeftType; typedef RightT RightType; - typedef BindConstT BindConstType; //! VCard typedef VCardJoin VCardType; //! Ancestor - typedef Variable::IVariable, Yuni::Default, VCardType> - AncestorType; + typedef Variable::IVariable, Yuni::Default, VCardType> AncestorType; //! List of expected results typedef typename VCardType::ResultsType ResultsType; @@ -124,9 +114,9 @@ class Join : public Variable::IVariable, Yuni::D { enum { - count = LeftType::template Statistics::count - + RightType::template Statistics::count - + BindConstType::template Statistics::count, + count = (int)LeftType::template Statistics < CDataLevel, + CFile > ::count + (int)RightType::template Statistics < CDataLevel, + CFile > ::count, }; }; @@ -141,7 +131,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::RetrieveVariableList(predicate); RightType::RetrieveVariableList(predicate); - BindConstType::RetrieveVariableList(predicate); } public: @@ -149,7 +138,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::initializeFromStudy(study); RightType::initializeFromStudy(study); - BindConstType::initializeFromStudy(study); } void initializeFromArea(Data::Study* study, Data::Area* area) @@ -188,7 +176,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::yearBegin(year, numSpace); RightType::yearBegin(year, numSpace); - BindConstType::yearBegin(year, numSpace); } void yearEndBuildPrepareDataForEachThermalCluster(State& state, uint year) @@ -208,14 +195,13 @@ class Join : public Variable::IVariable, Yuni::D void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) { LeftType::yearEndBuild(state, year, numSpace); - RightType::yearEndBuild(state, year); + RightType::yearEndBuild(state, year, numSpace); } void yearEnd(unsigned int year, unsigned int numSpace) { LeftType::yearEnd(year, numSpace); RightType::yearEnd(year, numSpace); - BindConstType::yearEnd(year, numSpace); } void computeSummary(std::map& numSpaceToYear, @@ -223,20 +209,18 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); RightType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); - BindConstType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); } void weekBegin(State& state) { LeftType::weekBegin(state); RightType::weekBegin(state); - BindConstType::weekBegin(state); } void weekForEachArea(State& state, unsigned int numSpace) { LeftType::weekForEachArea(state, numSpace); - RightType::weekForEachArea(state); + RightType::weekForEachArea(state, numSpace); } void weekEnd(State& state) @@ -249,13 +233,12 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::hourBegin(hourInTheYear); RightType::hourBegin(hourInTheYear); - BindConstType::hourBegin(hourInTheYear); } void hourForEachArea(State& state, unsigned int numSpace) { LeftType::hourForEachArea(state, numSpace); - RightType::hourForEachArea(state); + RightType::hourForEachArea(state, numSpace); } void hourForEachLink(State& state) @@ -268,7 +251,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::hourEnd(state, hourInTheYear); RightType::hourEnd(state, hourInTheYear); - BindConstType::hourEnd(state, hourInTheYear); } void buildSurveyReport(SurveyResults& results, @@ -278,7 +260,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::buildSurveyReport(results, dataLevel, fileLevel, precision); RightType::buildSurveyReport(results, dataLevel, fileLevel, precision); - BindConstType::buildSurveyReport(results, dataLevel, fileLevel, precision); } void buildAnnualSurveyReport(SurveyResults& results, @@ -289,7 +270,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); RightType::buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); - BindConstType::buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); } void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const @@ -317,7 +297,7 @@ class Join : public Variable::IVariable, Yuni::D void computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace) { LeftType ::template computeSpatialAggregateWith(out, area, numSpace); - RightType::template computeSpatialAggregateWith(out, area); + RightType::template computeSpatialAggregateWith(out, area, numSpace); } template @@ -332,10 +312,12 @@ class Join : public Variable::IVariable, Yuni::D std::map& numSpaceToYear, unsigned int nbYearsForCurrentSummary) { - LeftType ::template computeSpatialAggregatesSummary( - allVars, numSpaceToYear, nbYearsForCurrentSummary); - RightType::template computeSpatialAggregatesSummary( - allVars, numSpaceToYear, nbYearsForCurrentSummary); + LeftType ::template computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); + RightType::template computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); } template @@ -347,7 +329,7 @@ class Join : public Variable::IVariable, Yuni::D uint64_t memoryUsage() const { - return LeftType::memoryUsage() + RightType::memoryUsage() + BindConstType::memoryUsage(); + return LeftType::memoryUsage() + RightType::memoryUsage(); } template @@ -355,7 +337,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType ::provideInformations(infos); RightType::provideInformations(infos); - BindConstType::provideInformations(infos); } template @@ -396,7 +377,6 @@ class Join : public Variable::IVariable, Yuni::D { LeftType::localBuildAnnualSurveyReport(results, fileLevel, precision); RightType::localBuildAnnualSurveyReport(results, fileLevel, precision); - BindConstType::localBuildAnnualSurveyReport(results, fileLevel, precision); } }; // class Join diff --git a/src/solver/variable/include/antares/solver/variable/commons/links/links.h b/src/solver/variable/include/antares/solver/variable/commons/links/links.h new file mode 100644 index 0000000000..eff3b7d09d --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/links/links.h @@ -0,0 +1,230 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_INC_LINK_H__ +#define __SOLVER_VARIABLE_INC_LINK_H__ + +// NOTE : template includes are used here to reduce template instanciation +// which still seems to be really cpu/memory consuming + +#include + +#include "antares/solver/variable/info.h" +#include "antares/solver/variable/storage/results.h" + +#include "../../state.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ + +struct VCardAllLinks +{ + //! Caption + static std::string Caption() + { + return "Links"; + } + + //! Unit + static std::string Unit() + { + return ""; + } + + //! The short description of the variable + static const char* Description() + { + return ""; + } + + //! The expecte results + using ResultsType = Results<>; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +1; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 0; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 0; + +}; // class VCard + +template +class Links +{ +public: + //! Type of the next static variable + using NextType = VariablePerLink; + //! VCard + using VCardType = VCardAllLinks; + //! Ancestor + // using AncestorType = Variable::IVariable, NextT, VCardType>; + + //! List of expected results + using ResultsType = VCardType::ResultsType; + + enum + { + //! How many items have we got + count = NextType::count, + }; + + template + struct Statistics + { + enum + { + count = NextType::template Statistics < CDataLevel, + CFile > ::count + }; + }; + +public: + /*! + ** \brief Retrieve the list of all individual variables + ** + ** The predicate must implement the method `add(name, unit, comment)`. + */ + template + static void RetrieveVariableList(PredicateT& predicate); + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + Links(); + //! Destructor + ~Links(); + //@} + + void initializeFromStudy(Data::Study& study); + void initializeFromArea(Data::Study*, Data::Area*); + void initializeFromThermalCluster(Data::Study*, Data::Area*, Data::ThermalCluster*); + void initializeFromAreaLink(Data::Study*, Data::AreaLink*); + + void broadcastNonApplicability(bool applyNonApplicable); + void getPrintStatusFromStudy(Data::Study& study); + void supplyMaxNumberOfColumns(Data::Study& study); + + void simulationBegin(); + void simulationEnd(); + + void yearBegin(uint year, unsigned int numSpace); + + void yearEndBuildPrepareDataForEachThermalCluster(State& state, uint year, uint numSpace); + void yearEndBuildForEachThermalCluster(State& state, uint year, uint numSpace); + + void yearEndBuild(State& state, uint year); + + void yearEnd(uint year, uint numSpace); + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary); + + void weekBegin(State& state); + + void weekForEachArea(State& state, uint numSpace); + void weekEnd(State& state); + + void hourBegin(uint hourInTheYear); + void hourForEachArea(State& state, uint numSpace); + void hourForEachLink(State& state, uint numSpace); + + void hourEnd(State& state, uint hourInTheYear); + + void buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const; + + void buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + uint numSpace) const; + + void beforeYearByYearExport(uint year, uint numSpace); + + uint64_t memoryUsage() const; + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const; + + template + static void provideInformations(I& infos); + + template + inline const double* retrieveHourlyResultsForCurrentYear(uint) const + { + return nullptr; + } + + template + void retrieveResultsForArea(Storage::ResultsType** result, const Data::Area*) + { + *result = NULL; + } + + template + void retrieveResultsForThermalCluster(Storage::ResultsType** result, + const Data::ThermalCluster*) + { + *result = NULL; + } + + template + void retrieveResultsForLink(Storage::ResultsType** result, + const Data::AreaLink* link) + { + pLinks[link->indexForArea].template retrieveResultsForLink(result, link); + } + + template + void computeSpatialAggregateWith(O&, uint) + { + // Do nothing + } + +public: + //! Area list + NextType* pLinks; + //! The total number of links + uint pLinkCount; + +}; // class Links + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#include "links.hxx" + +#endif // __SOLVER_VARIABLE_INC_LINK_H__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/links/links.hxx b/src/solver/variable/include/antares/solver/variable/commons/links/links.hxx new file mode 100644 index 0000000000..d56090f7d3 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/links/links.hxx @@ -0,0 +1,460 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_INC_LINK_HXX__ +#define __SOLVER_VARIABLE_INC_LINK_HXX__ + +#include +#include "antares/solver/variable/endoflist.h" // For UNUSED_VARIABLE, should be somewhere else + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ + +template +inline Links::Links() +{ + // Do nothing +} + +template +inline void Links::initializeFromStudy([[maybe_unused]] Data::Study& study) +{ + // Do nothing +} + +template +inline void Links::initializeFromAreaLink(Data::Study*, Data::AreaLink*) +{ + // Nothing to do here +} + +template +inline void Links::initializeFromThermalCluster(Data::Study*, + Data::Area*, + Data::ThermalCluster*) +{ + // This method should not be called at this stage +} + +template +inline void Links::broadcastNonApplicability(bool applyNonApplicable) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].broadcastNonApplicability(applyNonApplicable); + } +} + +template +inline void Links::getPrintStatusFromStudy(Data::Study& study) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].getPrintStatusFromStudy(study); + } +} + +template +inline void Links::supplyMaxNumberOfColumns(Data::Study& study) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].supplyMaxNumberOfColumns(study); + } +} + +template +inline void Links::yearBegin(uint year, unsigned int numSpace) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].yearBegin(year, numSpace); + } +} + +template +inline void Links::yearEndBuildPrepareDataForEachThermalCluster( + State& state, + uint year, + unsigned int numSpace) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); + } +} + +template +inline void Links::yearEndBuildForEachThermalCluster(State& state, + uint year, + unsigned int numSpace) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].yearEndBuildForEachThermalCluster(state, year, numSpace); + } +} + +template +inline void Links::yearEndBuild(State& state, uint year) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].yearEndBuild(state, year); + } +} + +template +inline void Links::yearEnd(uint year, uint numSpace) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].yearEnd(year, numSpace); + } +} + +template +inline void Links::computeSummary( + std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } +} + +template +inline void Links::weekBegin(State& state) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].weekBegin(state); + } +} + +template +inline void Links::weekForEachArea(State&, uint numSpace) +{ + // do nothing + UNUSED_VARIABLE(numSpace); +} + +template +inline void Links::weekEnd(State& state) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].weekEnd(state); + } +} + +template +inline void Links::hourBegin(uint hourInTheYear) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].hourBegin(hourInTheYear); + } +} + +template +inline void Links::hourForEachArea(State& state, unsigned int numSpace) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].hourForEachArea(state, numSpace); + } +} + +template +inline void Links::hourForEachLink(State& state, unsigned int numSpace) +{ + pLinks[state.link->indexForArea].hourForEachLink(state, numSpace); +} + +template +inline void Links::hourEnd(State& state, uint hourInTheYear) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].hourEnd(state, hourInTheYear); + } +} + +template +inline void Links::buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const +{ + int count_int = count; + bool link_dataLevel = (dataLevel & Category::DataLevel::link); + if (count_int && link_dataLevel) + { + assert(results.data.link != NULL + && "The link must not be null to generate a survey report"); + + // Build the survey results for the given area + auto& link = *results.data.link; + + // Filtering + switch (precision) + { + case Category::hourly: + if (!(link.filterSynthesis & Data::filterHourly)) + { + return; + } + break; + case Category::daily: + if (!(link.filterSynthesis & Data::filterDaily)) + { + return; + } + break; + case Category::weekly: + if (!(link.filterSynthesis & Data::filterWeekly)) + { + return; + } + break; + case Category::monthly: + if (!(link.filterSynthesis & Data::filterMonthly)) + { + return; + } + break; + case Category::annual: + if (!(link.filterSynthesis & Data::filterAnnual)) + { + return; + } + break; + case Category::all: + break; + } + auto& linkOutputData = pLinks[link.indexForArea]; + linkOutputData.buildSurveyReport(results, dataLevel, fileLevel, precision); + } +} + +template +inline void Links::buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + uint numSpace) const +{ + int count_int = count; + bool link_dataLevel = (dataLevel & Category::DataLevel::link); + if (count_int && link_dataLevel) + { + assert(results.data.link != NULL + && "The link must not be null to generate a survey report"); + + auto& link = *results.data.link; + + // Filtering + switch (precision) + { + case Category::hourly: + if (not(link.filterYearByYear & Data::filterHourly)) + { + return; + } + break; + case Category::daily: + if (not(link.filterYearByYear & Data::filterDaily)) + { + return; + } + break; + case Category::weekly: + if (not(link.filterYearByYear & Data::filterWeekly)) + { + return; + } + break; + case Category::monthly: + if (not(link.filterYearByYear & Data::filterMonthly)) + { + return; + } + break; + case Category::annual: + if (not(link.filterYearByYear & Data::filterAnnual)) + { + return; + } + break; + case Category::all: + break; + } + + // Build the survey results for the given area + auto& linkOutputData = pLinks[results.data.link->indexForArea]; + linkOutputData.buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); + } +} + +template +template +inline void Links::provideInformations(I& infos) +{ + // Begining of the node + if (VCardType::nodeDepthForGUI) + { + infos.template beginNode(); + // Next variable in the list + NextType::template provideInformations(infos); + // End of the node + infos.endNode(); + } + else + { + // Giving our VCard + infos.template addVCard(); + // Next variable in the list + NextType::template provideInformations(infos); + } +} + +template +template +void Links::RetrieveVariableList(PredicateT& predicate) +{ + NextType::RetrieveVariableList(predicate); +} + +template +inline uint64_t Links::memoryUsage() const +{ + uint64_t result = 0; + for (uint i = 0; i != pLinkCount; ++i) + { + result += sizeof(NextType) + sizeof(void*); + result += pLinks[i].memoryUsage(); + } + return result; +} + +template +Links::~Links() +{ + // Releasing the memory occupied by the areas + delete[] pLinks; +} + +template +void Links::initializeFromArea(Data::Study* study, Data::Area* area) +{ + // Assert + assert(study && "A study pointer must not be null"); + assert(area && "An area pointer must not be null"); + + pLinkCount = (uint)area->links.size(); + if (pLinkCount) + { + pLinks = new NextType[pLinkCount]; + + // For each link... + uint lnkIndex = 0; + auto end = area->links.end(); + for (auto i = area->links.begin(); i != end; ++i, ++lnkIndex) + { + // Instancing a new set of variables of the area + NextType& n = pLinks[lnkIndex]; + + // Initialize the variables + // From the study + n.initializeFromStudy(*study); + // From the area + n.initializeFromArea(study, area); + // From the link + n.initializeFromAreaLink(study, i->second); + } + } + else + { + pLinks = nullptr; + } +} + +template +void Links::simulationBegin() +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].simulationBegin(); + } +} + +template +void Links::simulationEnd() +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].simulationEnd(); + } +} + +template +void Links::buildDigest(SurveyResults& results, + int digestLevel, + int dataLevel) const +{ + int count_int = count; + bool linkDataLevel = dataLevel & Category::DataLevel::link; + bool areaDataLevel = dataLevel & Category::DataLevel::area; + if (count_int && (linkDataLevel || areaDataLevel)) + { + if (not results.data.area->links.empty()) + { + auto end = results.data.area->links.cend(); + for (auto i = results.data.area->links.cbegin(); i != end; ++i) + { + results.data.link = i->second; + pLinks[results.data.link->indexForArea].buildDigest(results, + digestLevel, + Category::DataLevel::link); + } + } + } +} + +template +void Links::beforeYearByYearExport(uint year, uint numSpace) +{ + for (uint i = 0; i != pLinkCount; ++i) + { + pLinks[i].beforeYearByYearExport(year, numSpace); + } +} + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_INC_LINK_HXX__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/load.h b/src/solver/variable/include/antares/solver/variable/commons/load.h new file mode 100644 index 0000000000..3080f2f44a --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/load.h @@ -0,0 +1,289 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesLoad_H__ +#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesLoad_H__ + +#include "antares/solver/simulation/sim_extern_variables_globales.h" + +#include "../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardTimeSeriesValuesLoad +{ + //! Caption + static std::string Caption() + { + return "LOAD"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Load generation, thoughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardTimeSeriesValuesLoad VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal TimeSeriesValuesLoad +*/ +template +class TimeSeriesValuesLoad + : public Variable::IVariable, NextT, VCardTimeSeriesValuesLoad> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardTimeSeriesValuesLoad VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~TimeSeriesValuesLoad() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Next + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // The current time-series + // + // At this point, these values are not the raw values of the load timeseries + // see performTransformationsBeforeLaunchingSimulation() + // L* = L + DSM + // + (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, + pArea->load.series.getColumn(year), + sizeof(double) * pArea->load.series.timeSeries.height); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! The attached area + Antares::Data::Area* pArea; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class TimeSeriesValuesLoad + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesLoad_H__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/miscGenMinusRowPSP.h b/src/solver/variable/include/antares/solver/variable/commons/miscGenMinusRowPSP.h new file mode 100644 index 0000000000..acb74f7d9f --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/miscGenMinusRowPSP.h @@ -0,0 +1,289 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_MiscGenMinusRowPSP_H__ +#define __SOLVER_VARIABLE_ECONOMY_MiscGenMinusRowPSP_H__ + +#include +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardMiscGenMinusRowPSP +{ + //! Caption + static std::string Caption() + { + return "MISC. NDG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Non-dispatchable generation (not including wind and run-of-the-river)"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardMiscGenMinusRowPSP VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal MiscGenMinusRowPSP +*/ +template +class MiscGenMinusRowPSP + : public Variable::IVariable, NextT, VCardMiscGenMinusRowPSP> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardMiscGenMinusRowPSP VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~MiscGenMinusRowPSP() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Copy raw values + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + // Memcpy for the first value + (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, + area->miscGen.entry[0], + sizeof(double) * area->miscGen.height); + + { + // We must not include the CHP and the Solar. So we have to start from `2` + for (unsigned int x = 1; x != (unsigned int)Data::fhhPSP; ++x) + { + const Matrix<>::ColumnType& col = area->miscGen.entry[x]; + for (unsigned int y = 0; y != area->miscGen.height; ++y) + { + pValuesForTheCurrentYear[numSpace].hour[y] += col[y]; + } + } + } + } + + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class MiscGenMinusRowPSP + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_MiscGenMinusRowPSP_H__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/psp.h b/src/solver/variable/include/antares/solver/variable/commons/psp.h new file mode 100644 index 0000000000..06814e1800 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/psp.h @@ -0,0 +1,275 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_PSP_H__ +#define __SOLVER_VARIABLE_ECONOMY_PSP_H__ + +#include +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardPSP +{ + //! Caption + static std::string Caption() + { + return "PSP"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "PSP"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardPSP VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal PSP +*/ +template +class PSP: public Variable::IVariable, NextT, VCardPSP> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardPSP VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~PSP() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Copy raw values + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, + area->miscGen.entry[Data::fhhPSP], + sizeof(double) * area->miscGen.height); + } + + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class PSP + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_PSP_H__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/rowBalance.h b/src/solver/variable/include/antares/solver/variable/commons/rowBalance.h new file mode 100644 index 0000000000..503d11f981 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/rowBalance.h @@ -0,0 +1,265 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_RowBalance_H__ +#define __SOLVER_VARIABLE_ECONOMY_RowBalance_H__ + +#include +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardRowBalance +{ + //! Caption + static std::string Caption() + { + return "ROW BAL."; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Row Balance"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardRowBalance VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateOnce; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesType; + typedef IntermediateValues IntermediateValuesBaseType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal RowBalance +*/ +template +class RowBalance: public Variable::IVariable, NextT, VCardRowBalance> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardRowBalance VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~RowBalance() + { + } + + void initializeFromStudy(Data::Study& study) + { + // Average on all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear.initializeFromStudy(study); + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Copy raw values + unsigned int height = area->miscGen.height; + (void)::memcpy(pValuesForTheCurrentYear.hour, + area->miscGen.entry[Data::fhhRowBalance], + sizeof(double) * height); + + if (study->parameters.mode == Data::SimulationMode::Adequacy) + { + for (unsigned int h = 0; h != height; ++h) + { + pValuesForTheCurrentYear.hour[h] -= area->reserves + .entry[Data::fhrPrimaryReserve][h]; + } + } + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear.computeStatisticsForTheCurrentYear(); + + // Merge all those values with the global results + AncestorType::pResults.merge(0, pValuesForTheCurrentYear); + + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear.template buildAnnualSurveyReport(results, + fileLevel, + precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + +}; // class RowBalance + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_RowBalance_H__ diff --git a/src/solver/variable/include/antares/solver/variable/commons/solar.h b/src/solver/variable/include/antares/solver/variable/commons/solar.h new file mode 100644 index 0000000000..c5ab16422d --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/solar.h @@ -0,0 +1,294 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesSolar_H__ +#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesSolar_H__ + +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardTimeSeriesValuesSolar +{ + //! Caption + static std::string Caption() + { + return "SOLAR"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Solar generation, thoughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardTimeSeriesValuesSolar VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal TimeSeriesValuesSolar +*/ +template +class TimeSeriesValuesSolar + : public Variable::IVariable, NextT, VCardTimeSeriesValuesSolar> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardTimeSeriesValuesSolar VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~TimeSeriesValuesSolar() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + isRenewableGenerationAggregrated = study.parameters.renewableGeneration.isAggregated(); + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Next + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + if (isRenewableGenerationAggregrated) + { + // The current solar time-series + (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, + pArea->solar.series.getColumn(year), + sizeof(double) * pArea->solar.series.timeSeries.height); + } + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + NextType::hourEnd(state, hourInTheYear); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! The attached area + Data::Area* pArea; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + bool isRenewableGenerationAggregrated = true; + +}; // class TimeSeriesValuesSolar + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesSolar_H__ diff --git a/src/solver/variable/commons/spatial-aggregate.h b/src/solver/variable/include/antares/solver/variable/commons/spatial-aggregate.h similarity index 75% rename from src/solver/variable/commons/spatial-aggregate.h rename to src/solver/variable/include/antares/solver/variable/commons/spatial-aggregate.h index 82c39279e5..ea966c4977 100644 --- a/src/solver/variable/commons/spatial-aggregate.h +++ b/src/solver/variable/include/antares/solver/variable/commons/spatial-aggregate.h @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_ECONOMY_SPATIAL_AGGREGATE_H__ #define __SOLVER_VARIABLE_ECONOMY_SPATIAL_AGGREGATE_H__ -#include "../variable.h" +#include "antares/solver/variable/variable.h" + // #include // In case it is needed namespace Antares @@ -55,12 +50,12 @@ struct MultipleCaptionProxy template struct MultipleCaptionProxy<0, VCardT> { - static std::string Caption(const uint indx) + static std::string Caption(const uint) { return ""; } - static std::string Unit(const uint indx) + static std::string Unit(const uint) { return ""; } @@ -69,12 +64,12 @@ struct MultipleCaptionProxy<0, VCardT> template struct MultipleCaptionProxy<1, VCardT> { - static std::string Caption(const uint indx) + static std::string Caption(const uint) { return ""; } - static std::string Unit(const uint indx) + static std::string Unit(const uint) { return ""; } @@ -83,12 +78,12 @@ struct MultipleCaptionProxy<1, VCardT> template struct MultipleCaptionProxy { - static std::string Caption(const uint indx) + static std::string Caption(const uint) { return ""; } - static std::string Unit(const uint indx) + static std::string Unit(const uint) { return ""; } @@ -105,11 +100,13 @@ struct VCardProxy { return VCardOrigin::Caption(); } + //! Unit static std::string Unit() { return VCardOrigin::Unit(); } + //! The short description of the variable static std::string Description() { @@ -126,30 +123,27 @@ struct VCardProxy typedef typename VCardOrigin::IntermediateValuesTypeForSpatialAg IntermediateValuesTypeForSpatialAg; - enum - { - //! Data Level - categoryDataLevel = Category::setOfAreas, - //! File level (provided by the type of the results) - categoryFileLevel = VCardOrigin::categoryFileLevel, - //! Precision (views) - precision = VCardOrigin::precision, - //! Indentation (GUI) - nodeDepthForGUI = +0, - //! Decimal precision - decimal = VCardOrigin::decimal, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = VCardOrigin::columnCount, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - spatialAggregateMode = Category::spatialAggregateEachYear, - spatialAggregatePostProcessing = 0, - - //! Intermediate values - hasIntermediateValues = 1, - //! Can this variable be non applicable (0 : no, 1 : yes) - isPossiblyNonApplicable = VCardOrigin::isPossiblyNonApplicable, - }; + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::setOfAreas; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = VCardOrigin::categoryFileLevel; + //! Precision (views) + static constexpr uint8_t precision = VCardOrigin::precision; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = VCardOrigin::decimal; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = VCardOrigin::columnCount; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = VCardOrigin::isPossiblyNonApplicable; struct Multiple { @@ -168,7 +162,7 @@ struct VCardProxy template class VarT, class NextT = Container::EndOfList> class SpatialAggregate - : public Variable::IVariable, NextT, VCardProxy> + : public Variable::IVariable, NextT, VCardProxy> { public: //! Type of the next static variable @@ -195,11 +189,11 @@ class SpatialAggregate { enum { - count - = ((VCardType::categoryDataLevel & CDataLevel && VCardType::categoryFileLevel & CFile) - ? (NextType::template Statistics::count - + VCardType::columnCount * ResultsType::count) - : NextType::template Statistics::count), + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), }; }; @@ -223,7 +217,9 @@ class SpatialAggregate VarT::InitializeResultsFromStudy(AncestorType::pResults, study); pValuesForTheCurrentYear = new IntermediateValuesBaseType[pNbYearsParallel]; for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { VariableAccessorType::InitializeAndReset(pValuesForTheCurrentYear[numSpace], study); + } auto& limits = study.runtime->rangeLimits; @@ -277,10 +273,10 @@ class SpatialAggregate NextType::yearEndBuildForEachThermalCluster(state, year); } - void yearEndBuild(State& state, unsigned int year) + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) { // Next variable - NextType::yearEndBuild(state, year); + NextType::yearEndBuild(state, year, numSpace); } void yearEnd(uint year) @@ -307,17 +303,19 @@ class SpatialAggregate NextType::hourBegin(hourInTheYear); } - void hourForEachArea(State& state) + void hourForEachArea(State& state, unsigned int numSpace) { // Next variable - NextType::hourForEachArea(state); + NextType::hourForEachArea(state, numSpace); } template void yearEndSpatialAggregates(V& allVars, uint year, const SetT& set, uint numSpace) { if (VCardType::VCardOrigin::spatialAggregateMode & Category::spatialAggregateEachYear) + { internalSpatialAggregateForCurrentYear(allVars, set, numSpace); + } // Next variable NextType::template yearEndSpatialAggregates(allVars, year, set, numSpace); @@ -329,18 +327,23 @@ class SpatialAggregate uint nbYearsForCurrentSummary) { if (VCardType::VCardOrigin::spatialAggregateMode & Category::spatialAggregateEachYear) + { internalSpatialAggregateForParallelYears(numSpaceToYear, nbYearsForCurrentSummary); + } // Next variable - NextType::computeSpatialAggregatesSummary( - allVars, numSpaceToYear, nbYearsForCurrentSummary); + NextType::computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); } template void simulationEndSpatialAggregates(V& allVars, const SetT& set) { if (VCardType::VCardOrigin::spatialAggregateMode & Category::spatialAggregateOnce) + { internalSpatialAggregate(allVars, 0, set); + } // Next variable NextType::template simulationEndSpatialAggregates(allVars, set); @@ -349,14 +352,18 @@ class SpatialAggregate inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const { // Generate the Digest for the local results (districts part) - if (VCardType::columnCount != 0 && (VCardType::categoryDataLevel & Category::setOfAreas)) + if (VCardType::columnCount != 0 + && (VCardType::categoryDataLevel & Category::DataLevel::setOfAreas)) { // Initializing pointer on variable non applicable and print stati arrays to beginning results.isPrinted = AncestorType::isPrinted; results.isCurrentVarNA = AncestorType::isNonApplicable; VariableAccessorType::template BuildDigest( - results, AncestorType::pResults, digestLevel, dataLevel); + results, + AncestorType::pResults, + digestLevel, + dataLevel); } // Ask to build the digest to the next variable NextType::buildDigest(results, digestLevel, dataLevel); @@ -367,7 +374,8 @@ class SpatialAggregate int precision, uint numSpace) const { - if (VCardType::columnCount != 0 && (VCardType::categoryDataLevel & Category::setOfAreas)) + if (VCardType::columnCount != 0 + && (VCardType::categoryDataLevel & Category::DataLevel::setOfAreas)) { // Initializing pointer on variable non applicable and print stati arrays to beginning results.isPrinted = AncestorType::isPrinted; @@ -377,7 +385,10 @@ class SpatialAggregate VCardType::columnCount> VAType; VAType::template BuildAnnualSurveyReport( - results, pValuesForTheCurrentYear[numSpace], fileLevel, precision); + results, + pValuesForTheCurrentYear[numSpace], + fileLevel, + precision); } } @@ -402,22 +413,31 @@ class SpatialAggregate // The spatial cluster may be an average if (VCardType::VCardOrigin::spatialAggregate & Category::spatialAggregateAverage) + { VariableAccessorType::MultiplyHourlyResultsBy(pValuesForTheCurrentYear[0], 1. / set.size()); + } // The spatial cluster may be an average if (VCardType::VCardOrigin::spatialAggregate & Category::spatialAggregateSumThen1IfPositive) + { VariableAccessorType::SetTo1IfPositive(pValuesForTheCurrentYear[0]); + } if (VCardType::VCardOrigin::spatialAggregate & Category::spatialAggregateOr) + { VariableAccessorType::Or(pValuesForTheCurrentYear[0]); + } } else + { assert(!set.empty() && "The set should not be empty at this point"); + } // Compute all statistics for the current year (daily,weekly,monthly,...) VariableAccessorType::template ComputeStatistics(pValuesForTheCurrentYear[0]); - VariableAccessorType::ComputeSummary( - pValuesForTheCurrentYear[0], AncestorType::pResults, year); + VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[0], + AncestorType::pResults, + year); } template @@ -440,17 +460,25 @@ class SpatialAggregate // The spatial cluster may be an average if (VCardType::VCardOrigin::spatialAggregate & Category::spatialAggregateAverage) + { VariableAccessorType::MultiplyHourlyResultsBy(pValuesForTheCurrentYear[numSpace], 1. / set.size()); + } // The spatial cluster may be an average if (VCardType::VCardOrigin::spatialAggregate & Category::spatialAggregateSumThen1IfPositive) + { VariableAccessorType::SetTo1IfPositive(pValuesForTheCurrentYear[numSpace]); + } if (VCardType::VCardOrigin::spatialAggregate & Category::spatialAggregateOr) + { VariableAccessorType::Or(pValuesForTheCurrentYear[numSpace]); + } } else + { assert(!set.empty() && "The set should not be empty at this point"); + } // Compute all statistics for the current year (daily,weekly,monthly,...) VariableAccessorType::template ComputeStatistics( @@ -464,8 +492,9 @@ class SpatialAggregate for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) { // Merge all those values with the global results - VariableAccessorType::ComputeSummary( - pValuesForTheCurrentYear[numSpace], AncestorType::pResults, numSpaceToYear[numSpace]); + VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[numSpace], + AncestorType::pResults, + numSpaceToYear[numSpace]); } } diff --git a/src/solver/variable/include/antares/solver/variable/commons/wind.h b/src/solver/variable/include/antares/solver/variable/commons/wind.h new file mode 100644 index 0000000000..3e0fda355b --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/commons/wind.h @@ -0,0 +1,288 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesWind_H__ +#define __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesWind_H__ + +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardTimeSeriesValuesWind +{ + //! Caption + static std::string Caption() + { + return "WIND"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Wind generation, thoughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardTimeSeriesValuesWind VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal TimeSeriesValuesWind +*/ +template +class TimeSeriesValuesWind + : public Variable::IVariable, NextT, VCardTimeSeriesValuesWind> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardTimeSeriesValuesWind VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~TimeSeriesValuesWind() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + isRenewableGenerationAggregrated = study.parameters.renewableGeneration.isAggregated(); + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + if (isRenewableGenerationAggregrated) + { + // The current wind time-series + (void)::memcpy(pValuesForTheCurrentYear[numSpace].hour, + pArea->wind.series.getColumn(year), + sizeof(double) * pArea->wind.series.timeSeries.height); + } + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! The attached area + Data::Area* pArea; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + bool isRenewableGenerationAggregrated = true; + +}; // class TimeSeriesValuesWind + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_TimeSeriesValuesWind_H__ diff --git a/src/solver/variable/include/antares/solver/variable/container.h b/src/solver/variable/include/antares/solver/variable/container.h new file mode 100644 index 0000000000..94a3997b79 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/container.h @@ -0,0 +1,240 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_LIST_H__ +#define __SOLVER_VARIABLE_LIST_H__ + +#include +#include +#include + +#include + +#include "categories.h" +#include "endoflist.h" +#include "info.h" +#include "surveyresults.h" + +namespace Antares::Solver::Variable::Container +{ +/*! +** \brief Static list for all output variables +** +** This structure is merely a static linked list with all variables +*/ +template +class List: public NextT +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! The full type of the class + typedef List ListType; + + enum + { + //! How many items have we got + count = NextT::count, + }; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default Constructor + */ + List(); + /*! + ** \brief Destructor + */ + ~List(); + //@} + + //! \name Variable initialization + //@{ + /*! + ** \brief Initialize all output variables + */ + void initializeFromStudy(Data::Study& study); + + /*! + ** \brief Initialize all output variables according a given area + */ + void initializeFromArea(Data::Study* study, Data::Area* area); + + /*! + ** \brief Initialize all output variables according a given link + */ + void initializeFromLink(Data::Study* study, Data::AreaLink* link); + + /*! + ** \brief Initialize all output variables according a given thermal cluster + */ + void initializeFromThermalCluster(Data::Study* study, + Data::Area* area, + Data::ThermalCluster* cluster); + //@} + + //! \name Simulation events + //@{ + /*! + ** \brief Notify to all variables that the simulation is about to begin + */ + void simulationBegin(); + + /*! + ** \brief Notify to all variables that the simulation has finished + */ + void simulationEnd(); + //@} + + //! \name Years events + //@{ + /*! + ** \brief Notify to all variables that a new year is about to start + ** + ** \param year The current year + */ + void yearBegin(unsigned int year, unsigned int numSpace); + + /*! + ** \brief Notify to all variables that the year is now over + ** + ** That mainly means that all variables should perform the monthly + ** aggragations. + ** \param year The current year + */ + void yearEnd(unsigned int year, unsigned int numSpace); + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary); + + template + void yearEndSpatialAggregates(V& allVars, unsigned int year, unsigned int numSpace); + + template + void yearEndSpatialAggregates(V& allVars, unsigned int year, const SetT& set); + + template + void computeSpatialAggregatesSummary(V& allVars, + std::map& numSpaceToYear, + unsigned int); + + template + void simulationEndSpatialAggregates(V& allVars); + + template + void simulationEndSpatialAggregates(V& allVars, const SetT& set); + //@} + + //! \name Hourly events + //@{ + /*! + ** \brief Notify to all variables that a new hour is about to begin + */ + void hourBegin(unsigned int hourInTheYear); + + void hourForEachArea(State& state, unsigned int numSpace); + + void hourForEachLink(State& state); + + void hourEnd(State& state, unsigned int hourInTheYear); + //@} + + //! \name Weekly events + //@{ + void weekBegin(State& state); + + void weekEnd(State& state); + //@} + + //! \name Spatial aggregation + //@{ + template + void computeSpatialAggregateWith(O& out); + + template + void computeSpatialAggregateWith(O& out, const Data::Area* area, unsigned int numSpace); + + template + void retrieveResultsForArea(typename Variable::Storage::ResultsType** result, + const Data::Area* area); + + template + void retrieveResultsForThermalCluster( + typename Variable::Storage::ResultsType** result, + const Data::ThermalCluster* cluster); + + template + void retrieveResultsForLink(typename Variable::Storage::ResultsType** result, + const Data::AreaLink* link); + //@} + + //! \name User reports + //@{ + /*! + ** \brief Ask to all variables to fullfil the report + */ + void buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const; + + void buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + unsigned int numSpace) const; + + /*! + ** \brief Ask to all variables to fullfil additional reports (like the digest for example) + ** + ** \tparam GlobalT True to write down the results of the simulation, false + ** for the results of the current year + */ + void exportSurveyResults(bool global, + const Yuni::String& output, + unsigned int numSpace, + IResultWriter& writer); + + /*! + ** \brief Ask to all variables to fullfil the digest + */ + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const; + //@} + + //! \name Memory management + //@{ + //! Get the amount of memory currently used by the class + uint64_t memoryUsage() const; + //@} + +private: + //! Pointer to the current study + Data::Study* pStudy; + +}; // class List + +} // namespace Antares::Solver::Variable::Container + +#include "container.hxx" +#include "surveyresults/reportbuilder.hxx" + +#endif // __SOLVER_VARIABLE_LIST_H__ diff --git a/src/solver/variable/include/antares/solver/variable/container.hxx b/src/solver/variable/include/antares/solver/variable/container.hxx new file mode 100644 index 0000000000..0f9559b3a2 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/container.hxx @@ -0,0 +1,370 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_CONTAINER_CONTAINER_HXX__ +#define __SOLVER_CONTAINER_CONTAINER_HXX__ + +#include + +#include +#include + +#include "antares/solver/variable/surveyresults/reportbuilder.hxx" + +#define SEP Yuni::IO::Separator + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Container +{ +template +inline List::List() +{ +} + +template +inline List::~List() +{ +} + +template +inline void List::initializeFromStudy(Data::Study& study) +{ + // Store a pointer to the current study + pStudy = &study; + // Next + NextType::initializeFromStudy(study); +} + +template +inline void List::initializeFromArea(Data::Study* study, Data::Area* area) +{ + // Ask to the first variable to do it + NextType::initializeFromArea(study, area); +} + +template +inline void List::initializeFromLink(Data::Study* study, Data::AreaLink* link) +{ + // Next + NextType::initializeFromAreaLink(study, link); +} + +template +inline void List::initializeFromThermalCluster(Data::Study* study, + Data::Area* area, + Data::ThermalCluster* cluster) +{ + // Next + NextType::initializeFromThermalCluster(study, area, cluster); +} + +template +inline void List::simulationBegin() +{ + NextType::simulationBegin(); +} + +template +inline void List::simulationEnd() +{ + NextType::simulationEnd(); +} + +template +inline void List::yearBegin(unsigned int year, unsigned int numSpace) +{ + NextType::yearBegin(year, numSpace); +} + +template +inline void List::yearEnd(unsigned int year, unsigned int numSpace) +{ + NextType::yearEnd(year, numSpace); +} + +template +inline void List::computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) +{ + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); +} + +template +template +inline void List::yearEndSpatialAggregates(V& allVars, + unsigned int year, + unsigned int numSpace) +{ + // Next variable + NextType::template yearEndSpatialAggregates(allVars, year, numSpace); +} + +template +template +inline void List::yearEndSpatialAggregates(V& allVars, unsigned int year, const SetT& set) +{ + // Next variable + NextType::template yearEndSpatialAggregates(allVars, year, set); +} + +template +template +inline void List::computeSpatialAggregatesSummary( + V& allVars, + std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) +{ + // Next variable + NextType::template computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); +} + +template +template +inline void List::simulationEndSpatialAggregates(V& allVars) +{ + // Next variable + NextType::template simulationEndSpatialAggregates(allVars); +} + +template +template +inline void List::simulationEndSpatialAggregates(V& allVars, const SetT& set) +{ + // Next variable + NextType::template simulationEndSpatialAggregates(allVars, set); +} + +template +inline void List::hourBegin(unsigned int hourInTheYear) +{ + NextType::hourBegin(hourInTheYear); +} + +template +inline void List::weekBegin(State& state) +{ + NextType::weekBegin(state); +} + +template +inline void List::weekEnd(State& state) +{ + NextType::weekEnd(state); +} + +template +inline void List::hourForEachArea(State& state, unsigned int numSpace) +{ + NextType::hourForEachArea(state, numSpace); +} + +template +inline void List::hourForEachLink(State& state) +{ + NextType::hourForEachLink(state); +} + +template +inline void List::hourEnd(State& state, unsigned int hourInTheYear) +{ + NextType::hourEnd(state, hourInTheYear); +} + +template +template +inline void List::computeSpatialAggregateWith(O& out) +{ + NextType::template computeSpatialAggregateWith(out); +} + +template +template +inline void List::computeSpatialAggregateWith(O& out, + const Data::Area* area, + unsigned int numSpace) +{ + NextType::template computeSpatialAggregateWith(out, area, numSpace); +} + +template +template +inline void List::retrieveResultsForArea( + typename Variable::Storage::ResultsType** result, + const Data::Area* area) +{ + NextType::template retrieveResultsForArea(result, area); +} + +template +template +inline void List::retrieveResultsForThermalCluster( + typename Variable::Storage::ResultsType** result, + const Data::ThermalCluster* cluster) +{ + NextType::template retrieveResultsForThermalCluster(result, cluster); +} + +template +template +inline void List::retrieveResultsForLink( + typename Variable::Storage::ResultsType** result, + const Data::AreaLink* link) +{ + NextType::template retrieveResultsForLink(result, link); +} + +template +inline uint64_t List::memoryUsage() const +{ + return sizeof(ListType) + NextType::memoryUsage(); +} + +template +void List::buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const +{ + // Reset + results.data.columnIndex = 0; + + // The new filename + results.data.filename.clear(); + results.data.filename << results.data.output << SEP; + Category::FileLevelToStream(results.data.filename, fileLevel); + results.data.filename << '-'; + Category::PrecisionLevelToStream(results.data.filename, precision); + results.data.filename << ".txt"; + + // Ask to all variables + NextType::buildSurveyReport(results, dataLevel, fileLevel, precision); + + // If the column index is still equals to 0, that would mean we have nothing + // to do (there is no data to write) + if (results.data.columnIndex > 0) + { + results.saveToFile(dataLevel, fileLevel, precision); + } +} + +template +void List::buildAnnualSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision, + unsigned int numSpace) const +{ + // Reset + results.data.columnIndex = 0; + + // The new filename + results.data.filename.clear(); + results.data.filename << results.data.output << SEP; + Category::FileLevelToStream(results.data.filename, fileLevel); + results.data.filename << '-'; + Category::PrecisionLevelToStream(results.data.filename, precision); + results.data.filename.append(".txt", 4); + + // Ask to all variables + NextType::buildAnnualSurveyReport(results, dataLevel, fileLevel, precision, numSpace); + + // If the column index is still equals to 0, that would mean we have nothing + // to do (there is no data to write) + if (results.data.columnIndex > 0) + { + results.saveToFile(dataLevel, fileLevel, precision); + } +} + +template +void List::buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const +{ + // Reset + results.data.columnIndex = 0; + results.data.thermalCluster = nullptr; + results.data.area = nullptr; + results.data.link = nullptr; + results.variableCaption.clear(); + + // Building the digest + NextType::buildDigest(results, digestLevel, dataLevel); +} + +template +void List::exportSurveyResults(bool global, + const Yuni::String& output, + unsigned int numSpace, + IResultWriter& writer) +{ + using namespace Antares; + + // Infos + if (global) + { + logs.info(); // empty line + logs.checkpoint() << "Exporting the survey results..."; + } + else + { + logs.info() << "Exporting the annual results"; + } + + auto survey = std::make_shared(*pStudy, output, writer); + + // Year by year ? + survey->yearByYearResults = !global; + + if (global) + { + // alias to the type of the report builder + using Builder = SurveyReportBuilder; + // Building the survey results for each possible state + Builder::Run(*this, *survey); + + // Exporting the Grid (information about the study) + survey->exportGridInfos(); + + // Exporting the digest + // The digest must be exported after the real report because some values + // are computed at this moment. + Builder::RunDigest(*this, *survey, writer); + } + else + { + // alias to the type of the report builder + using Builder = SurveyReportBuilder; + // Building the survey results for each possible state + Builder::Run(*this, *survey, numSpace); + } +} + +} // namespace Container +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_CONTAINER_CONTAINER_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/STSbyGroup.h b/src/solver/variable/include/antares/solver/variable/economy/STSbyGroup.h new file mode 100644 index 0000000000..4e3ad6ee7c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/STSbyGroup.h @@ -0,0 +1,440 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/solver/variable/variable.h" + +namespace +{ +inline std::vector sortedUniqueGroups( + const std::vector& storages) +{ + std::set names; + for (const auto& cluster: storages) + { + names.insert(cluster.properties.groupName); + } + return {names.begin(), names.end()}; +} + +inline std::map giveNumbersToGroups( + const std::vector& groupNames) +{ + unsigned int groupNumber{0}; + std::map groupToNumbers; + for (const auto& name: groupNames) + { + groupToNumbers[name] = groupNumber++; + } + return groupToNumbers; +} +} // namespace + +namespace Antares::Solver::Variable::Economy +{ +struct VCardSTSbyGroup +{ + //! Caption + static std::string Caption() + { + return "STS by group"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "STS injections, withdrawals and levels"; + } + + //! The synhesis results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSTSbyGroup VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + // Nb of columns occupied by this variable in year-by-year results + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Variables related to short term storage groups +*/ +template +class STSbyGroup: public Variable::IVariable, NextT, VCardSTSbyGroup> +{ +private: + enum VariableType + { + injection = 0, + withdrawal = 1, + level = 2 + }; + +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSTSbyGroup VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + STSbyGroup(): + pValuesForTheCurrentYear(nullptr) + { + } + + ~STSbyGroup() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Building the vector of group names the clusters belong to. + groupNames_ = sortedUniqueGroups(area->shortTermStorage.storagesByIndex); + groupToNumbers_ = giveNumbersToGroups(groupNames_); + + nbColumns_ = groupNames_.size() * NB_COLS_PER_GROUP; + + if (nbColumns_) + { + AncestorType::pResults.resize(nbColumns_); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [nbColumns_]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != nbColumns_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != nbColumns_; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return nbColumns_ * ResultsType::count; + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != nbColumns_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Here we perform time-aggregations : + // --------------------------------- + // For a given MC year, from hourly results we compute daily, weekly, monthly and annual + // results by aggregation operations (averages or sums). + // Caution : + // - level results are stored in columns of which indices satisfy : col_index % 3 == 2. + // They are time-aggregated by means of averages + // - injection and withdrawal results are stored in columns of which indices + // satisfy : col_index % 3 != 2. + // They are time-aggregated by means of sums. + + for (unsigned int column = 0; column < nbColumns_; column++) + { + switch (column % NB_COLS_PER_GROUP) + { + case VariableType::level: + pValuesForTheCurrentYear[numSpace][column] + .computeAveragesForCurrentYearFromHourlyResults(); + break; + case VariableType::injection: + case VariableType::withdrawal: + pValuesForTheCurrentYear[numSpace][column].computeStatisticsForTheCurrentYear(); + break; + } + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + // Here we compute synthesis : + // for each interval of any time period results (hourly, daily, weekly, ...), + // we compute the average over all MC years : + // For instance : + // - we compute the average of the results of the first hour over all MC years + // - or we compute the average of the results of the n-th day over all MC years + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[numSpace], + AncestorType::pResults, + numSpaceToYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + using namespace Antares::Data::ShortTermStorage; + const auto& shortTermStorage = state.area->shortTermStorage; + + uint clusterIndex = 0; + for (const auto& cluster: shortTermStorage.storagesByIndex) + { + unsigned int groupNumber = groupToNumbers_[cluster.properties.groupName]; + const auto& result = state.hourlyResults->ShortTermStorage[state.hourInTheWeek]; + // Injection + pValuesForTheCurrentYear[numSpace][NB_COLS_PER_GROUP * groupNumber + + VariableType::injection][state.hourInTheYear] + += result.injection[clusterIndex]; + + // Withdrawal + pValuesForTheCurrentYear[numSpace][NB_COLS_PER_GROUP * groupNumber + + VariableType::withdrawal][state.hourInTheYear] + += result.withdrawal[clusterIndex]; + + // Levels + pValuesForTheCurrentYear[numSpace][NB_COLS_PER_GROUP * groupNumber + + VariableType::level][state.hourInTheYear] + += result.level[clusterIndex]; + + clusterIndex++; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * nbColumns_ + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * nbColumns_ * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + std::string caption(unsigned int column) const + { + static const std::vector VAR_POSSIBLE_KINDS = {"INJECTION", + "WITHDRAWAL", + "LEVEL"}; + const std::string& groupName = groupNames_[column / NB_COLS_PER_GROUP]; + const std::string& variableKind = VAR_POSSIBLE_KINDS[column % NB_COLS_PER_GROUP]; + return groupName + "_" + variableKind; + } + + std::string unit(unsigned int column) const + { + switch (column % NB_COLS_PER_GROUP) + { + case VariableType::level: + return "MWh"; + case VariableType::injection: + case VariableType::withdrawal: + return "MW"; + default: + return "error"; + } + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (!AncestorType::isPrinted[0]) + { + return; + } + + for (unsigned int column = 0; column < nbColumns_; column++) + { + results.variableCaption = caption(column); + results.variableUnit = unit(column); + pValuesForTheCurrentYear[numSpace][column] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + + void buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const + { + // Building synthesis results + // ------------------------------ + + if (AncestorType::isPrinted[0]) + { + // And only if we match the current data level _and_ precision level + if ((dataLevel & VCardType::categoryDataLevel) + && (fileLevel & VCardType::categoryFileLevel) && (precision & VCardType::precision)) + { + results.isCurrentVarNA[0] = AncestorType::isNonApplicable[0]; + + for (unsigned int column = 0; column < nbColumns_; column++) + { + results.variableCaption = caption(column); + results.variableUnit = unit(column); + AncestorType::pResults[column] + .template buildSurveyReport( + results, + AncestorType::pResults[column], + dataLevel, + fileLevel, + precision); + } + } + } + // Ask to the next item in the static list to export its results as well + NextType::buildSurveyReport(results, dataLevel, fileLevel, precision); + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t nbColumns_ = 0; + std::vector groupNames_; // Names of group containing the clusters of the area + std::map groupToNumbers_; // Gives to each group (of area) a number + const int NB_COLS_PER_GROUP = 3; // Injection + withdrawal + levels = 3 variables + unsigned int pNbYearsParallel; + +}; // class STSbyGroup + +} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/include/antares/solver/variable/economy/STStorageCashFlowByCluster.h b/src/solver/variable/include/antares/solver/variable/economy/STStorageCashFlowByCluster.h new file mode 100644 index 0000000000..eb2eaa48b9 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/STStorageCashFlowByCluster.h @@ -0,0 +1,307 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardSTstorageCashFlowByCluster +{ + //! Caption + static std::string Caption() + { + return "STS Cashflow By Cluster"; + } + + //! Unit + static std::string Unit() + { + return "CashFlow - Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Cash Flow by short term storage"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSTstorageCashFlowByCluster VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & Category::FileLevel::de_sts; + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Energy generated by short term storage clusters +*/ +template +class STstorageCashFlowByCluster: public Variable::IVariable, + NextT, + VCardSTstorageCashFlowByCluster> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSTstorageCashFlowByCluster VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + static constexpr int count = 1 + NextT::count; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + STstorageCashFlowByCluster() = default; + + ~STstorageCashFlowByCluster() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + nbClusters_ = area->shortTermStorage.count(); + if (nbClusters_) + { + AncestorType::pResults.resize(nbClusters_); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [nbClusters_]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != nbClusters_; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return nbClusters_ * ResultsType::count; + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int clusterIndex = 0; clusterIndex != nbClusters_; ++clusterIndex) + { + pValuesForTheCurrentYear[numSpace][clusterIndex].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Compute all statistics from hourly results for the current year (daily, weekly, + // monthly, ...) + pValuesForTheCurrentYear[numSpace][clusterIndex].computeStatisticsForTheCurrentYear(); + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Merge all those values with the global results + AncestorType::pResults[clusterIndex].merge( + numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][clusterIndex]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + unsigned int hourInYear = state.hourInTheYear; + for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); + ++clusterIndex) + { + const auto& stsHourlyResults = state.hourlyResults + ->ShortTermStorage[state.hourInTheWeek]; + // ST storage injection for the current cluster and this hour + // CashFlow[h] = (withdrawal - injection) * MRG. PRICE + pValuesForTheCurrentYear[numSpace][clusterIndex].hour[hourInYear] + = (stsHourlyResults.withdrawal[clusterIndex] + - stsHourlyResults.injection[clusterIndex]) + * (-state.hourlyResults->CoutsMarginauxHoraires[state.hourInTheWeek]); + // Note: The marginal price provided by the solver is negative (naming convention). + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * nbClusters_ * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& shortTermStorage = results.data.area->shortTermStorage; + + // Write the data for the current year + uint clusterIndex = 0; + for (const auto& cluster: shortTermStorage.storagesByIndex) + { + // Write the data for the current year + results.variableCaption = cluster.properties.name; + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][clusterIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + + clusterIndex++; + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear = nullptr; + size_t nbClusters_ = 0; + unsigned int pNbYearsParallel = 0; + +}; // class STstorageCashFlowByCluster + +} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/include/antares/solver/variable/economy/STStorageInjectionByCluster.h b/src/solver/variable/include/antares/solver/variable/economy/STStorageInjectionByCluster.h new file mode 100644 index 0000000000..7d7646b5c8 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/STStorageInjectionByCluster.h @@ -0,0 +1,307 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardSTstorageInjectionByCluster +{ + //! Caption + static std::string Caption() + { + return "STS inj by plant"; + } + + //! Unit + static std::string Unit() + { + return "P-injection - MW"; + } + + //! The short description of the variable + static std::string Description() + { + return "Energy injected by ST storage clusters"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSTstorageInjectionByCluster VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de_sts); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Energy generated by short term storage clusters +*/ +template +class STstorageInjectionByCluster: public Variable::IVariable, + NextT, + VCardSTstorageInjectionByCluster> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSTstorageInjectionByCluster VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + STstorageInjectionByCluster(): + pValuesForTheCurrentYear(nullptr) + { + } + + ~STstorageInjectionByCluster() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + nbClusters_ = area->shortTermStorage.count(); + if (nbClusters_) + { + AncestorType::pResults.resize(nbClusters_); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [nbClusters_]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != nbClusters_; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return nbClusters_ * ResultsType::count; + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Compute all statistics from hourly results for the current year (daily, weekly, + // monthly, ...) + pValuesForTheCurrentYear[numSpace][clusterIndex].computeStatisticsForTheCurrentYear(); + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Merge all those values with the global results + AncestorType::pResults[clusterIndex].merge( + numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][clusterIndex]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); + ++clusterIndex) + { + // ST storage injection for the current cluster and this hour + pValuesForTheCurrentYear[numSpace][clusterIndex].hour[state.hourInTheYear] + = state.hourlyResults->ShortTermStorage[state.hourInTheWeek].injection[clusterIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * nbClusters_ * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& shortTermStorage = results.data.area->shortTermStorage; + + // Write the data for the current year + uint clusterIndex = 0; + for (const auto& cluster: shortTermStorage.storagesByIndex) + { + // Write the data for the current year + results.variableCaption = cluster.properties.name; + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][clusterIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + + clusterIndex++; + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t nbClusters_; + unsigned int pNbYearsParallel; + +}; // class STstorageInjectionByCluster + +} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/include/antares/solver/variable/economy/STStorageLevelsByCluster.h b/src/solver/variable/include/antares/solver/variable/economy/STStorageLevelsByCluster.h new file mode 100644 index 0000000000..fff57c33c7 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/STStorageLevelsByCluster.h @@ -0,0 +1,308 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardSTstorageLevelsByCluster +{ + //! Caption + static std::string Caption() + { + return "STS lvl by plant"; + } + + //! Unit + static std::string Unit() + { + return "Levels - MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Levels by ST storage clusters"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSTstorageLevelsByCluster VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de_sts); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Energy generated by short term storage clusters +*/ +template +class STstorageLevelsByCluster: public Variable::IVariable, + NextT, + VCardSTstorageLevelsByCluster> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSTstorageLevelsByCluster VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + STstorageLevelsByCluster(): + pValuesForTheCurrentYear(nullptr) + { + } + + ~STstorageLevelsByCluster() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + nbClusters_ = area->shortTermStorage.count(); + if (nbClusters_) + { + AncestorType::pResults.resize(nbClusters_); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [nbClusters_]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != nbClusters_; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return nbClusters_ * ResultsType::count; + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Compute all statistics from hourly results for the current year (daily, weekly, + // monthly, ...) + pValuesForTheCurrentYear[numSpace][clusterIndex] + .computeAveragesForCurrentYearFromHourlyResults(); + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Merge all those values with the global results + AncestorType::pResults[clusterIndex].merge( + numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][clusterIndex]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); + ++clusterIndex) + { + // ST storage levels for the current cluster and this hour + pValuesForTheCurrentYear[numSpace][clusterIndex].hour[state.hourInTheYear] + = state.hourlyResults->ShortTermStorage[state.hourInTheWeek].level[clusterIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * nbClusters_ * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& shortTermStorage = results.data.area->shortTermStorage; + + // Write the data for the current year + uint clusterIndex = 0; + for (const auto& cluster: shortTermStorage.storagesByIndex) + { + // Write the data for the current year + results.variableCaption = cluster.properties.name; + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][clusterIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + + clusterIndex++; + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t nbClusters_; + unsigned int pNbYearsParallel; + +}; // class STstorageLevelsByCluster + +} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/include/antares/solver/variable/economy/STStorageWithdrawalByCluster.h b/src/solver/variable/include/antares/solver/variable/economy/STStorageWithdrawalByCluster.h new file mode 100644 index 0000000000..998cc3e9ed --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/STStorageWithdrawalByCluster.h @@ -0,0 +1,307 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardSTstorageWithdrawalByCluster +{ + //! Caption + static std::string Caption() + { + return "STS withdrawal by plant"; + } + + //! Unit + static std::string Unit() + { + return "P-withdrawal - MW"; + } + + //! The short description of the variable + static std::string Description() + { + return "Energy withdrawn by ST storage clusters"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSTstorageWithdrawalByCluster VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de_sts); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Energy generated by short term storage clusters +*/ +template +class STstorageWithdrawalByCluster: public Variable::IVariable, + NextT, + VCardSTstorageWithdrawalByCluster> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSTstorageWithdrawalByCluster VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + STstorageWithdrawalByCluster(): + pValuesForTheCurrentYear(nullptr) + { + } + + ~STstorageWithdrawalByCluster() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + nbClusters_ = area->shortTermStorage.count(); + if (nbClusters_) + { + AncestorType::pResults.resize(nbClusters_); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [nbClusters_]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != nbClusters_; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return nbClusters_ * ResultsType::count; + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != nbClusters_; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Compute all statistics from hourly results for the current year (daily, weekly, + // monthly, ...) + pValuesForTheCurrentYear[numSpace][clusterIndex].computeStatisticsForTheCurrentYear(); + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int clusterIndex = 0; clusterIndex < nbClusters_; ++clusterIndex) + { + // Merge all those values with the global results + AncestorType::pResults[clusterIndex].merge( + numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][clusterIndex]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + for (uint clusterIndex = 0; clusterIndex != state.area->shortTermStorage.count(); + ++clusterIndex) + { + // ST storage withdrawal for the current cluster and this hour + pValuesForTheCurrentYear[numSpace][clusterIndex].hour[state.hourInTheYear] + = state.hourlyResults->ShortTermStorage[state.hourInTheWeek].withdrawal[clusterIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * nbClusters_ + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * nbClusters_ * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& shortTermStorage = results.data.area->shortTermStorage; + + // Write the data for the current year + uint clusterIndex = 0; + for (const auto& cluster: shortTermStorage.storagesByIndex) + { + // Write the data for the current year + results.variableCaption = cluster.properties.name; + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][clusterIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + + clusterIndex++; + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t nbClusters_; + unsigned int pNbYearsParallel; + +}; // class STstorageWithdrawalByCluster + +} // End namespace Antares::Solver::Variable::Economy diff --git a/src/solver/variable/include/antares/solver/variable/economy/all.h b/src/solver/variable/include/antares/solver/variable/economy/all.h new file mode 100644 index 0000000000..b7a62eb6bf --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/all.h @@ -0,0 +1,262 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_ALL_H__ +#define __SOLVER_VARIABLE_ECONOMY_ALL_H__ + +#include "antares/solver/variable/variable.h" + +#include "../area.h" +#include "../bindConstraints.h" +#include "../commons/hydro.h" +#include "../commons/join.h" +#include "../commons/load.h" +#include "../commons/miscGenMinusRowPSP.h" +#include "../commons/psp.h" +#include "../commons/rowBalance.h" +#include "../commons/solar.h" +#include "../commons/spatial-aggregate.h" +#include "../commons/wind.h" +#include "../setofareas.h" +#include "balance.h" +#include "price.h" + +// For General values +#include "avail-dispatchable-generation.h" +#include "dispatchable-generation-margin.h" +#include "dispatchableGeneration.h" +#include "domesticUnsuppliedEnergy.h" +#include "dtgMarginAfterCsr.h" +#include "hydroCost.h" +#include "hydrostorage.h" +#include "inflow.h" +#include "localMatchingRuleViolations.h" +#include "lold.h" +#include "lolp.h" +#include "max-mrg.h" +#include "nbOfDispatchedUnits.h" +#include "nonProportionalCost.h" +#include "operatingCost.h" +#include "overallCost.h" +#include "overflow.h" +#include "pumping.h" +#include "renewableGeneration.h" +#include "reservoirlevel.h" +#include "spilledEnergy.h" +#include "spilledEnergyAfterCSR.h" +#include "thermalAirPollutantEmissions.h" +#include "unsupliedEnergy.h" +#include "waterValue.h" + +// By thermal plant +#include "nbOfDispatchedUnitsByPlant.h" +#include "npCostByDispatchablePlant.h" +#include "productionByDispatchablePlant.h" +#include "profitByPlant.h" + +// By RES plant +#include "STSbyGroup.h" +#include "STStorageCashFlowByCluster.h" +#include "STStorageInjectionByCluster.h" +#include "STStorageLevelsByCluster.h" +#include "STStorageWithdrawalByCluster.h" +#include "productionByRenewablePlant.h" + +// Output variables associated to links +#include "links.h" + +// Output variables associated to binding constraints +#include "bindingConstraints/bindingConstraintsMarginalCost.h" + +namespace Antares::Solver::Variable::Economy +{ + +/*! +** \brief All variables for a single area (economy) +*/ +typedef // Prices + OverallCost // Overall Cost (Op. Cost + Unsupplied Eng.) + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + VariablesPerArea; + +/*! +** \brief All variables for a single set of areas (economy) +*/ +typedef // Prices + Common::SpatialAggregate< + OverallCost, + Common::SpatialAggregate< + OperatingCost, + Common::SpatialAggregate< + Price, + // Thermal pollutants + Common::SpatialAggregate< + ThermalAirPollutantEmissions, + // Production by thermal cluster + Common::SpatialAggregate< + Balance, + // Misc Gen. + Common::SpatialAggregate< + RowBalance, + Common::SpatialAggregate< + PSP, + Common::SpatialAggregate< + MiscGenMinusRowPSP, + // Time series + Common::SpatialAggregate< + TimeSeriesValuesLoad, + Common::SpatialAggregate< + TimeSeriesValuesHydro, + Common::SpatialAggregate< + TimeSeriesValuesWind, + Common::SpatialAggregate< + TimeSeriesValuesSolar, + // Other + Common::SpatialAggregate< + DispatchableGeneration, + Common::SpatialAggregate< + RenewableGeneration, + Common::SpatialAggregate< + HydroStorage, + Common::SpatialAggregate< + Pumping, + Common::SpatialAggregate< + ReservoirLevel, + Common::SpatialAggregate< + Inflows, + Common::SpatialAggregate< + Overflows, + Common::SpatialAggregate< + WaterValue, + Common::SpatialAggregate< + HydroCost, + Common::SpatialAggregate< + UnsupliedEnergy, + Common::SpatialAggregate< + DomesticUnsuppliedEnergy, + Common::SpatialAggregate< + LMRViolations, + Common::SpatialAggregate< + SpilledEnergy, + Common::SpatialAggregate< + SpilledEnergyAfterCSR, + // LOLD + Common::SpatialAggregate< + LOLD, + Common::SpatialAggregate< + LOLP, + Common::SpatialAggregate< + AvailableDispatchGen, + Common::SpatialAggregate< + DispatchableGenMargin, + Common::SpatialAggregate< + DtgMarginCsr, + Common::SpatialAggregate< + Marge, + + // Detail Prices + Common::SpatialAggregate< + NonProportionalCost, // MBO + // 13/05/2014 + // - + // refs: + // #21 + + // Number Of Dispatched Units + Common::SpatialAggregate< + NbOfDispatchedUnits // MBO + // 25/02/2016 + // - + // refs: + // #55 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + VariablesPerSetOfAreas; + +typedef BindingConstMarginCost< // Marginal cost for a binding constraint + Container::EndOfList // End of variable list + > + + VariablesPerBindingConstraints; + +typedef Variable::Join< + // Variables for each area / links attached to the areas + Variable::Areas, + // Variables for each set of areas + Variable::Join, + // Variables for each binding constraint + Variable::BindingConstraints>> + ItemList; + +/*! +** \brief All variables for a simulation (economy) +*/ +typedef Container::List AllVariables; + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_ALL_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/avail-dispatchable-generation.h b/src/solver/variable/include/antares/solver/variable/economy/avail-dispatchable-generation.h new file mode 100644 index 0000000000..86b0711d16 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/avail-dispatchable-generation.h @@ -0,0 +1,291 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_AvailableDispatchGen_H__ +#define __SOLVER_VARIABLE_ECONOMY_AvailableDispatchGen_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardAvailableDispatchGen +{ + //! Caption + static std::string Caption() + { + return "AVL DTG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Available dispatchable generation"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardAvailableDispatchGen VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal AvailableDispatchGen +*/ +template +class AvailableDispatchGen + : public Variable::IVariable, NextT, VCardAvailableDispatchGen> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardAvailableDispatchGen VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~AvailableDispatchGen() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average thoughout all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Somme de toutes les productions disponibles pour l'ensemble des + // paliers thermiques (+must-run) + pValuesForTheCurrentYear[numSpace].reset(); + for (const auto& cluster: pArea->thermal.list.each_enabled()) + { + const auto& availableProduction = cluster->series.getColumn(year); + for (unsigned int hour = 0; hour != cluster->series.timeSeries.height; ++hour) + { + pValuesForTheCurrentYear[numSpace].hour[hour] += availableProduction[hour]; + } + } + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + // + Data::Area* pArea; + unsigned int pNbYearsParallel; + +}; // class AvailableDispatchGen + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_AvailableDispatchGen_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/balance.h b/src/solver/variable/include/antares/solver/variable/economy/balance.h new file mode 100644 index 0000000000..8547c075ae --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/balance.h @@ -0,0 +1,303 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_BALANCE_H__ +#define __SOLVER_VARIABLE_ECONOMY_BALANCE_H__ + +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardBalance +{ + //! Caption + static std::string Caption() + { + return "BALANCE"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Nodal energy balance, throughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardBalance VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal Balance +*/ +template +class Balance: public Variable::IVariable, NextT, VCardBalance> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardBalance VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~Balance() + { + delete[] pValuesForTheCurrentYear; + delete[] bilanPays; + delete[] pInterco; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + bilanPays = nullptr; + pInterco = nullptr; + bilanPays = new double[pNbYearsParallel]; + pInterco = new long[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + bilanPays[numSpace] = 0.; + pInterco[numSpace] = 0; + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // A single reset is enough + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + bilanPays[numSpace] = 0.; + pInterco[numSpace] = state.problemeHebdo->IndexDebutIntercoOrigine[state.area->index]; + while (pInterco[numSpace] >= 0) + { + bilanPays[numSpace] += state.ntc.ValeurDuFlux[pInterco[numSpace]]; + pInterco[numSpace] = state.problemeHebdo + ->IndexSuivantIntercoOrigine[pInterco[numSpace]]; + } + pInterco[numSpace] = state.problemeHebdo->IndexDebutIntercoExtremite[state.area->index]; + while (pInterco[numSpace] >= 0) + { + bilanPays[numSpace] -= state.ntc.ValeurDuFlux[pInterco[numSpace]]; + pInterco[numSpace] = state.problemeHebdo + ->IndexSuivantIntercoExtremite[pInterco[numSpace]]; + } + + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = bilanPays[numSpace]; + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + double* bilanPays; + long* pInterco; + + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class Balance + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_BALANCE_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h b/src/solver/variable/include/antares/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h new file mode 100644 index 0000000000..8a1f97676f --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/bindingConstraints/bindingConstraintsMarginalCost.h @@ -0,0 +1,482 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include "antares/study/binding_constraint/BindingConstraint.h" + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardBindingConstMarginCost +{ + //! Caption + static std::string Caption() + { + return "BC. MARG. COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Marginal cost for binding constraints"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::bindingConstraint; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::bc); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable + static constexpr int columnCount = 1; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 1; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/* + Marginal cost associated to binding constraints : + Suppose that the BC is hourly, + - if binding constraint is not saturated (rhs is not reached) for a given hour, the value is 0; + - if binding constraint is saturated (rhs is reached), the value is the total benefit (�/MW) for + the system that would result in increasing the BC's rhs of 1 MW. +*/ +template +class BindingConstMarginCost + : public Variable::IVariable, NextT, VCardBindingConstMarginCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardBindingConstMarginCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + BindingConstMarginCost() = default; + + ~BindingConstMarginCost() + { + if (pValuesForTheCurrentYear) + { + delete[] pValuesForTheCurrentYear; + } + } + + void simulationBegin() + { + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Statistics thoughout all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void setAssociatedBindConstraint(std::shared_ptr bc_ptr) + { + associatedBC_ = bc_ptr; + } + + void setBindConstraintsCount(uint bcCount) + { + nbCount_ = bcCount; + } + + size_t getMaxNumberColumns() const + { + return nbCount_ * ResultsType::count; + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + if (isInitialized()) + { + // Compute statistics for the current year depending on + // the BC type (hourly, daily, weekly) + using namespace Data; + switch (associatedBC_->type()) + { + case BindingConstraint::typeHourly: + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); + break; + case BindingConstraint::typeDaily: + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromDailyResults(); + break; + case BindingConstraint::typeWeekly: + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromWeeklyResults(); + break; + case BindingConstraint::typeUnknown: + case BindingConstraint::typeMax: + break; + } + } + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void weekBegin(State& state) + { + if (isInitialized()) + { + auto numSpace = state.numSpace; + // For daily binding constraints, getting daily marginal price + using namespace Data; + switch (associatedBC_->type()) + { + case BindingConstraint::typeHourly: + case BindingConstraint::typeUnknown: + case BindingConstraint::typeMax: + break; + + case BindingConstraint::typeDaily: + { + int dayInTheYear = state.weekInTheYear * 7; + for (int dayInTheWeek = 0; dayInTheWeek < 7; dayInTheWeek++) + { + pValuesForTheCurrentYear[numSpace].day[dayInTheYear] + -= state.problemeHebdo + ->ResultatsContraintesCouplantes[associatedBC_][dayInTheWeek]; + + dayInTheYear++; + } + break; + } + + // For weekly binding constraints, getting weekly marginal price + case BindingConstraint::typeWeekly: + { + uint weekInTheYear = state.weekInTheYear; + double weeklyValue = -state.problemeHebdo + ->ResultatsContraintesCouplantes[associatedBC_][0]; + + pValuesForTheCurrentYear[numSpace].week[weekInTheYear] = weeklyValue; + + int dayInTheYear = state.weekInTheYear * 7; + for (int dayInTheWeek = 0; dayInTheWeek < 7; dayInTheWeek++) + { + pValuesForTheCurrentYear[numSpace].day[dayInTheYear] = weeklyValue; + dayInTheYear++; + } + break; + } + } + } + NextType::weekBegin(state); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + NextType::hourForEachArea(state, numSpace); + } + + void weekForEachArea(State& state, unsigned int numSpace) + { + NextType::weekForEachArea(state, numSpace); + } + + template + static void retrieveResultsForArea(typename Storage::ResultsType** result, + const Data::Area* area) + { + // Next variable + NextType::template retrieveResultsForArea(result, area); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + NextType::buildDigest(results, digestLevel, dataLevel); + } + + template + static void simulationEndSpatialAggregates(V& allVars) + { + NextType::template simulationEndSpatialAggregates(allVars); + } + + template + static void computeSpatialAggregatesSummary( + V& allVars, + std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + NextType::template computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); + } + + void beforeYearByYearExport(uint year, uint numSpace) + { + NextType::beforeYearByYearExport(year, numSpace); + } + + template + static void computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace) + { + NextType::template computeSpatialAggregateWith(out, area, numSpace); + } + + template + static void retrieveResultsForLink(typename Storage::ResultsType** result, + const Data::AreaLink* link) + { + NextType::template retrieveResultsForLink(result, link); + } + + template + static void retrieveResultsForThermalCluster( + typename Storage::ResultsType** result, + const Data::ThermalCluster* cluster) + { + NextType::template retrieveResultsForThermalCluster(result, cluster); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + if (isInitialized()) + { + auto numSpace = state.numSpace; + if (associatedBC_->type() == Data::BindingConstraint::typeHourly) + { + pValuesForTheCurrentYear[numSpace][hourInTheYear] + -= state.problemeHebdo + ->ResultatsContraintesCouplantes[associatedBC_][state.hourInTheWeek]; + } + } + + NextType::hourEnd(state, hourInTheYear); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport( + SurveyResults& results, + int fileLevel, + int precision /* printed results : hourly, daily, weekly, ...*/, + unsigned int numSpace) const + { + if (!(precision & associatedBC_->yearByYearFilter())) + { + return; + } + + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA[0] = isCurrentOutputNonApplicable(precision); + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = getBindConstraintCaption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + + void buildSurveyReport(SurveyResults& results, + int dataLevel, + int fileLevel, + int precision) const + { + // Building syntheses results + // ------------------------------ + if (precision & associatedBC_->yearByYearFilter()) + { + // And only if we match the current data level _and_ precision level + if ((dataLevel & VCardType::categoryDataLevel) + && (fileLevel & VCardType::categoryFileLevel) && (precision & VCardType::precision)) + { + results.isPrinted = AncestorType::isPrinted; + results.isCurrentVarNA[0] = isCurrentOutputNonApplicable(precision); + results.variableCaption = getBindConstraintCaption(); + + VariableAccessorType::template BuildSurveyReport(results, + AncestorType::pResults, + dataLevel, + fileLevel, + precision, + false); + } + } + NextType::buildSurveyReport(results, dataLevel, fileLevel, precision); + } + +private: + // Private methods + // --------------- + std::string getBindConstraintCaption() const + { + std::string mathOperator( + Antares::Data::BindingConstraint::MathOperatorToCString(associatedBC_->operatorType())); + return std::string() + associatedBC_->name().c_str() + " (" + mathOperator + ")"; + } + + bool isInitialized() + { + return associatedBC_ != nullptr; + } + + bool isCurrentOutputNonApplicable(int precision) const + { + using namespace Antares::Data; + // The current marginal prices to print becomes non applicable if they have a precision + // (hour, day, week, ...) smaller than the associated binding constraint granularity. + // Ex : if the BC is daily and we try to print hourly associated marginal prices, + // then these prices are set to N/A + switch (associatedBC_->type()) + { + case BindingConstraint::typeUnknown: + case BindingConstraint::typeMax: + return true; + default: + const auto precision_bc = 1 << (associatedBC_->type() - 1); + return precision < precision_bc; + } + } + + // Private data mambers + // ---------------------- + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear = nullptr; + unsigned int pNbYearsParallel = 0; + std::shared_ptr associatedBC_ = nullptr; + uint nbCount_ = 0; // Number of inequality BCs + +}; // class BindingConstMarginCost + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares diff --git a/src/solver/variable/include/antares/solver/variable/economy/dispatchable-generation-margin.h b/src/solver/variable/include/antares/solver/variable/economy/dispatchable-generation-margin.h new file mode 100644 index 0000000000..76b2b5418a --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/dispatchable-generation-margin.h @@ -0,0 +1,295 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_DispatchableGenMargin_H__ +#define __SOLVER_VARIABLE_ECONOMY_DispatchableGenMargin_H__ + +#include +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardDispatchableGenMargin +{ + //! Caption + static std::string Caption() + { + return "DTG MRG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Dispatchable Generation Margin"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardDispatchableGenMargin VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal DispatchableGenMargin +*/ +template +class DispatchableGenMargin + : public Variable::IVariable, NextT, VCardDispatchableGenMargin> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardDispatchableGenMargin VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~DispatchableGenMargin() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average thoughout all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] += state.scratchpad + ->dispatchableGenerationMargin + [state.hourInTheWeek]; + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + template + inline const double* retrieveHourlyResultsForCurrentYear(unsigned int numSpace) const + { + typedef RetrieveResultsAssignment< + Yuni::Static::Type::StrictlyEqual::Yes> + AssignT; + return (AssignT::Yes) + ? Memory::RawPointer(pValuesForTheCurrentYear[numSpace].hour) + : NextType::template retrieveHourlyResultsForCurrentYear(numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + Data::Area* pArea; + unsigned int pNbYearsParallel; + +}; // class DispatchableGenMargin + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_DispatchableGenMargin_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/dispatchableGeneration.h b/src/solver/variable/include/antares/solver/variable/economy/dispatchableGeneration.h new file mode 100644 index 0000000000..2c9b21046c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/dispatchableGeneration.h @@ -0,0 +1,329 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_DispatchableGeneration_H__ +#define __SOLVER_VARIABLE_ECONOMY_DispatchableGeneration_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardDispatchableGeneration +{ + //! Caption + static std::string Caption() + { + return "Dispatch. Gen."; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Value of all the dispatchable generation throughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardDispatchableGeneration VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 10; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType[columnCount]; + typedef IntermediateValuesBaseType* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + + struct Multiple + { + static std::string Caption(const unsigned int indx) + { + switch (indx) + { + case 0: + return "NUCLEAR"; + case 1: + return "LIGNITE"; + case 2: + return "COAL"; + case 3: + return "GAS"; + case 4: + return "OIL"; + case 5: + return "MIX. FUEL"; + case 6: + return "MISC. DTG"; + case 7: + return "MISC. DTG 2"; + case 8: + return "MISC. DTG 3"; + case 9: + return "MISC. DTG 4"; + + default: + return ""; + } + } + + static std::string Unit([[maybe_unused]] const unsigned int indx) + { + return VCardDispatchableGeneration::Unit(); + } + }; +}; // class VCard + +/*! +** \brief Marginal DispatchableGeneration +*/ +template +class DispatchableGeneration + : public Variable::IVariable, NextT, VCardDispatchableGeneration> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardDispatchableGeneration VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~DispatchableGeneration() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); + } + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + results[i].initializeFromStudy(study); + results[i].reset(); + } + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + VariableAccessorType::template ComputeStatistics( + pValuesForTheCurrentYear[numSpace]); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[numSpace], + AncestorType::pResults, + numSpaceToYear[numSpace]); + } + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + auto area = state.area; + auto& thermal = state.thermal; + for (auto& cluster: area->thermal.list.each_enabled()) + { + pValuesForTheCurrentYear[numSpace][cluster->groupID][state.hourInTheYear] + += thermal[area->index].thermalClustersProductions[cluster->areaWideIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // The current variable is actually a multiple-variable. + results.isCurrentVarNA = AncestorType::isNonApplicable; + + for (uint i = 0; i != VCardType::columnCount; ++i) + { + if (AncestorType::isPrinted[i]) + { + // Write the data for the current year + results.variableCaption = VCardType::Multiple::Caption(i); + results.variableUnit = VCardType::Multiple::Unit(i); + pValuesForTheCurrentYear[numSpace][i] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + results.isCurrentVarNA++; + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class DispatchableGeneration + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_DispatchableGeneration_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/domesticUnsuppliedEnergy.h b/src/solver/variable/include/antares/solver/variable/economy/domesticUnsuppliedEnergy.h new file mode 100644 index 0000000000..ab73f1a2b2 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/domesticUnsuppliedEnergy.h @@ -0,0 +1,285 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ +#define __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardDomesticUnsuppliedEnergy +{ + //! Caption + static std::string Caption() + { + return "DENS"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Domestic Unsupplied Energy (demand that cannot be satisfied without " + "interconnections/links)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardDomesticUnsuppliedEnergy VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall DomesticUnsuppliedEnergy emissions expected from all +** the thermal dispatchable clusters +*/ +template +class DomesticUnsuppliedEnergy: public Variable::IVariable, + NextT, + VCardDomesticUnsuppliedEnergy> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardDomesticUnsuppliedEnergy VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~DomesticUnsuppliedEnergy() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Total DomesticUnsuppliedEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = state.hourlyResults + ->ValeursHorairesDENS + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class DomesticUnsuppliedEnergy + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/dtgMarginAfterCsr.h b/src/solver/variable/include/antares/solver/variable/economy/dtgMarginAfterCsr.h new file mode 100644 index 0000000000..d748b9ac4c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/dtgMarginAfterCsr.h @@ -0,0 +1,272 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ +#define __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardDtgMarginCsr +{ + //! Caption + static std::string Caption() + { + return "DTG MRG CSR"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Dispatchable Generation Margin (after CSR optimization)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardDtgMarginCsr VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall DtgMarginCsr emissions expected from all +** the thermal dispatchable clusters +*/ +template +class DtgMarginCsr: public Variable::IVariable, NextT, VCardDtgMarginCsr> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardDtgMarginCsr VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + + ~DtgMarginCsr() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Total DtgMarginCsr + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = state.hourlyResults + ->ValeursHorairesDtgMrgCsr + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class DtgMarginCsr + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/hydroCost.h b/src/solver/variable/include/antares/solver/variable/economy/hydroCost.h new file mode 100644 index 0000000000..1edf42e14f --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/hydroCost.h @@ -0,0 +1,282 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_HydroCost_H__ +#define __SOLVER_VARIABLE_ECONOMY_HydroCost_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardHydroCost +{ + //! Caption + static std::string Caption() + { + return "H. COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydro Cost throughout all MC years, of all the thermal dispatchable clusters"; + } + + //! The expecte results + typedef Results>>>, + R::AllYears::Average> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardHydroCost VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Hydro costs +*/ +template +class HydroCost: public Variable::IVariable, NextT, VCardHydroCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardHydroCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~HydroCost() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Setting the pumping efficiency + pPumpRatio = area->hydro.pumpingEfficiency; + + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Hydro costs : storage and pumping + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + += state.hourlyResults->valeurH2oHoraire[state.hourInTheWeek] + * (state.hourlyResults->TurbinageHoraire[state.hourInTheWeek] + - pPumpRatio * state.hourlyResults->PompageHoraire[state.hourInTheWeek]); + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + double pPumpRatio; + +}; // class HydroCost + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_HydroCost_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/hydrostorage.h b/src/solver/variable/include/antares/solver/variable/economy/hydrostorage.h new file mode 100644 index 0000000000..be56b970b6 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/hydrostorage.h @@ -0,0 +1,281 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_HydroStorage_H__ +#define __SOLVER_VARIABLE_ECONOMY_HydroStorage_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardHydroStorage +{ + //! Caption + static std::string Caption() + { + return "H. STOR"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydro Storage Generation"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardHydroStorage VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall HydroStorage emissions expected from all +** the thermal dispatchable clusters +*/ +template +class HydroStorage: public Variable::IVariable, NextT, VCardHydroStorage> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardHydroStorage VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~HydroStorage() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily, weekly, monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Total HydroStorage emissions + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = + // Current Hydro Storage generation + state.hourlyResults->TurbinageHoraire[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class HydroStorage + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_HydroStorage_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/inflow.h b/src/solver/variable/include/antares/solver/variable/economy/inflow.h new file mode 100644 index 0000000000..136bd8410e --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/inflow.h @@ -0,0 +1,284 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_Inflows_H__ +#define __SOLVER_VARIABLE_ECONOMY_Inflows_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardInflows +{ + //! Caption + static std::string Caption() + { + return "H. INFL"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydraulic inflows"; + } + + //! The expected results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardInflows VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Inflows +*/ +template +class Inflows: public Variable::IVariable, NextT, VCardInflows> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardInflows VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~Inflows() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Next + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily, weekly, monthly, annual). + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Retrieving the inflows + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + = state.problemeHebdo->CaracteristiquesHydrauliques[pArea->index] + .ApportNaturelHoraire[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! The attached area + Antares::Data::Area* pArea; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class Inflows + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_Inflows_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links.h b/src/solver/variable/include/antares/solver/variable/economy/links.h new file mode 100644 index 0000000000..89e2fbfbe3 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links.h @@ -0,0 +1,59 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_VARIABLE_ECONOMY_LINK_H__ +#define __SOLVER_VARIABLE_ECONOMY_LINK_H__ + +#include + +#include "antares/solver/variable/economy/links/congestionFee.h" +#include "antares/solver/variable/economy/links/congestionFeeAbs.h" +#include "antares/solver/variable/economy/links/congestionProbability.h" +#include "antares/solver/variable/economy/links/flowLinear.h" +#include "antares/solver/variable/economy/links/flowLinearAbs.h" +#include "antares/solver/variable/economy/links/flowQuad.h" +#include "antares/solver/variable/economy/links/hurdleCosts.h" +#include "antares/solver/variable/economy/links/loopFlow.h" +#include "antares/solver/variable/economy/links/marginalCost.h" + +#include "../commons/links/links.h" + +namespace Antares::Solver::Variable::Economy +{ +/*! +** \brief All variables for a single link (economy) +*/ +typedef FlowLinear // Flow linear + >>>>>>>> + VariablePerLink; + +using Links = Antares::Solver::Variable::Links; + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_LINK_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/congestionFee.h b/src/solver/variable/include/antares/solver/variable/economy/links/congestionFee.h new file mode 100644 index 0000000000..6e2c2200d0 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/congestionFee.h @@ -0,0 +1,288 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_CongestionFee_H__ +#define __SOLVER_VARIABLE_ECONOMY_CongestionFee_H__ + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardCongestionFee +{ + //! Caption + static std::string Caption() + { + return "CONG. FEE (ALG.)"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Congestion fee collected throughout all MC years (Alg.)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal CongestionFee +*/ +template +class CongestionFee: public Variable::IVariable, NextT, VCardCongestionFee> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardCongestionFee VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~CongestionFee() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(uint year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { +#define UPSTREAM_PRICE \ + state.problemeHebdo->ResultatsHoraires[state.link->from->index] \ + .CoutsMarginauxHoraires[state.hourInTheWeek] +#define DOWNSTREAM_PRICE \ + state.problemeHebdo->ResultatsHoraires[state.link->with->index] \ + .CoutsMarginauxHoraires[state.hourInTheWeek] + + // Congestion Fee + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = state.ntc.ValeurDuFlux + [state.link->index] + * (UPSTREAM_PRICE + - DOWNSTREAM_PRICE); + // Next item in the list + NextType::hourForEachLink(state, numSpace); + +#undef UPSTREAM_PRICE +#undef DOWNSTREAM_PRICE + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class CongestionFee + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_CongestionFee_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/congestionFeeAbs.h b/src/solver/variable/include/antares/solver/variable/economy/links/congestionFeeAbs.h new file mode 100644 index 0000000000..d6468f5e88 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/congestionFeeAbs.h @@ -0,0 +1,290 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_CongestionFeeAbs_H__ +#define __SOLVER_VARIABLE_ECONOMY_CongestionFeeAbs_H__ + +#include + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardCongestionFeeAbs +{ + //! Caption + static std::string Caption() + { + return "CONG. FEE (ABS.)"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Congestion fee collected throughout all MC years (Absolute value)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal CongestionFeeAbs +*/ +template +class CongestionFeeAbs + : public Variable::IVariable, NextT, VCardCongestionFeeAbs> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardCongestionFeeAbs VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~CongestionFeeAbs() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { +#define UPSTREAM_PRICE \ + state.problemeHebdo->ResultatsHoraires[state.link->from->index] \ + .CoutsMarginauxHoraires[state.hourInTheWeek] +#define DOWNSTREAM_PRICE \ + state.problemeHebdo->ResultatsHoraires[state.link->with->index] \ + .CoutsMarginauxHoraires[state.hourInTheWeek] + + // Congestion Fee + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = std::abs( + state.ntc.ValeurDuFlux[state.link->index] * (UPSTREAM_PRICE - DOWNSTREAM_PRICE)); + // Next item in the list + NextType::hourForEachLink(state, numSpace); + +#undef UPSTREAM_PRICE +#undef DOWNSTREAM_PRICE + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class CongestionFeeAbs + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_CongestionFeeAbs_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/congestionProbability.h b/src/solver/variable/include/antares/solver/variable/economy/links/congestionProbability.h new file mode 100644 index 0000000000..f44809d927 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/congestionProbability.h @@ -0,0 +1,393 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_CongestionProbability_H__ +#define __SOLVER_VARIABLE_ECONOMY_CongestionProbability_H__ + +#include + +#include "../../variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardCongestionProbability +{ + //! Caption + static std::string Caption() + { + return "CONG. PROB. (+/-)"; + } + + //! Unit + static std::string Unit() + { + return "%"; + } + + //! The short description of the variable + static std::string Description() + { + return "Probability for the line to be congested in the upstream-downstream way"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 2; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType[columnCount]; + typedef IntermediateValuesBaseType* IntermediateValuesType; + + struct Multiple + { + static std::string Caption(uint indx) + { + switch (indx) + { + case 0: + return "CONG. PROB +"; + case 1: + return "CONG. PROB -"; + default: + return ""; + } + } + + static std::string Unit([[maybe_unused]] const unsigned int indx) + { + return VCardCongestionProbability::Unit(); + } + }; + +}; // class VCard + +/*! +** \brief Marginal CongestionProbability +*/ +template +class CongestionProbability + : public Variable::IVariable, NextT, VCardCongestionProbability> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardCongestionProbability VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~CongestionProbability() + { + delete[] pValuesForTheCurrentYear; + delete[] pValuesForYearLocalReport; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + yearsWeight = study.parameters.getYearsWeight(); + yearsWeightSum = study.parameters.getYearsWeightSum(); + + // Average on all years + for (uint i = 0; i != VCardType::columnCount; ++i) + { + AncestorType::pResults[i].initializeFromStudy(study); + AncestorType::pResults[i].reset(); + } + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); + } + } + + pValuesForYearLocalReport = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForYearLocalReport[numSpace][i].initializeFromStudy(study); + } + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) + { + pValuesForTheCurrentYear[numSpace][0].reset(); + pValuesForTheCurrentYear[numSpace][1].reset(); + } + + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Next variable + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset + pValuesForTheCurrentYear[numSpace][0].reset(); + pValuesForTheCurrentYear[numSpace][1].reset(); + + pValuesForYearLocalReport[numSpace][0].reset(); + pValuesForYearLocalReport[numSpace][1].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(uint year, uint numSpace) + { + for (uint i = 0; i != VCardType::columnCount; ++i) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace][i].computeProbabilitiesForTheCurrentYear(); + } + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (uint i = 0; i != VCardType::columnCount; ++i) + { + // Merge all those values with the global results + AncestorType::pResults[i].merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][i]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + // Ratio take into account MC year weight + float ratio = yearsWeight[state.year] / yearsWeightSum; + + assert(state.link != NULL); + const auto& linkDirectCapa = state.link->directCapacities; + const auto& linkIndirectCapa = state.link->indirectCapacities; + // CONG. PROB + + if (state.ntc.ValeurDuFlux[state.link->index] + > +linkDirectCapa.getCoefficient(state.year, state.hourInTheYear) - 10e-6) + { + pValuesForTheCurrentYear[numSpace][0].hour[state.hourInTheYear] += 100.0 * ratio; + } + // CONG. PROB - + if (state.ntc.ValeurDuFlux[state.link->index] + < -linkIndirectCapa.getCoefficient(state.year, state.hourInTheYear) + 10e-6) + { + pValuesForTheCurrentYear[numSpace][1].hour[state.hourInTheYear] += 100.0 * ratio; + } + + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void beforeYearByYearExport(uint /*year*/, uint numSpace) + { + for (uint i = 0; i != VCardType::columnCount; ++i) + { + for (uint h = 0; h != HOURS_PER_YEAR; ++h) + { + pValuesForYearLocalReport[numSpace][i].hour[h] = (pValuesForTheCurrentYear[numSpace] + [i] + .hour[h] + > 0.) + ? 100. + : 0.; + } + + for (uint d = 0; d != DAYS_PER_YEAR; ++d) + { + pValuesForYearLocalReport[numSpace][i].day[d] = (pValuesForTheCurrentYear[numSpace] + [i] + .day[d] + > 0.) + ? 100. + : 0.; + } + + for (uint w = 0; w != WEEKS_PER_YEAR; ++w) + { + pValuesForYearLocalReport[numSpace][i].week[w] = (pValuesForTheCurrentYear[numSpace] + [i] + .week[w] + > 0.) + ? 100. + : 0.; + } + + for (uint m = 0; m != MONTHS_PER_YEAR; ++m) + { + pValuesForYearLocalReport[numSpace][i].month[m] = (pValuesForTheCurrentYear + [numSpace][i] + .month[m] + > 0.) + ? 100. + : 0.; + } + + pValuesForYearLocalReport[numSpace][i].year = (pValuesForTheCurrentYear[numSpace][i] + .year + > 0.) + ? 100. + : 0.; + } + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint column, + uint numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint numSpace) const + { + // The current variable is actually a multiple-variable. + results.isCurrentVarNA = AncestorType::isNonApplicable; + + for (uint i = 0; i != VCardType::columnCount; ++i) + { + if (AncestorType::isPrinted[i]) + { + // Write the data for the current year + results.variableCaption = VCardType::Multiple::Caption(i); + results.variableUnit = VCardType::Multiple::Unit(i); + pValuesForYearLocalReport[numSpace][i] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + results.isCurrentVarNA++; + } + } + +private: + std::vector yearsWeight; + float yearsWeightSum; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + typename VCardType::IntermediateValuesType pValuesForYearLocalReport; + unsigned int pNbYearsParallel; + +}; // class CongestionProbability + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_CongestionProbability_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/flowLinear.h b/src/solver/variable/include/antares/solver/variable/economy/links/flowLinear.h new file mode 100644 index 0000000000..5d89ae75cd --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/flowLinear.h @@ -0,0 +1,294 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_FlowLinear_H__ +#define __SOLVER_VARIABLE_ECONOMY_FlowLinear_H__ + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardFlowLinear +{ + //! Caption + static std::string Caption() + { + return "FLOW LIN."; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Flow assessed, over all MC years, through linear optimization"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal FlowLinear +*/ +template +class FlowLinear: public Variable::IVariable, NextT, VCardFlowLinear> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardFlowLinear VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~FlowLinear() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + // Flow assessed over all MC years (linear) + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] += state.ntc.ValeurDuFlux + [state.link->index]; + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + if (dataLevel & Category::DataLevel::link) + { + if (digestLevel & Category::digestFlowLinear) + { + results.data.matrix + .entry[results.data.link->from->index][results.data.link->with->index] + = AncestorType::pResults.avgdata.allYears; + results.data.matrix + .entry[results.data.link->with->index][results.data.link->from->index] + = -AncestorType::pResults.avgdata.allYears; + } + } + + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class FlowLinear + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_FlowLinear_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/flowLinearAbs.h b/src/solver/variable/include/antares/solver/variable/economy/links/flowLinearAbs.h new file mode 100644 index 0000000000..c7ca4ba60e --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/flowLinearAbs.h @@ -0,0 +1,283 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_FlowLinearAbs_H__ +#define __SOLVER_VARIABLE_ECONOMY_FlowLinearAbs_H__ + +#include + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardFlowLinearAbs +{ + //! Caption + static std::string Caption() + { + return "UCAP LIN."; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Used capacity assessed, over all MC years, through linear optimization"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal FlowLinearAbs +*/ +template +class FlowLinearAbs: public Variable::IVariable, NextT, VCardFlowLinearAbs> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardFlowLinearAbs VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~FlowLinearAbs() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + // Flow assessed over all MC years (linear) + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] += std::abs( + state.ntc.ValeurDuFlux[state.link->index]); + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class FlowLinearAbs + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_FlowLinearAbs_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/flowQuad.h b/src/solver/variable/include/antares/solver/variable/economy/links/flowQuad.h new file mode 100644 index 0000000000..b7d00a3fb8 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/flowQuad.h @@ -0,0 +1,281 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_FlowQuad_H__ +#define __SOLVER_VARIABLE_ECONOMY_FlowQuad_H__ + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardFlowQuad +{ + //! Caption + static std::string Caption() + { + return "FLOW QUAD."; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Flow (quad.)"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal FlowQuad +*/ +template +class FlowQuad: public Variable::IVariable, NextT, VCardFlowQuad> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardFlowQuad VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~FlowQuad() + { + } + + void initializeFromStudy(Data::Study& study) + { + // Average on all years + pNbHours = study.runtime->rangeLimits.hour[Data::rangeEnd] + 1; + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear.initializeFromStudy(study); + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + assert(link && "invalid interconnection"); + pLinkGlobalIndex = link->index; + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + pValuesForTheCurrentYear.reset(); + + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Flow assessed over all MC years (linear) + (void)::memcpy(pValuesForTheCurrentYear.hour, + transitMoyenInterconnexionsRecalculQuadratique[pLinkGlobalIndex].data(), + sizeof(double) * pNbHours); + + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear.computeStatisticsForTheCurrentYear(); + // Merge all those values with the global results + AncestorType::pResults.merge(0, pValuesForTheCurrentYear); + + // Next + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(uint year, unsigned int numSpace) + { + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + if (dataLevel & Category::DataLevel::link) + { + if (digestLevel & Category::digestFlowQuad) + { + results.data.matrix + .entry[results.data.link->from->index][results.data.link->with->index] + = AncestorType::pResults.rawdata.allYears; + results.data.matrix + .entry[results.data.link->with->index][results.data.link->from->index] + = -AncestorType::pResults.rawdata.allYears; + } + } + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint) const + { + return pValuesForTheCurrentYear.hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear.template buildAnnualSurveyReport(results, + fileLevel, + precision); + } + } + +private: + uint pLinkGlobalIndex; + uint pNbHours; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + +}; // class FlowQuad + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_FlowQuad_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/hurdleCosts.h b/src/solver/variable/include/antares/solver/variable/economy/links/hurdleCosts.h new file mode 100644 index 0000000000..a4b1c0c4de --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/hurdleCosts.h @@ -0,0 +1,331 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_HURDLE_COSTS_H__ +#define __SOLVER_VARIABLE_ECONOMY_HURDLE_COSTS_H__ + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardHurdleCosts +{ + //! Caption + static std::string Caption() + { + return "HURDLE COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hurdle costs, over all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal HurdleCosts +*/ +template +class HurdleCosts: public Variable::IVariable, NextT, VCardHurdleCosts> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardHurdleCosts VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~HurdleCosts() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + // Flow assessed over all MC years (linear) + if (state.link->useHurdlesCost) + { + const double flowLinear = state.ntc.ValeurDuFlux[state.link->index]; + + if (state.link->useLoopFlow) + { + const double loopFlow = state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] + .ValeurDeLoopFlowOrigineVersExtremite[state.link->index]; + if (flowLinear - loopFlow > 0.) + { + const double hurdleCostDirect = (flowLinear - loopFlow) + * state.link->parameters + .entry[Data::fhlHurdlesCostDirect] + [state.hourInTheYear]; + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + += hurdleCostDirect; + // Incrementing annual system cost (to be printed in output in a separate file) + state.annualSystemCost += hurdleCostDirect; + } + else + { + const double hurdleCostIndirect = -(flowLinear - loopFlow) + * state.link->parameters + .entry[Data::fhlHurdlesCostIndirect] + [state.hourInTheYear]; + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + += hurdleCostIndirect; + // Incrementing annual system cost (to be printed in output into a separate + // file) + state.annualSystemCost += hurdleCostIndirect; + } + } + else + { + if (flowLinear > 0.) + { + const double hurdleCostDirect = flowLinear + * state.link->parameters + .entry[Data::fhlHurdlesCostDirect] + [state.hourInTheYear]; + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + += hurdleCostDirect; + // Incrementing annual system cost (to be printed in output in a separate file) + state.annualSystemCost += hurdleCostDirect; + } + else + { + const double hurdleCostIndirect = -flowLinear + * state.link->parameters + .entry[Data::fhlHurdlesCostIndirect] + [state.hourInTheYear]; + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] + += hurdleCostIndirect; + // Incrementing annual system cost (to be printed in output into a separate + // file) + state.annualSystemCost += hurdleCostIndirect; + } + } + } + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; +}; // class HurdleCosts + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_HURDLE_COSTS_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/loopFlow.h b/src/solver/variable/include/antares/solver/variable/economy/links/loopFlow.h new file mode 100644 index 0000000000..b09b559a0c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/loopFlow.h @@ -0,0 +1,277 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_LoopFlow_H__ +#define __SOLVER_VARIABLE_ECONOMY_LoopFlow_H__ + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardLoopFlow +{ + //! Caption + static std::string Caption() + { + return "LOOP FLOW"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Loop flow"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesType; + +}; // class VCard + +/*! +** \brief LoopFlow +*/ +template +class LoopFlow: public Variable::IVariable, NextT, VCardLoopFlow> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardLoopFlow VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~LoopFlow() + { + } + + void initializeFromStudy(Data::Study& study) + { + // Average on all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear.initializeFromStudy(study); + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + if (link->useLoopFlow) + { + // Flow assessed over all MC years (linear) + unsigned int height = link->parameters.height; + (void)::memcpy(pValuesForTheCurrentYear.hour, + link->parameters[Data::fhlLoopFlow], + sizeof(double) * height); + } + + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear.computeStatisticsForTheCurrentYear(); + // Merge all those values with the global results + AncestorType::pResults.merge(0, pValuesForTheCurrentYear); + + // Next + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(uint year, unsigned int numSpace) + { + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint) const + { + return pValuesForTheCurrentYear.hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear.template buildAnnualSurveyReport(results, + fileLevel, + precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + +}; // class LoopFlow + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_LoopFlow_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/links/marginalCost.h b/src/solver/variable/include/antares/solver/variable/economy/links/marginalCost.h new file mode 100644 index 0000000000..0b267870a3 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/links/marginalCost.h @@ -0,0 +1,294 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_MarginalCost_H__ +#define __SOLVER_VARIABLE_ECONOMY_MarginalCost_H__ + +#include + +#include "../../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardMarginalCost +{ + //! Caption + static std::string Caption() + { + return "MARG. COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro/MW"; + } + + //! The short description of the variable + static std::string Description() + { + return "Decrease of the overall operating cost expected by a 1MW capacity reinforcement"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::link; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Marginal MarginalCost +*/ +template +class MarginalCost: public Variable::IVariable, NextT, VCardMarginalCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardMarginalCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~MarginalCost() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average on all years + AncestorType::pResults.initializeFromStudy(study); + AncestorType::pResults.reset(); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromAreaLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourForEachLink(State& state, unsigned int numSpace) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = std::abs( + state.problemeHebdo->VariablesDualesDesContraintesDeNTC[state.hourInTheWeek] + .VariableDualeParInterconnexion[state.link->index]); + + // This value should be reset to zero if (flow_lowerbound) < flow < (flow_upperbound) (with + // signed values) + double flow = state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] + .ValeurDuFlux[state.link->index]; + double flow_lowerbound = -state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] + .ValeurDeNTCExtremiteVersOrigine[state.link->index]; + double flow_upperbound = state.problemeHebdo->ValeursDeNTC[state.hourInTheWeek] + .ValeurDeNTCOrigineVersExtremite[state.link->index]; + + if (flow - 0.001 > flow_lowerbound && flow + 0.001 < flow_upperbound) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 0.; + } + + // Next item in the list + NextType::hourForEachLink(state, numSpace); + } + + void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Next + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + uint numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + uint numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class MarginalCost + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_MarginalCost_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/localMatchingRuleViolations.h b/src/solver/variable/include/antares/solver/variable/economy/localMatchingRuleViolations.h new file mode 100644 index 0000000000..868588f271 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/localMatchingRuleViolations.h @@ -0,0 +1,268 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ +#define __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardLMRViolations +{ + //! Caption + static std::string Caption() + { + return "LMR VIOL."; + } + + //! Unit + static std::string Unit() + { + return " "; + } + + //! The short description of the variable + static std::string Description() + { + return "Local Matching Rule is violated more than the provided threshold"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardLMRViolations VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall CO2 emissions expected from all +** the thermal dispatchable clusters +*/ +template +class LMRViolations: public Variable::IVariable, NextT, VCardLMRViolations> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardLMRViolations VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + + ~LMRViolations() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Total LocalMatchingRule Violations + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = state.hourlyResults + ->ValeursHorairesLmrViolations + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class LMRViolations + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/lold.h b/src/solver/variable/include/antares/solver/variable/economy/lold.h new file mode 100644 index 0000000000..875408a060 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/lold.h @@ -0,0 +1,282 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_LOLD_H__ +#define __SOLVER_VARIABLE_ECONOMY_LOLD_H__ + +#include "antares/solver/variable/economy/unsupliedEnergy.h" +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardLOLD +{ + //! Caption + static std::string Caption() + { + return "LOLD"; + } + + //! Unit + static std::string Unit() + { + return "Hours"; + } + + //! The short description of the variable + static std::string Description() + { + return "LOLD"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardUnsupliedEnergy VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSumThen1IfPositive; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief +*/ +template +class LOLD: public Variable::IVariable, NextT, VCardLOLD> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardLOLD VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~LOLD() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // LOLD + if (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] > 0.5) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 1.; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class LOLD + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_LOLD_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/lolp.h b/src/solver/variable/include/antares/solver/variable/economy/lolp.h new file mode 100644 index 0000000000..95602b0030 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/lolp.h @@ -0,0 +1,279 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_LOLP_H__ +#define __SOLVER_VARIABLE_ECONOMY_LOLP_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardLOLP +{ + //! Caption + static std::string Caption() + { + return "LOLP"; + } + + //! Unit + static std::string Unit() + { + return "%"; + } + + //! The short description of the variable + static std::string Description() + { + return "LOLP"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardLOLP VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateOr; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief +*/ +template +class LOLP: public Variable::IVariable, NextT, VCardLOLP> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardLOLP VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~LOLP() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsOrForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // LOLP + if (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] > 0.) + { + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 100; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class LOLP + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_LOLP_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/max-mrg.h b/src/solver/variable/include/antares/solver/variable/economy/max-mrg.h new file mode 100644 index 0000000000..959d6f16e7 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/max-mrg.h @@ -0,0 +1,288 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_MARGE_H__ +#define __SOLVER_VARIABLE_ECONOMY_MARGE_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardMARGE +{ + //! Caption + static std::string Caption() + { + return "MAX MRG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Maximum margin throughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardMARGE VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Prepare MAX.MRG results for a given week +*/ +void PrepareMaxMRG(const State& state, double* opmrg, uint numSpace); + +/*! +** \brief Max MRG +*/ +template +class Marge: public Variable::IVariable, NextT, VCardMARGE> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardMARGE VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~Marge() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Next + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + // Merge all those values with the global results + // AncestorType::pResults.merge(year, pValuesForTheCurrentYear); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void weekForEachArea(State& state, unsigned int numSpace) + { + double* rawhourly = Memory::RawPointer(pValuesForTheCurrentYear[numSpace].hour); + PrepareMaxMRG(state, rawhourly + state.hourInTheYear, numSpace); + + // next + NextType::weekForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class Marge + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_MARGE_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/nbOfDispatchedUnits.h b/src/solver/variable/include/antares/solver/variable/economy/nbOfDispatchedUnits.h new file mode 100644 index 0000000000..a2af682a67 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/nbOfDispatchedUnits.h @@ -0,0 +1,291 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnits_H__ +#define __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnits_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardNbOfDispatchedUnits +{ + //! Caption + static std::string Caption() + { + return "NODU"; + } + + //! Unit + static std::string Unit() + { + return " "; + } + + //! The short description of the variable + static std::string Description() + { + return "Number Of Dispatched Units throughout all MC years, of all the thermal " + "dispatchable clusters"; + } + + //! The expecte results + typedef Results>>>, + R::AllYears::Average // The + > + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardNbOfDispatchedUnits VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OperatingCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class NbOfDispatchedUnits + : public Variable::IVariable, NextT, VCardNbOfDispatchedUnits> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardNbOfDispatchedUnits VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~NbOfDispatchedUnits() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; + i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; + ++i) + { + pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterDispatchedUnitsCountForYear + [i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class NbOfDispatchedUnits + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnits_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/nbOfDispatchedUnitsByPlant.h b/src/solver/variable/include/antares/solver/variable/economy/nbOfDispatchedUnitsByPlant.h new file mode 100644 index 0000000000..2bc519a94c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/nbOfDispatchedUnitsByPlant.h @@ -0,0 +1,364 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnitsByPlant_H__ +#define __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnitsByPlant_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardNbOfDispatchedUnitsByPlant +{ + //! Caption + static std::string Caption() + { + return "NODU by plant"; + } + + //! Unit + static std::string Unit() + { + return "NODU"; + } + + //! The short description of the variable + static std::string Description() + { + return "Number of Dispatchable Units by plant"; + } + + //! The expected results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardNbOfDispatchedUnitsByPlant VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + + // typedef IntermediateValues IntermediateValuesType; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OperatingCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class NbOfDispatchedUnitsByPlant: public Variable::IVariable, + NextT, + VCardNbOfDispatchedUnitsByPlant> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardNbOfDispatchedUnitsByPlant VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + NbOfDispatchedUnitsByPlant(): + pValuesForTheCurrentYear(NULL), + pSize(0) + { + } + + ~NbOfDispatchedUnitsByPlant() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + pSize = area->thermal.list.enabledCount(); + if (pSize) + { + AncestorType::pResults.resize(pSize); + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [pSize]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != pSize; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return pSize * ResultsType::count; + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildPrepareDataForEachThermalCluster(State& state, + uint year, + unsigned int numSpace) + { + for (unsigned int i = 0; i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; ++i) + { + state.thermalClusterDispatchedUnitsCountForYear[i] += static_cast( + pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i]); + } + + // Next variable + NextType::yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; + i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; + ++i) + { + pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i] + = state.thermalClusterDispatchedUnitsCountForYear[i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Merge all results for all thermal clusters + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); + } + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Merge all those values with the global results + AncestorType::pResults[i].merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][i]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + auto area = state.area; + auto& thermal = state.thermal; + for (auto& cluster: area->thermal.list.each_enabled()) + { + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex].hour[state.hourInTheYear] + = thermal[area->index].numberOfUnitsONbyCluster[cluster->areaWideIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace]->hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& thermal = results.data.area->thermal; + + // Write the data for the current year + for (auto& cluster: thermal.list.each_enabled()) + { + // Write the data for the current year + results.variableCaption = cluster->name(); // VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t pSize; + unsigned int pNbYearsParallel; + +}; // class NbOfDispatchedUnitsByPlant + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_NbOfDispatchedUnitsByPlant_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/nonProportionalCost.h b/src/solver/variable/include/antares/solver/variable/economy/nonProportionalCost.h new file mode 100644 index 0000000000..be8436d29a --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/nonProportionalCost.h @@ -0,0 +1,291 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_NonProportionalCost_H__ +#define __SOLVER_VARIABLE_ECONOMY_NonProportionalCost_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardNonProportionalCost +{ + //! Caption + static std::string Caption() + { + return "NP COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Non Proportional Cost throughout all MC years, of all the thermal dispatchable " + "clusters"; + } + + //! The expecte results + typedef Results>>>, + R::AllYears::Average // The + > + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardNonProportionalCost VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OperatingCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class NonProportionalCost + : public Variable::IVariable, NextT, VCardNonProportionalCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardNonProportionalCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~NonProportionalCost() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; + i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; + ++i) + { + pValuesForTheCurrentYear[numSpace][i] += state + .thermalClusterNonProportionalCostForYear[i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class NonProportionalCost + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_NonProportionalCost_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/npCostByDispatchablePlant.h b/src/solver/variable/include/antares/solver/variable/economy/npCostByDispatchablePlant.h new file mode 100644 index 0000000000..b0587d51a2 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/npCostByDispatchablePlant.h @@ -0,0 +1,345 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_NonProportionalCostByDispatchablePlant_H__ +#define __SOLVER_VARIABLE_ECONOMY_NonProportionalCostByDispatchablePlant_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardNonProportionalCostByDispatchablePlant +{ + //! Caption + static std::string Caption() + { + return "NP Cost by plant"; + } + + //! Unit + static std::string Unit() + { + return "NP Cost - Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Non proportional costs by all the clusters"; + } + + //! The expected results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardNonProportionalCostByDispatchablePlant VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + + // typedef IntermediateValues IntermediateValuesType; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OperatingCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class NonProportionalCostByDispatchablePlant + : public Variable::IVariable, + NextT, + VCardNonProportionalCostByDispatchablePlant> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardNonProportionalCostByDispatchablePlant VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> + AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + NonProportionalCostByDispatchablePlant(): + pValuesForTheCurrentYear(NULL), + pSize(0) + { + } + + ~NonProportionalCostByDispatchablePlant() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + pSize = area->thermal.list.enabledCount(); + if (pSize) + { + AncestorType::pResults.resize(pSize); + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [pSize]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != pSize; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return pSize * ResultsType::count; + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; + i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; + ++i) + { + pValuesForTheCurrentYear[numSpace][state.thermalCluster->areaWideIndex].hour[i] + = state.thermalClusterNonProportionalCostForYear[i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Merge all results for all thermal clusters + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); + } + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Merge all those values with the global results + AncestorType::pResults[i].merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][i]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace]->hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& thermal = results.data.area->thermal; + + // Write the data for the current year + for (auto& cluster: thermal.list.each_enabled()) + { + // Write the data for the current year + results.variableCaption = cluster->name(); // VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t pSize; + unsigned int pNbYearsParallel; + +}; // class NonProportionalCostByDispatchablePlant + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_NonProportionalCostByDispatchablePlant_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/operatingCost.h b/src/solver/variable/include/antares/solver/variable/economy/operatingCost.h new file mode 100644 index 0000000000..0df88e6711 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/operatingCost.h @@ -0,0 +1,288 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_OperatingCost_H__ +#define __SOLVER_VARIABLE_ECONOMY_OperatingCost_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardOperatingCost +{ + //! Caption + static std::string Caption() + { + return "OP. COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Operating Cost throughout all MC years, of all the thermal dispatchable clusters"; + } + + //! The expecte results + typedef Results>>>, + R::AllYears::Average // The + > + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardOperatingCost VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OperatingCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class OperatingCost: public Variable::IVariable, NextT, VCardOperatingCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardOperatingCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~OperatingCost() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; + i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; + ++i) + { + pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterOperatingCostForYear[i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class OperatingCost + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_OperatingCost_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/overallCost.h b/src/solver/variable/include/antares/solver/variable/economy/overallCost.h new file mode 100644 index 0000000000..43c13f6620 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/overallCost.h @@ -0,0 +1,305 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_OverallCost_H__ +#define __SOLVER_VARIABLE_ECONOMY_OverallCost_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardOverallCost +{ + //! Caption + static std::string Caption() + { + return "OV. COST"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Overall Cost throughout all MC years"; + } + + //! The expecte results + typedef Results, + R::AllYears::Average // Use these values for spatial cluster + > + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardOverallCost VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OverallCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class OverallCost: public Variable::IVariable, NextT, VCardOverallCost> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardOverallCost VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~OverallCost() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildForEachThermalCluster(State& state, uint year, unsigned int numSpace) + { + // Get end year calculations + for (unsigned int i = state.study.runtime->rangeLimits.hour[Data::rangeBegin]; + i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; + ++i) + { + pValuesForTheCurrentYear[numSpace][i] += state.thermalClusterOperatingCostForYear[i]; + // Incrementing annual system cost (to be printed in output into a separate file) + state.annualSystemCost += state.thermalClusterOperatingCostForYear[i]; + } + + // Next variable + NextType::yearEndBuildForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + const double costForSpilledOrUnsuppliedEnergy = + // Total UnsupliedEnergy emissions + (state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek] + * state.area->thermal.unsuppliedEnergyCost) + + (state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek] + * state.area->thermal.spilledEnergyCost) + // Current hydro storage and pumping generation costs + + (state.hourlyResults->valeurH2oHoraire[state.hourInTheWeek] + * (state.hourlyResults->TurbinageHoraire[state.hourInTheWeek] + - state.area->hydro.pumpingEfficiency + * state.hourlyResults->PompageHoraire[state.hourInTheWeek])); + + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] += costForSpilledOrUnsuppliedEnergy; + + // Incrementing annual system cost (to be printed in output into a separate file) + state.annualSystemCost += costForSpilledOrUnsuppliedEnergy; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class OverallCost + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_OverallCost_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/overflow.h b/src/solver/variable/include/antares/solver/variable/economy/overflow.h new file mode 100644 index 0000000000..05a7cb5fbe --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/overflow.h @@ -0,0 +1,280 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_Overflow_H__ +#define __SOLVER_VARIABLE_ECONOMY_Overflow_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardOverflow +{ + //! Caption + static std::string Caption() + { + return "H. OVFL"; + } + + //! Unit + static std::string Unit() + { + return "%"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydro overflow"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardOverflow VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 1; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Reservoir level +*/ +template +class Overflows: public Variable::IVariable, NextT, VCardOverflow> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardOverflow VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~Overflows() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily, weekly, monthly, annual). + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Retrieving hourly reservoir levels of week simulation + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = state.hourlyResults + ->debordementsHoraires + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class HydroLevel + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_Overflow_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/price.h b/src/solver/variable/include/antares/solver/variable/economy/price.h new file mode 100644 index 0000000000..f74567c938 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/price.h @@ -0,0 +1,279 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_Price_H__ +#define __SOLVER_VARIABLE_ECONOMY_Price_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardPrice +{ + //! Caption + static std::string Caption() + { + return "MRG. PRICE"; + } + + //! Unit + static std::string Unit() + { + return "Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Marginal Price, throughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardPrice VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateAverage; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = Category:: + spatialAggregatePostProcessingPrice; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Marginal Price +*/ +template +class Price: public Variable::IVariable, NextT, VCardPrice> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardPrice VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~Price() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Average thoughout all years + InitializeResultsFromStudy(AncestorType::pResults, study); + + // Intermediate values + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(uint year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(uint year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(uint hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Marginal Price + // Note: The marginal price provided by the solver is negative + // (naming convention). + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] -= state.hourlyResults + ->CoutsMarginauxHoraires + [state.hourInTheWeek]; + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + uint, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class Price + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_Price_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/productionByDispatchablePlant.h b/src/solver/variable/include/antares/solver/variable/economy/productionByDispatchablePlant.h new file mode 100644 index 0000000000..2e401844eb --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/productionByDispatchablePlant.h @@ -0,0 +1,395 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_ProductionByDispatchablePlant_H__ +#define __SOLVER_VARIABLE_ECONOMY_ProductionByDispatchablePlant_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardProductionByDispatchablePlant +{ + //! Caption + static std::string Caption() + { + return "DTG by plant"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Energy generated by all the clusters"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardProductionByDispatchablePlant VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Energy generated by all thermal dispatchable clusters +*/ +template +class ProductionByDispatchablePlant + : public Variable:: + IVariable, NextT, VCardProductionByDispatchablePlant> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardProductionByDispatchablePlant VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> + AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ProductionByDispatchablePlant(): + pValuesForTheCurrentYear(nullptr), + pminOfTheClusterForYear(nullptr), + pSize(0) + { + } + + ~ProductionByDispatchablePlant() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pminOfTheClusterForYear[numSpace]; + } + delete[] pminOfTheClusterForYear; + } + + void initializeFromStudy(Data::Study& study) + { + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + pminOfTheClusterForYear = new double*[pNbYearsParallel]; + + // Get the area + pSize = area->thermal.list.enabledCount(); + if (pSize) + { + AncestorType::pResults.resize(pSize); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [pSize]; + } + + // Minimum power values of the cluster for the whole year - from the solver in the + // accurate mode not to be displayed in the output \todo think of a better place like + // the DispatchableMarginForAllAreas done at the beginning of the year + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pminOfTheClusterForYear[numSpace] = new double[pSize * HOURS_PER_YEAR]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != pSize; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + pminOfTheClusterForYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return pSize * ResultsType::count; + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + + for (unsigned int j = 0; j != HOURS_PER_YEAR; ++j) + { + pminOfTheClusterForYear[numSpace][i * HOURS_PER_YEAR + j] = 0; + } + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildPrepareDataForEachThermalCluster(State& state, + uint year, + unsigned int numSpace) + { + for (unsigned int i = 0; i <= state.study.runtime->rangeLimits.hour[Data::rangeEnd]; ++i) + { + state.thermalClusterProductionForYear[i] += pValuesForTheCurrentYear + [numSpace] + [state.thermalCluster->areaWideIndex] + .hour[i]; + state.thermalClusterPMinOfTheClusterForYear[i] += pminOfTheClusterForYear + [numSpace][(state.thermalCluster->areaWideIndex * HOURS_PER_YEAR) + i]; + } + + // Next variable + NextType::yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Merge all results for all thermal clusters + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); + } + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Merge all those values with the global results + AncestorType::pResults[i].merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][i]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + auto& area = state.area; + auto& thermal = state.thermal; + for (auto& cluster: area->thermal.list.each_enabled()) + { + // Production for this hour + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex].hour[state.hourInTheYear] + += thermal[area->index].thermalClustersProductions[cluster->areaWideIndex]; + + pminOfTheClusterForYear[numSpace] + [(cluster->areaWideIndex * HOURS_PER_YEAR) + state.hourInTheYear] + = thermal[area->index].PMinOfClusters[cluster->areaWideIndex]; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * pSize + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * pSize * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& thermal = results.data.area->thermal; + + // Write the data for the current year + for (auto& cluster: thermal.list.each_enabled()) + { + // Write the data for the current year + results.variableCaption = cluster->name(); // VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + double** pminOfTheClusterForYear; + size_t pSize; + unsigned int pNbYearsParallel; + +}; // class ProductionByDispatchablePlant + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_ProductionByDispatchablePlant_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/productionByRenewablePlant.h b/src/solver/variable/include/antares/solver/variable/economy/productionByRenewablePlant.h new file mode 100644 index 0000000000..82ce7b3dcf --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/productionByRenewablePlant.h @@ -0,0 +1,356 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_ProductionByRenewablePlant_H__ +#define __SOLVER_VARIABLE_ECONOMY_ProductionByRenewablePlant_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardProductionByRenewablePlant +{ + //! Caption + static std::string Caption() + { + return "RES generation by plant"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Energy generated by all the RES clusters"; + } + + //! The expecte results + typedef Results> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardProductionByRenewablePlant VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de_res); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; + +}; // class VCard + +/*! +** \brief Energy generated by all renewable clusters +*/ +template +class ProductionByRenewablePlant: public Variable::IVariable, + NextT, + VCardProductionByRenewablePlant> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardProductionByRenewablePlant VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ProductionByRenewablePlant(): + pValuesForTheCurrentYear(nullptr), + pSize(0) + { + } + + ~ProductionByRenewablePlant() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + pSize = area->renewable.list.enabledCount(); + if (pSize) + { + AncestorType::pResults.resize(pSize); + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [pSize]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != pSize; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return pSize * ResultsType::count; + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != pSize; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuildPrepareDataForEachThermalCluster(State& state, + uint year, + unsigned int numSpace) + { + // Next variable + NextType::yearEndBuildPrepareDataForEachThermalCluster(state, year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Merge all results for all renewable clusters + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); + } + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int i = 0; i < pSize; ++i) + { + // Merge all those values with the global results + AncestorType::pResults[i].merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][i]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + for (const auto& renewableCluster: state.area->renewable.list.each_enabled()) + { + double renewableClusterProduction = renewableCluster->valueAtTimeStep( + state.year, + state.hourInTheYear); + + pValuesForTheCurrentYear[numSpace][renewableCluster->areaWideIndex] + .hour[state.hourInTheYear] + += renewableClusterProduction; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + inline void buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const + { + // Ask to build the digest to the next variable + NextType::buildDigest(results, digestLevel, dataLevel); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + inline uint64_t memoryUsage() const + { + uint64_t r = (sizeof(IntermediateValues) * pSize + IntermediateValues::MemoryUsage()) + * pNbYearsParallel; + r += sizeof(double) * pSize * HOURS_PER_YEAR * pNbYearsParallel; + r += AncestorType::memoryUsage(); + return r; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& renewable = results.data.area->renewable; + // Write the data for the current year + for (auto& cluster: renewable.list.each_enabled()) + { + // Write the data for the current year + results.variableCaption = cluster->name(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t pSize; + unsigned int pNbYearsParallel; +}; // class ProductionByRenewablePlant + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_ProductionByRenewablePlant_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/profitByPlant.h b/src/solver/variable/include/antares/solver/variable/economy/profitByPlant.h new file mode 100644 index 0000000000..2dd9378067 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/profitByPlant.h @@ -0,0 +1,341 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#pragma once + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardProfitByPlant +{ + //! Caption + static std::string Caption() + { + return "Profit by plant"; + } + + //! Unit + static std::string Unit() + { + return "Profit - Euro"; + } + + //! The short description of the variable + static std::string Description() + { + return "Profit for thermal units"; + } + + //! The expected results + typedef Results> + ResultsType; + + //! The VCard to look for calculating spatial aggregates + typedef VCardProfitByPlant VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::de); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable + static constexpr int columnCount = Category::dynamicColumns; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesDeepType; + typedef IntermediateValues* IntermediateValuesBaseType; + typedef IntermediateValuesBaseType* IntermediateValuesType; +}; // class VCard + +/*! +** \brief C02 Average value of the overrall OperatingCost emissions expected from all +** the thermal dispatchable clusters +*/ +template +class ProfitByPlant: public Variable::IVariable, NextT, VCardProfitByPlant> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardProfitByPlant VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ProfitByPlant(): + pValuesForTheCurrentYear(nullptr), + pNbClustersOfArea(0) + { + } + + ~ProfitByPlant() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + delete[] pValuesForTheCurrentYear[numSpace]; + } + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + // Next + NextType::initializeFromStudy(study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Get the number of years in parallel + pNbYearsParallel = study->maxNbYearsInParallel; + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + + // Get the area + pNbClustersOfArea = area->thermal.list.enabledCount(); + if (pNbClustersOfArea) + { + AncestorType::pResults.resize(pNbClustersOfArea); + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = new VCardType::IntermediateValuesDeepType + [pNbClustersOfArea]; + } + + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + for (unsigned int i = 0; i != pNbClustersOfArea; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(*study); + } + } + + for (unsigned int i = 0; i != pNbClustersOfArea; ++i) + { + AncestorType::pResults[i].initializeFromStudy(*study); + AncestorType::pResults[i].reset(); + } + } + else + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace] = nullptr; + } + + AncestorType::pResults.clear(); + } + + // Next + NextType::initializeFromArea(study, area); + } + + size_t getMaxNumberColumns() const + { + return pNbClustersOfArea * ResultsType::count; + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != pNbClustersOfArea; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Merge all results for all thermal clusters + { + for (unsigned int i = 0; i < pNbClustersOfArea; ++i) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace][i].computeStatisticsForTheCurrentYear(); + } + } + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + for (unsigned int i = 0; i < pNbClustersOfArea; ++i) + { + // Merge all those values with the global results + AncestorType::pResults[i].merge(numSpaceToYear[numSpace], + pValuesForTheCurrentYear[numSpace][i]); + } + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Useful local variables + auto area = state.area; + auto& thermal = state.thermal; + const std::vector& areaMarginalCosts = state.hourlyResults->CoutsMarginauxHoraires; + uint hourInTheWeek = state.hourInTheWeek; + uint hourInTheYear = state.hourInTheYear; + + for (auto& cluster: area->thermal.list.each_enabled()) + { + double hourlyClusterProduction = thermal[area->index] + .thermalClustersProductions[cluster->areaWideIndex]; + uint tsIndex = cluster->series.timeseriesNumbers[state.year]; + + // Thermal cluster profit + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex].hour[hourInTheYear] + = std::max((hourlyClusterProduction - cluster->PthetaInf[hourInTheYear]), 0.) + * (-areaMarginalCosts[hourInTheWeek] + - cluster->getMarginalCost(tsIndex, hourInTheYear)); + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace]->hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + assert(NULL != results.data.area); + const auto& thermal = results.data.area->thermal; + + // Write the data for the current year + for (auto& cluster: thermal.list.each_enabled()) + { + // Write the data for the current year + results.variableCaption = cluster->name(); // VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace][cluster->areaWideIndex] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + size_t pNbClustersOfArea; + unsigned int pNbYearsParallel; + +}; // class + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares diff --git a/src/solver/variable/include/antares/solver/variable/economy/pumping.h b/src/solver/variable/include/antares/solver/variable/economy/pumping.h new file mode 100644 index 0000000000..db8d59289f --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/pumping.h @@ -0,0 +1,284 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_Pumping_H__ +#define __SOLVER_VARIABLE_ECONOMY_Pumping_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardPumping +{ + //! Caption + static std::string Caption() + { + return "H. PUMP"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydraulic pumping"; + } + + //! The expected results + typedef Results>>>> + ResultsType; + + //! The VCard to look for calculating spatial aggregates + typedef VCardPumping VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Reservoir level +*/ +template +class Pumping: public Variable::IVariable, NextT, VCardPumping> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardPumping VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~Pumping() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + pArea = area; + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + // Next + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily, weekly, monthly, annual). + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Retrieving the hourly pumping energy + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = state.hourlyResults + ->PompageHoraire + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! The attached area + Antares::Data::Area* pArea; + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class Pumping + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_Pumping_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/renewableGeneration.h b/src/solver/variable/include/antares/solver/variable/economy/renewableGeneration.h new file mode 100644 index 0000000000..c46f6c624e --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/renewableGeneration.h @@ -0,0 +1,328 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_RenewableGeneration_H__ +#define __SOLVER_VARIABLE_ECONOMY_RenewableGeneration_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardRenewableGeneration +{ + //! Caption + static std::string Caption() + { + return "Renewable Gen."; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Value of all the renewable generation throughout all MC years"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardRenewableGeneration VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 9; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType[columnCount]; + typedef IntermediateValuesBaseType* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + + struct Multiple + { + static std::string Caption(const unsigned int indx) + { + switch (indx) + { + case 0: + return "WIND OFFSHORE"; + case 1: + return "WIND ONSHORE"; + case 2: + return "SOLAR CONCRT."; + case 3: + return "SOLAR PV"; + case 4: + return "SOLAR ROOFT"; + case 5: + return "RENW. 1"; + case 6: + return "RENW. 2"; + case 7: + return "RENW. 3"; + case 8: + return "RENW. 4"; + default: + return ""; + } + } + + static std::string Unit([[maybe_unused]] const unsigned int indx) + { + return VCardRenewableGeneration::Unit(); + } + }; +}; // class VCard + +/*! +** \brief Marginal RenewableGeneration +*/ +template +class RenewableGeneration + : public Variable::IVariable, NextT, VCardRenewableGeneration> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardRenewableGeneration VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~RenewableGeneration() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); + } + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + results[i].initializeFromStudy(study); + results[i].reset(); + } + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + VariableAccessorType::template ComputeStatistics( + pValuesForTheCurrentYear[numSpace]); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[numSpace], + AncestorType::pResults, + numSpaceToYear[numSpace]); + } + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + for (const auto& renewableCluster: state.area->renewable.list.each_enabled()) + { + double renewableClusterProduction = renewableCluster->valueAtTimeStep( + state.year, + state.hourInTheYear); + + pValuesForTheCurrentYear[numSpace][renewableCluster->groupID][state.hourInTheYear] + += renewableClusterProduction; + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // The current variable is actually a multiple-variable. + results.isCurrentVarNA = AncestorType::isNonApplicable; + + for (uint i = 0; i != VCardType::columnCount; ++i) + { + if (AncestorType::isPrinted[i]) + { + // Write the data for the current year + results.variableCaption = VCardType::Multiple::Caption(i); + results.variableUnit = VCardType::Multiple::Unit(i); + pValuesForTheCurrentYear[numSpace][i] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + results.isCurrentVarNA++; + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class RenewableGeneration + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_RenewableGeneration_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/reservoirlevel.h b/src/solver/variable/include/antares/solver/variable/economy/reservoirlevel.h new file mode 100644 index 0000000000..9dad55e963 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/reservoirlevel.h @@ -0,0 +1,280 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_ReservoirLevel_H__ +#define __SOLVER_VARIABLE_ECONOMY_ReservoirLevel_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardReservoirLevel +{ + //! Caption + static std::string Caption() + { + return "H. LEV"; + } + + //! Unit + static std::string Unit() + { + return "%"; + } + + //! The short description of the variable + static std::string Description() + { + return "Hydro Level"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardReservoirLevel VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable + static constexpr uint8_t isPossiblyNonApplicable = 1; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Reservoir level +*/ +template +class ReservoirLevel: public Variable::IVariable, NextT, VCardReservoirLevel> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardReservoirLevel VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~ReservoirLevel() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily, weekly, monthly, annual). + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Retrieving hourly reservoir levels of week simulation + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = state.hourlyResults + ->niveauxHoraires + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class HydroLevel + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_ReservoirLevel_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/spilledEnergy.h b/src/solver/variable/include/antares/solver/variable/economy/spilledEnergy.h new file mode 100644 index 0000000000..ad6c895d3f --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/spilledEnergy.h @@ -0,0 +1,282 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_SpilledEnergy_H__ +#define __SOLVER_VARIABLE_ECONOMY_SpilledEnergy_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardSpilledEnergy +{ + //! Caption + static std::string Caption() + { + return "SPIL. ENRG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Spilled Energy (generation that cannot be satisfied)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSpilledEnergy VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall SpilledEnergy emissions expected from all +** the thermal dispatchable clusters +*/ +template +class SpilledEnergy: public Variable::IVariable, NextT, VCardSpilledEnergy> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSpilledEnergy VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~SpilledEnergy() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + assert(state.hourlyResults && "Invalid pointer to simplex results"); + + // Total SpilledEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesDeDefaillanceNegative[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class SpilledEnergy + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_SpilledEnergy_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/spilledEnergyAfterCSR.h b/src/solver/variable/include/antares/solver/variable/economy/spilledEnergyAfterCSR.h new file mode 100644 index 0000000000..9881775f78 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/spilledEnergyAfterCSR.h @@ -0,0 +1,273 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ +#define __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardSpilledEnergyAfterCSR +{ + //! Caption + static std::string Caption() + { + return "SPIL. ENRG. CSR"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Spilled Energy After CSR Optimization (generation that cannot be satisfied) " + "after CSR optimization"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardSpilledEnergyAfterCSR VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall SpilledEnergyAfterCSR emissions expected from all +** the thermal dispatchable clusters +*/ +template +class SpilledEnergyAfterCSR + : public Variable::IVariable, NextT, VCardSpilledEnergyAfterCSR> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardSpilledEnergyAfterCSR VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + + ~SpilledEnergyAfterCSR() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Total SpilledEnergyAfterCSR emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesSpilledEnergyAfterCSR[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class SpilledEnergyAfterCSR + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/thermalAirPollutantEmissions.h b/src/solver/variable/include/antares/solver/variable/economy/thermalAirPollutantEmissions.h new file mode 100644 index 0000000000..2955469715 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/thermalAirPollutantEmissions.h @@ -0,0 +1,309 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_thermalAirPollutantEmissions_H__ +#define __SOLVER_VARIABLE_ECONOMY_thermalAirPollutantEmissions_H__ + +#include +#include "antares/solver/variable/variable.h" + +namespace Antares::Solver::Variable::Economy +{ +struct VCardThermalAirPollutantEmissions +{ + //! Caption not used: several columns + static std::string Caption() + { + return ""; + } + + //! Unit + static std::string Unit() + { + return "Tons"; + } + + //! The short description of the variable + static std::string Description() + { + return "Overall pollutant emissions expected from all the thermal clusters"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardThermalAirPollutantEmissions VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = Antares::Data::Pollutant::POLLUTANT_MAX; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType[columnCount]; + typedef IntermediateValuesBaseType* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + + struct Multiple + { + static std::string Caption(const unsigned int indx) + { + if (indx < Antares::Data::Pollutant::POLLUTANT_MAX) + { + return Antares::Data::Pollutant::getPollutantName(indx).c_str(); + } + + return ""; + } + + static std::string Unit([[maybe_unused]] const unsigned int indx) + { + return VCardThermalAirPollutantEmissions::Unit(); + } + }; +}; // class VCard + +/*! +** \brief Marginal ThermalAirPollutantEmissions +*/ +template +class ThermalAirPollutantEmissions: public Variable::IVariable, + NextT, + VCardThermalAirPollutantEmissions> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardThermalAirPollutantEmissions VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~ThermalAirPollutantEmissions() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; ++numSpace) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].initializeFromStudy(study); + } + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + results[i].initializeFromStudy(study); + results[i].reset(); + } + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + for (unsigned int i = 0; i != VCardType::columnCount; ++i) + { + pValuesForTheCurrentYear[numSpace][i].reset(); + } + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + VariableAccessorType::template ComputeStatistics( + pValuesForTheCurrentYear[numSpace]); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + VariableAccessorType::ComputeSummary(pValuesForTheCurrentYear[numSpace], + AncestorType::pResults, + numSpaceToYear[numSpace]); + } + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + auto area = state.area; + auto& thermal = state.thermal; + for (auto& cluster: area->thermal.list.each_enabled()) + { + // Multiply every pollutant factor with production + for (int pollutant = 0; pollutant < Antares::Data::Pollutant::POLLUTANT_MAX; + pollutant++) + { + pValuesForTheCurrentYear[numSpace][pollutant][state.hourInTheYear] + += cluster->emissions.factors[pollutant] + * thermal[state.area->index] + .thermalClustersProductions[cluster->areaWideIndex]; + } + } + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int column, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace][column].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // The current variable is actually a multiple-variable. + results.isCurrentVarNA = AncestorType::isNonApplicable; + + for (uint i = 0; i != VCardType::columnCount; ++i) + { + if (AncestorType::isPrinted[i]) + { + // Write the data for the current year + results.variableCaption = VCardType::Multiple::Caption(i); + results.variableUnit = VCardType::Multiple::Unit(i); + pValuesForTheCurrentYear[numSpace][i] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + results.isCurrentVarNA++; + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class ThermalAirPollutantEmissions + +} // namespace Antares::Solver::Variable::Economy + +#endif // __SOLVER_VARIABLE_ECONOMY_thermalAirPollutantEmissions_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/unsupliedEnergy.h b/src/solver/variable/include/antares/solver/variable/economy/unsupliedEnergy.h new file mode 100644 index 0000000000..b3f15946ae --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/unsupliedEnergy.h @@ -0,0 +1,283 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ +#define __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardUnsupliedEnergy +{ + //! Caption + static std::string Caption() + { + return "UNSP. ENRG"; + } + + //! Unit + static std::string Unit() + { + return "MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Unsuplied Energy (demand that cannot be satisfied)"; + } + + //! The expecte results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardUnsupliedEnergy VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 0; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::spatialAggregateSum; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 0; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief C02 Average value of the overrall UnsupliedEnergy emissions expected from all +** the thermal dispatchable clusters +*/ +template +class UnsupliedEnergy + : public Variable::IVariable, NextT, VCardUnsupliedEnergy> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardUnsupliedEnergy VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~UnsupliedEnergy() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + // Intermediate values + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily,weekly,monthly) + pValuesForTheCurrentYear[numSpace].computeStatisticsForTheCurrentYear(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Total UnsupliedEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = + // Current Hydro Storage generation + state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class UnsupliedEnergy + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ diff --git a/src/solver/variable/include/antares/solver/variable/economy/waterValue.h b/src/solver/variable/include/antares/solver/variable/economy/waterValue.h new file mode 100644 index 0000000000..488737ca5c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/economy/waterValue.h @@ -0,0 +1,280 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_ECONOMY_WaterValue_H__ +#define __SOLVER_VARIABLE_ECONOMY_WaterValue_H__ + +#include "antares/solver/variable/variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardWaterValue +{ + //! Caption + static std::string Caption() + { + return "H. VAL"; + } + + //! Unit + static std::string Unit() + { + return "Euro/MWh"; + } + + //! The short description of the variable + static std::string Description() + { + return "Water value"; + } + + //! The expected results + typedef Results>>>> + ResultsType; + + //! The VCard to look for for calculating spatial aggregates + typedef VCardWaterValue VCardForSpatialAggregate; + + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & (Category::FileLevel::id + | Category::FileLevel::va); + //! Precision (views) + static constexpr uint8_t precision = Category::all; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +0; + //! Decimal precision + static constexpr uint8_t decimal = 2; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 1; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + static constexpr uint8_t spatialAggregateMode = Category::spatialAggregateEachYear; + static constexpr uint8_t spatialAggregatePostProcessing = 0; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 1; + //! Can this variable be non applicable (0 : no, 1 : yes) + static constexpr uint8_t isPossiblyNonApplicable = 1; + + typedef IntermediateValues IntermediateValuesBaseType; + typedef IntermediateValues* IntermediateValuesType; + + typedef IntermediateValuesBaseType* IntermediateValuesTypeForSpatialAg; + +}; // class VCard + +/*! +** \brief Water values +*/ +template +class WaterValue: public Variable::IVariable, NextT, VCardWaterValue> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardWaterValue VCardType; + //! Ancestor + typedef Variable::IVariable, NextT, VCardType> AncestorType; + + //! List of expected results + typedef typename VCardType::ResultsType ResultsType; + + typedef VariableAccessor VariableAccessorType; + + enum + { + //! How many items have we got + count = 1 + NextT::count, + }; + + template + struct Statistics + { + enum + { + count = ((VCardType::categoryDataLevel & CDataLevel + && VCardType::categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + VCardType::columnCount * ResultsType::count) + : NextType::template Statistics::count), + }; + }; + +public: + ~WaterValue() + { + delete[] pValuesForTheCurrentYear; + } + + void initializeFromStudy(Data::Study& study) + { + pNbYearsParallel = study.maxNbYearsInParallel; + + InitializeResultsFromStudy(AncestorType::pResults, study); + + pValuesForTheCurrentYear = new VCardType::IntermediateValuesBaseType[pNbYearsParallel]; + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].initializeFromStudy(study); + } + + // Next + NextType::initializeFromStudy(study); + } + + template + static void InitializeResultsFromStudy(R& results, Data::Study& study) + { + VariableAccessorType::InitializeAndReset(results, study); + } + + void initializeFromArea(Data::Study* study, Data::Area* area) + { + // Next + NextType::initializeFromArea(study, area); + } + + void initializeFromLink(Data::Study* study, Data::AreaLink* link) + { + // Next + NextType::initializeFromAreaLink(study, link); + } + + void simulationBegin() + { + for (unsigned int numSpace = 0; numSpace < pNbYearsParallel; numSpace++) + { + pValuesForTheCurrentYear[numSpace].reset(); + } + // Next + NextType::simulationBegin(); + } + + void simulationEnd() + { + NextType::simulationEnd(); + } + + void yearBegin(unsigned int year, unsigned int numSpace) + { + // Reset the values for the current year + pValuesForTheCurrentYear[numSpace].reset(); + + // Next variable + NextType::yearBegin(year, numSpace); + } + + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace) + { + // Next variable + NextType::yearEndBuild(state, year, numSpace); + } + + void yearEnd(unsigned int year, unsigned int numSpace) + { + // Compute all statistics for the current year (daily, weekly, monthly, annual). + pValuesForTheCurrentYear[numSpace].computeAveragesForCurrentYearFromHourlyResults(); + + // Next variable + NextType::yearEnd(year, numSpace); + } + + void computeSummary(std::map& numSpaceToYear, + unsigned int nbYearsForCurrentSummary) + { + for (unsigned int numSpace = 0; numSpace < nbYearsForCurrentSummary; ++numSpace) + { + // Merge all those values with the global results + AncestorType::pResults.merge(numSpaceToYear[numSpace] /*year*/, + pValuesForTheCurrentYear[numSpace]); + } + + // Next variable + NextType::computeSummary(numSpaceToYear, nbYearsForCurrentSummary); + } + + void hourBegin(unsigned int hourInTheYear) + { + // Next variable + NextType::hourBegin(hourInTheYear); + } + + void hourForEachArea(State& state, unsigned int numSpace) + { + // Retrieving hourly water values of week simulation + pValuesForTheCurrentYear[numSpace].hour[state.hourInTheYear] = state.hourlyResults + ->valeurH2oHoraire + [state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + Antares::Memory::Stored::ConstReturnType retrieveRawHourlyValuesForCurrentYear( + unsigned int, + unsigned int numSpace) const + { + return pValuesForTheCurrentYear[numSpace].hour; + } + + void localBuildAnnualSurveyReport(SurveyResults& results, + int fileLevel, + int precision, + unsigned int numSpace) const + { + // Initializing external pointer on current variable non applicable status + results.isCurrentVarNA = AncestorType::isNonApplicable; + + if (AncestorType::isPrinted[0]) + { + // Write the data for the current year + results.variableCaption = VCardType::Caption(); + results.variableUnit = VCardType::Unit(); + pValuesForTheCurrentYear[numSpace] + .template buildAnnualSurveyReport(results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class WaterValue + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_WaterValue_H__ diff --git a/src/solver/variable/endoflist.h b/src/solver/variable/include/antares/solver/variable/endoflist.h similarity index 83% rename from src/solver/variable/endoflist.h rename to src/solver/variable/include/antares/solver/variable/endoflist.h index 13594f11ae..7c32c32ecb 100644 --- a/src/solver/variable/endoflist.h +++ b/src/solver/variable/include/antares/solver/variable/endoflist.h @@ -1,34 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_END_OF_LIST_END_OF_LIST_H__ #define __SOLVER_END_OF_LIST_END_OF_LIST_H__ #include + #include + #include "state.h" #include "surveyresults.h" @@ -65,7 +61,6 @@ class EndOfList }; public: - /*! ** \brief Retrieve the list of all individual variables ** @@ -82,9 +77,11 @@ class EndOfList EndOfList() { } + ~EndOfList() { } + //@} static void initializeFromStudy([[maybe_unused]] Data::Study& study) @@ -94,9 +91,11 @@ class EndOfList static void initializeFromArea(Data::Study*, Data::Area*) { } + static void initializeFromThermalCluster(Data::Study*, Data::Area*, Data::ThermalCluster*) { } + static void initializeFromAreaLink(Data::Study*, Data::AreaLink*) { } @@ -139,9 +138,10 @@ class EndOfList UNUSED_VARIABLE(numSpace); } - static void yearEndBuild(State&, unsigned int) + static void yearEndBuild(State&, unsigned int, unsigned int) { } + static void yearEnd(unsigned int, unsigned int) { } @@ -151,10 +151,10 @@ class EndOfList { UNUSED_VARIABLE(numSpaceToYear); UNUSED_VARIABLE(nbYearsForCurrentSummary); - }; + } template - void yearEndSpatialAggregates(V&, unsigned int, uint numSpace) + void yearEndSpatialAggregates(V&, unsigned int, uint) { } @@ -165,14 +165,17 @@ class EndOfList } template - void computeSpatialAggregatesSummary(V&, std::map&, unsigned int) + static void computeSpatialAggregatesSummary(V&, + std::map&, + unsigned int) { } template - void simulationEndSpatialAggregates(V&) + static void simulationEndSpatialAggregates(V&) { } + template void simulationEndSpatialAggregates(V&, const SetT&) { @@ -240,12 +243,20 @@ class EndOfList { assert(false); } + template static void computeSpatialAggregateWith(O&, const Data::Area*) { assert(false); } + template + static void computeSpatialAggregateWith(O&, const Data::Area*, uint numSpace) + { + UNUSED_VARIABLE(numSpace); + assert(false); + } + template const double* retrieveHourlyResultsForCurrentYear(uint) const { diff --git a/src/solver/variable/info.h b/src/solver/variable/include/antares/solver/variable/info.h similarity index 78% rename from src/solver/variable/info.h rename to src/solver/variable/include/antares/solver/variable/info.h index b8c6e0d38c..39c6a43e42 100644 --- a/src/solver/variable/info.h +++ b/src/solver/variable/include/antares/solver/variable/info.h @@ -1,32 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_INFO_H__ #define __SOLVER_VARIABLE_INFO_H__ +#include + +#include "antares/solver/variable/surveyresults.h" +#include "antares/study/fwd.h" + namespace Antares { namespace Solver @@ -72,12 +71,14 @@ struct VariableAccessor template static void MultiplyHourlyResultsBy(U& intermediateValues, const double v) { - assert(!Yuni::Math::NaN(v)); + assert(!std::isnan(v)); for (uint i = 0; i != ColumnCountT; ++i) { Antares::Memory::Stored::ReturnType array = intermediateValues[i].hour; - for (uint y = 0; y != maxHoursInAYear; ++y) + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { array[y] *= v; + } } } @@ -87,9 +88,9 @@ struct VariableAccessor for (uint i = 0; i != ColumnCountT; ++i) { Antares::Memory::Stored::ReturnType array = intermediateValues[i].hour; - for (uint y = 0; y != maxHoursInAYear; ++y) + for (uint y = 0; y != HOURS_PER_YEAR; ++y) { - array[y] = Yuni::Math::Abs(array[y]) > 0. ? 1. : 0.; + array[y] = std::abs(array[y]) > 0. ? 1. : 0.; } } } @@ -100,8 +101,10 @@ struct VariableAccessor for (uint i = 0; i != ColumnCountT; ++i) { Antares::Memory::Stored::ReturnType array = intermediateValues[i].hour; - for (uint y = 0; y != maxHoursInAYear; ++y) - array[y] = Yuni::Math::Abs(array[y]) > 0. ? 100. : 0.; + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { + array[y] = std::abs(array[y]) > 0. ? 100. : 0.; + } } } @@ -119,7 +122,9 @@ struct VariableAccessor static void Reset(U& out) { for (uint i = 0; i != ColumnCountT; ++i) + { out[i].reset(); + } } template @@ -136,9 +141,13 @@ struct VariableAccessor { if (VCardT::spatialAggregatePostProcessing == (int)Category::spatialAggregatePostProcessingPrice) + { intermediateValues[i].computeAveragesForCurrentYearFromHourlyResults(); + } else + { intermediateValues[i].computeStatisticsForTheCurrentYear(); + } } } } @@ -157,7 +166,9 @@ struct VariableAccessor { uint64_t result = 0; for (uint i = 0; i != ColumnCountT; ++i) + { result += container[i].memoryUsage(); + } return result; } @@ -194,8 +205,11 @@ struct VariableAccessor { results.variableCaption = VCardType::Multiple::Caption(i); results.variableUnit = VCardType::Multiple::Unit(i); - container[i].template buildSurveyReport( - results, container[i], dataLevel, fileLevel, precision); + container[i].template buildSurveyReport(results, + container[i], + dataLevel, + fileLevel, + precision); } // Shift to the next internal variable's non applicable status and print status results.isCurrentVarNA++; @@ -214,8 +228,9 @@ struct VariableAccessor if (*results.isPrinted) { results.variableCaption = VCardType::Multiple::Caption(i); - container[i].template buildAnnualSurveyReport( - results, fileLevel, precision); + container[i].template buildAnnualSurveyReport(results, + fileLevel, + precision); } // Shift to the next internal variable's non applicable status and print status results.isCurrentVarNA++; @@ -232,8 +247,10 @@ struct VariableAccessor = var.retrieveRawHourlyValuesForCurrentYear(i, numSpace); assert(src != NULL); - for (uint h = 0; h != maxHoursInAYear; ++h) + for (uint h = 0; h != HOURS_PER_YEAR; ++h) + { out[i].hour[h] += src[h]; + } } } @@ -246,10 +263,12 @@ struct VariableAccessor = var.retrieveRawHourlyValuesForCurrentYear(i, numSpace); assert(src != NULL); - for (uint h = 0; h != maxHoursInAYear; ++h) + for (uint h = 0; h != HOURS_PER_YEAR; ++h) { if (out[i].hour[h] < src[h]) + { out[i].hour[h] = src[h]; + } } } } @@ -264,14 +283,16 @@ struct VariableAccessor template static void MultiplyHourlyResultsBy(U& intermediateValues, const double v) { - assert(!Yuni::Math::NaN(v)); + assert(!std::isnan(v)); double* array; const typename Type::const_iterator end = intermediateValues.end(); for (typename Type::const_iterator i = intermediateValues.begin(); i != end; ++i) { array = (*i).hour; - for (uint y = 0; y != maxHoursInAYear; ++y) + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { array[y] *= v; + } } } @@ -283,8 +304,10 @@ struct VariableAccessor for (typename Type::const_iterator i = intermediateValues.begin(); i != end; ++i) { array = (*i).hour; - for (uint y = 0; y != maxHoursInAYear; ++y) - array[y] = Yuni::Math::Abs(array[y]) > 0. ? 1. : 0.; + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { + array[y] = std::abs(array[y]) > 0. ? 1. : 0.; + } } } @@ -296,8 +319,10 @@ struct VariableAccessor for (typename Type::const_iterator i = intermediateValues.begin(); i != end; ++i) { array = (*i).hour; - for (uint y = 0; y != maxHoursInAYear; ++y) - array[y] = Yuni::Math::Abs(array[y]) > 0. ? 100. : 0.; + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { + array[y] = std::abs(array[y]) > 0. ? 100. : 0.; + } } } @@ -317,11 +342,13 @@ struct VariableAccessor { const typename Type::const_iterator end = out.end(); for (typename Type::const_iterator i = out.begin(); i != end; ++i) + { (*i).reset(); + } } template - static void ComputeStatistics(U& intermediateValues, Type& container, uint year) + static void ComputeStatistics(U& intermediateValues, Type& container, uint) { for (uint i = 0; i != container.size(); ++i) { @@ -334,10 +361,14 @@ struct VariableAccessor // Compute all statistics for the current year (daily,weekly,monthly) if (VCardT::spatialAggregatePostProcessing == (int)Category::spatialAggregatePostProcessingPrice) + { // intermediateValues[i].adjustValuesWhenRelatedToAPrice(); intermediateValues[i].computeAveragesForCurrentYearFromHourlyResults(); + } else + { intermediateValues[i].computeStatisticsForTheCurrentYear(); + } } } } @@ -357,7 +388,9 @@ struct VariableAccessor uint64_t result = 0; const typename Type::const_iterator end = container.end(); for (typename Type::const_iterator i = container.begin(); i != end; ++i) + { result += sizeof(ResultsT) + (*i).memoryUsage(); + } return result; } @@ -372,7 +405,7 @@ struct VariableAccessor const Data::PartThermal& thermal = results.data.area->thermal; for (uint i = 0; i != container.size(); ++i) { - results.variableCaption = thermal.clusters[i]->name(); + results.variableCaption = thermal.list.enabledClusterAt(i)->name(); container[i].template buildDigest(results, digestLevel, dataLevel); } @@ -382,15 +415,19 @@ struct VariableAccessor static bool setClusterCaption(SurveyResults& results, int fileLevel, uint idx) { assert(results.data.area && "Area is NULL"); - const bool thermal_details = fileLevel & Category::de; - const bool renewable_details = fileLevel & Category::de_res; - const bool st_storage_details = fileLevel & Category::de_sts; + const bool thermal_details = fileLevel & Category::FileLevel::de; + const bool renewable_details = fileLevel & Category::FileLevel::de_res; + const bool st_storage_details = fileLevel & Category::FileLevel::de_sts; - std::array kind_of_details = { thermal_details, renewable_details , st_storage_details }; + std::array kind_of_details = {thermal_details, + renewable_details, + st_storage_details}; // The current result file must be a detail file and of one kind only. // So the vector above must contain one true. No less, no more. - auto how_many_kinds_of_details = std::count(kind_of_details.begin(), kind_of_details.end(), true); + auto how_many_kinds_of_details = std::count(kind_of_details.begin(), + kind_of_details.end(), + true); if (how_many_kinds_of_details != 1) { @@ -401,19 +438,19 @@ struct VariableAccessor if (thermal_details) { auto& thermal = results.data.area->thermal; - results.variableCaption = thermal.clusters[idx]->name(); + results.variableCaption = thermal.list.enabledClusterAt(idx)->name(); return true; } if (renewable_details) { auto& renewable = results.data.area->renewable; - results.variableCaption = renewable.clusters[idx]->name(); + results.variableCaption = renewable.list.enabledClusterAt(idx)->name(); return true; } if (st_storage_details) { auto& st_storage_part = results.data.area->shortTermStorage; - results.variableCaption = st_storage_part.storagesByIndex[idx]->properties.name; + results.variableCaption = st_storage_part.storagesByIndex[idx].properties.name; return true; } return true; @@ -433,11 +470,16 @@ struct VariableAccessor { res = setClusterCaption(results, fileLevel, i); if (!res) + { return; + } results.variableUnit = VCardType::Unit(); - container[i].template buildSurveyReport( - results, container[i], dataLevel, fileLevel, precision); + container[i].template buildSurveyReport(results, + container[i], + dataLevel, + fileLevel, + precision); } } } @@ -455,9 +497,12 @@ struct VariableAccessor { res = setClusterCaption(results, fileLevel, i); if (!res) + { return; - container[i].template buildAnnualSurveyReport( - results, fileLevel, precision); + } + container[i].template buildAnnualSurveyReport(results, + fileLevel, + precision); } } } @@ -471,8 +516,10 @@ struct VariableAccessor = var.retrieveRawHourlyValuesForCurrentYear(i, numSpace); assert(src != NULL); - for (uint h = 0; h != maxHoursInAYear; ++h) + for (uint h = 0; h != HOURS_PER_YEAR; ++h) + { out[i].hour[h] += src[h]; + } } } @@ -485,10 +532,12 @@ struct VariableAccessor = var.retrieveRawHourlyValuesForCurrentYear(i, numSpace); assert(src != NULL); - for (uint h = 0; h != maxHoursInAYear; ++h) + for (uint h = 0; h != HOURS_PER_YEAR; ++h) { if (out[i].hour[h] < src[h]) + { out[i].hour[h] = src[h]; + } } } } @@ -503,24 +552,29 @@ struct VariableAccessor template static void MultiplyHourlyResultsBy(U& intermediateValues, const double v) { - assert(!Yuni::Math::NaN(v)); - for (uint y = 0; y != maxHoursInAYear; ++y) + assert(!std::isnan(v)); + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { intermediateValues.hour[y] *= v; + } } template static void SetTo1IfPositive(U& intermediateValues) { - for (uint y = 0; y != maxHoursInAYear; ++y) - intermediateValues.hour[y] = Yuni::Math::Abs(intermediateValues.hour[y]) > 0. ? 1. : 0.; + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { + intermediateValues.hour[y] = std::abs(intermediateValues.hour[y]) > 0. ? 1. : 0.; + } } template static void Or(U& intermediateValues) { - for (uint y = 0; y != maxHoursInAYear; ++y) - intermediateValues.hour[y] - = Yuni::Math::Abs(intermediateValues.hour[y]) > 0. ? 100. : 0.; + for (uint y = 0; y != HOURS_PER_YEAR; ++y) + { + intermediateValues.hour[y] = std::abs(intermediateValues.hour[y]) > 0. ? 100. : 0.; + } } template @@ -548,10 +602,14 @@ struct VariableAccessor // Compute all statistics for the current year (daily,weekly,monthly) if (VCardT::spatialAggregatePostProcessing == (int)Category::spatialAggregatePostProcessingPrice) + { // intermediateValues[i].adjustValuesWhenRelatedToAPrice(); intermediateValues.computeAveragesForCurrentYearFromHourlyResults(); + } else + { intermediateValues.computeStatisticsForTheCurrentYear(); + } } } @@ -596,8 +654,11 @@ struct VariableAccessor results.variableCaption = VCardType::Caption(); results.variableUnit = VCardType::Unit(); } - container.template buildSurveyReport( - results, container, dataLevel, fileLevel, precision); + container.template buildSurveyReport(results, + container, + dataLevel, + fileLevel, + precision); } } @@ -622,8 +683,10 @@ struct VariableAccessor = var.retrieveRawHourlyValuesForCurrentYear(-1, numSpace); assert(src != NULL); - for (uint h = 0; h != maxHoursInAYear; ++h) + for (uint h = 0; h != HOURS_PER_YEAR; ++h) + { out.hour[h] += src[h]; + } } template @@ -633,10 +696,12 @@ struct VariableAccessor = var.retrieveRawHourlyValuesForCurrentYear(-1, numSpace); assert(src != NULL); - for (uint h = 0; h != maxHoursInAYear; ++h) + for (uint h = 0; h != HOURS_PER_YEAR; ++h) { if (out.hour[h] < src[h]) + { out.hour[h] = src[h]; + } } } }; @@ -705,13 +770,13 @@ struct VariableAccessor } template - static void ComputeSum(U&, const VarT&, uint numSpace) + static void ComputeSum(U&, const VarT&, uint) { // Do nothing } template - static void ComputeMax(U&, const VarT&, uint numSpace) + static void ComputeMax(U&, const VarT&, uint) { // Do nothing } @@ -742,8 +807,9 @@ struct SpatialAggregateOperation static void Perform(U& intermediateResults, const VarT& var, uint numSpace) { typedef typename VCardT::ResultsType ResultsType; - VariableAccessor::ComputeSum( - intermediateResults, var, numSpace); + VariableAccessor::ComputeSum(intermediateResults, + var, + numSpace); } }; @@ -755,8 +821,9 @@ struct SpatialAggregateOperation static void Perform(U& intermediateResults, const VarT& var, uint numSpace) { typedef typename VCardT::ResultsType ResultsType; - VariableAccessor::ComputeSum( - intermediateResults, var, numSpace); + VariableAccessor::ComputeSum(intermediateResults, + var, + numSpace); } }; @@ -768,8 +835,9 @@ struct SpatialAggregateOperation::ComputeSum( - intermediateResults, var, numSpace); + VariableAccessor::ComputeSum(intermediateResults, + var, + numSpace); } }; @@ -781,8 +849,9 @@ struct SpatialAggregateOperation::ComputeSum( - intermediateResults, var, numSpace); + VariableAccessor::ComputeSum(intermediateResults, + var, + numSpace); } }; @@ -794,8 +863,9 @@ struct SpatialAggregateOperation static void Perform(U& intermediateResults, const VarT& var, uint numSpace) { typedef typename VCardT::ResultsType ResultsType; - VariableAccessor::ComputeMax( - intermediateResults, var, numSpace); + VariableAccessor::ComputeMax(intermediateResults, + var, + numSpace); } }; diff --git a/src/solver/variable/include/antares/solver/variable/print.h b/src/solver/variable/include/antares/solver/variable/print.h new file mode 100644 index 0000000000..5ac4b0617a --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/print.h @@ -0,0 +1,179 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_PRINT_H__ +#define __SOLVER_VARIABLE_PRINT_H__ + +#include + +namespace Antares::Solver::Variable +{ +class PrintInfosStdCout final +{ +public: + PrintInfosStdCout(): + pIndent(0) + { + } + + template + void beginNode() + { + printVCard(); + ++pIndent; + } + + template + void addVCard() + { + printVCard(); + } + + void endNode() + { + --pIndent; + } + +private: + template + void printVCard() + { + pBuffer.clear(); + pBuffer.resize(1 + pBuffer.size() + pIndent * 4, " "); + pBuffer += (IsNodeT ? "+ " : " "); + pBuffer += VCardT::Caption(); + pBuffer.resize(29, " "); + pBuffer += VCardT::Unit(); + pBuffer.resize(37, " "); + pBuffer += VCardT::Description(); + Antares::logs.info() << pBuffer; + } + + void printIndent() + { + if (pIndent) + { + for (uint i = 0; i != pIndent; ++i) + { + pBuffer += " "; + } + } + } + +private: + uint pIndent; + Yuni::String pBuffer; +}; + +template +struct PrecisionToPrintfFormat +{ + static const char* Value() + { + return "%.6f"; + } +}; + +template<> +struct PrecisionToPrintfFormat<0> +{ + static const char* Value() + { + return "%.0f"; + } +}; + +template<> +struct PrecisionToPrintfFormat<1> +{ + static const char* Value() + { + return "%.1f"; + } +}; + +template<> +struct PrecisionToPrintfFormat<2> +{ + static const char* Value() + { + return "%.2f"; + } +}; + +template<> +struct PrecisionToPrintfFormat<3> +{ + static const char* Value() + { + return "%.3f"; + } +}; + +template<> +struct PrecisionToPrintfFormat<4> +{ + static const char* Value() + { + return "%.4f"; + } +}; + +template<> +struct PrecisionToPrintfFormat<5> +{ + static const char* Value() + { + return "%.5f"; + } +}; + +template +static inline void AssignPrecisionToPrintfFormat(StringT& out, uint precision) +{ + switch (precision) + { + case 0: + out.assign("%.0f", 4); + break; + case 1: + out.assign("%.1f", 4); + break; + case 2: + out.assign("%.2f", 4); + break; + case 3: + out.assign("%.3f", 4); + break; + case 4: + out.assign("%.4f", 4); + break; + case 5: + out.assign("%.5f", 4); + break; + default: + out.assign("%.6f", 4); + break; + } +} + +} // namespace Antares::Solver::Variable + +#endif // __SOLVER_VARIABLE_PRINT_H__ diff --git a/src/solver/variable/setofareas.h b/src/solver/variable/include/antares/solver/variable/setofareas.h similarity index 77% rename from src/solver/variable/setofareas.h rename to src/solver/variable/include/antares/solver/variable/setofareas.h index 79e8ca7e8e..d2444df247 100644 --- a/src/solver/variable/setofareas.h +++ b/src/solver/variable/include/antares/solver/variable/setofareas.h @@ -1,35 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_SET_OF_AREAS_H__ #define __SOLVER_VARIABLE_SET_OF_AREAS_H__ -#include "state.h" #include +#include "state.h" + namespace Antares { namespace Solver @@ -43,6 +38,7 @@ struct VCardAllSetsOfAreas { return "Sets of Areas"; } + //! Unit static std::string Unit() { @@ -58,21 +54,19 @@ struct VCardAllSetsOfAreas //! The expecte results typedef Results<> ResultsType; - enum - { - //! Data Level - categoryDataLevel = Category::area, - //! File level (provided by the type of the results) - categoryFileLevel = ResultsType::categoryFile & Category::de, - //! Indentation (GUI) - nodeDepthForGUI = +1, - //! Number of columns used by the variable (One ResultsType per column) - columnCount = 0, - //! The Spatial aggregation - spatialAggregate = Category::noSpatialAggregate, - //! Intermediate values - hasIntermediateValues = 0, - }; + //! Data Level + static constexpr uint8_t categoryDataLevel = Category::DataLevel::area; + //! File level (provided by the type of the results) + static constexpr uint8_t categoryFileLevel = ResultsType::categoryFile + & Category::FileLevel::de; + //! Indentation (GUI) + static constexpr uint8_t nodeDepthForGUI = +1; + //! Number of columns used by the variable (One ResultsType per column) + static constexpr int columnCount = 0; + //! The Spatial aggregation + static constexpr uint8_t spatialAggregate = Category::noSpatialAggregate; + //! Intermediate values + static constexpr uint8_t hasIntermediateValues = 0; }; // class VCard @@ -101,7 +95,8 @@ class SetsOfAreas { enum { - count = NextType::template Statistics::count + count = NextType::template Statistics < CDataLevel, + CFile > ::count }; }; @@ -135,7 +130,7 @@ class SetsOfAreas void yearBegin(unsigned int year, unsigned int numSpace); - void yearEndBuild(State& state, unsigned int year); + void yearEndBuild(State& state, unsigned int year, unsigned int numSpace); void yearEnd(unsigned int year, unsigned int numSpace); @@ -143,12 +138,12 @@ class SetsOfAreas unsigned int nbYearsForCurrentSummary); void hourBegin(unsigned int hourInTheYear); - void hourForEachArea(State& state); + void hourForEachArea(State& state, unsigned int numSpace); void hourForEachLink(State& state); void hourEnd(State& state, unsigned int hourInTheYear); void weekBegin(State&); - void weekForEachArea(State&); + void weekForEachArea(State&, unsigned int numSpace); void weekEnd(State&); void buildSurveyReport(SurveyResults& results, @@ -186,7 +181,7 @@ class SetsOfAreas void computeSpatialAggregateWith(O& out); template - void computeSpatialAggregateWith(O& out, const Data::Area* area); + void computeSpatialAggregateWith(O& out, const Data::Area* area, uint numSpace); template const double* retrieveHourlyResultsForCurrentYear() const; diff --git a/src/solver/variable/setofareas.hxx b/src/solver/variable/include/antares/solver/variable/setofareas.hxx similarity index 81% rename from src/solver/variable/setofareas.hxx rename to src/solver/variable/include/antares/solver/variable/setofareas.hxx index 2936fa6bfa..630ded8903 100644 --- a/src/solver/variable/setofareas.hxx +++ b/src/solver/variable/include/antares/solver/variable/setofareas.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_SET_OF_AREAS_HXX__ #define __SOLVER_VARIABLE_SET_OF_AREAS_HXX__ @@ -44,7 +38,9 @@ inline SetsOfAreas::~SetsOfAreas() { // Releasing the memory occupied by the areas for (typename SetOfAreasVector::iterator i = pBegin; i != pEnd; ++i) + { delete *i; + } } template @@ -64,7 +60,9 @@ void SetsOfAreas::initializeFromStudy(Data::Study& study) for (uint setIndex = 0; setIndex != sets.size(); ++setIndex) { if (!sets.hasOutput(setIndex)) + { continue; + } // Name of the set const auto& setname = sets.caption(setIndex); @@ -146,7 +144,7 @@ inline void SetsOfAreas::yearBegin(uint /*year*/, uint /* numSpace */) } template -inline void SetsOfAreas::yearEndBuild(State& /*state*/, uint /*year*/) +inline void SetsOfAreas::yearEndBuild(State& /*state*/, uint /*year*/, uint /*numSpace*/) { // Nothing to do here } @@ -178,7 +176,7 @@ inline void SetsOfAreas::weekBegin(State&) } template -inline void SetsOfAreas::weekForEachArea(State&) +inline void SetsOfAreas::weekForEachArea(State&, unsigned int /*numSpace*/) { // Nothing to do here } @@ -190,7 +188,7 @@ inline void SetsOfAreas::weekEnd(State&) } template -void SetsOfAreas::hourForEachArea(State& state) +void SetsOfAreas::hourForEachArea(State& state, unsigned int) { (void)state; } @@ -215,11 +213,13 @@ inline void SetsOfAreas::buildSurveyReport(SurveyResults& results, int precision) const { int count_int = count; - bool setOfAreasDataLevel = dataLevel & Category::setOfAreas; + bool setOfAreasDataLevel = dataLevel & Category::DataLevel::setOfAreas; if (count_int && setOfAreasDataLevel) { - pSetsOfAreas[results.data.setOfAreasIndex]->buildSurveyReport( - results, dataLevel, fileLevel, precision); + pSetsOfAreas[results.data.setOfAreasIndex]->buildSurveyReport(results, + dataLevel, + fileLevel, + precision); } } @@ -231,11 +231,14 @@ inline void SetsOfAreas::buildAnnualSurveyReport(SurveyResults& results, uint numSpace) const { int count_int = count; - bool setOfAreasDataLevel = dataLevel & Category::setOfAreas; + bool setOfAreasDataLevel = dataLevel & Category::DataLevel::setOfAreas; if (count_int && setOfAreasDataLevel) { - pSetsOfAreas[results.data.setOfAreasIndex]->buildAnnualSurveyReport( - results, dataLevel, fileLevel, precision, numSpace); + pSetsOfAreas[results.data.setOfAreasIndex]->buildAnnualSurveyReport(results, + dataLevel, + fileLevel, + precision, + numSpace); } } @@ -243,7 +246,7 @@ template void SetsOfAreas::buildDigest(SurveyResults& results, int digestLevel, int dataLevel) const { int count_int = count; - bool setOfAreasDataLevel = dataLevel & Category::setOfAreas; + bool setOfAreasDataLevel = dataLevel & Category::DataLevel::setOfAreas; if (count_int && setOfAreasDataLevel) { // Reset @@ -268,7 +271,9 @@ inline uint64_t SetsOfAreas::memoryUsage() const { uint64_t result = sizeof(NextType) * pSetsOfAreas.size(); for (auto i = pBegin; i != pEnd; ++i) + { result += (*i)->memoryUsage(); + } return result; } @@ -301,8 +306,10 @@ void SetsOfAreas::yearEndSpatialAggregates(V& allVars, uint year, uint nu for (uint setindex = 0; setindex != pSetsOfAreas.size(); ++setindex) { assert(setindex < pOriginalSets.size()); - pSetsOfAreas[setindex]->yearEndSpatialAggregates( - allVars, year, *(pOriginalSets[setindex]), numSpace); + pSetsOfAreas[setindex]->yearEndSpatialAggregates(allVars, + year, + *(pOriginalSets[setindex]), + numSpace); } } @@ -316,8 +323,9 @@ void SetsOfAreas::computeSpatialAggregatesSummary( for (uint setindex = 0; setindex != pSetsOfAreas.size(); ++setindex) { assert(setindex < pOriginalSets.size()); - pSetsOfAreas[setindex]->computeSpatialAggregatesSummary( - allVars, numSpaceToYear, nbYearsForCurrentSummary); + pSetsOfAreas[setindex]->computeSpatialAggregatesSummary(allVars, + numSpaceToYear, + nbYearsForCurrentSummary); } } @@ -349,10 +357,13 @@ inline void SetsOfAreas::computeSpatialAggregateWith(O&) template template -inline void SetsOfAreas::computeSpatialAggregateWith(O& out, const Data::Area* area) +inline void SetsOfAreas::computeSpatialAggregateWith(O& out, + const Data::Area* area, + uint numSpace) { (void)out; (void)area; + (void)numSpace; // pSetsOfAreas[area->index]->computeSpatialAggregateWith(out); } diff --git a/src/solver/variable/include/antares/solver/variable/state.h b/src/solver/variable/include/antares/solver/variable/state.h new file mode 100644 index 0000000000..eb3edda98c --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/state.h @@ -0,0 +1,244 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STATE_H__ +#define __SOLVER_VARIABLE_STATE_H__ + +#include +#include + +#include + +#include +#include +#include "antares/solver/simulation/sim_extern_variables_globales.h" +#include "antares/solver/simulation/sim_structure_donnees.h" +#include "antares/solver/simulation/sim_structure_probleme_economique.h" + +namespace Antares::Solver::Variable +{ +class ThermalState +{ +public: + explicit ThermalState(const Data::AreaList& areas); + + class StateForAnArea + { + public: + void initializeFromArea(const Data::Area& area); + //! Thermal production for thermal clusters for the current hour in the year + std::vector thermalClustersProductions; + + //! The operating cost for all clusters at the current hour (production level*production + //! cost + NP Cost) + std::vector thermalClustersOperatingCost; + + //! Number of units turned ON by cluster for the current hour in the year with the ucMILP + //! (accurate) unit commitment mode + std::vector numberOfUnitsONbyCluster; + + //! Minimum power of all clusters for the current hour in the year + std::vector PMinOfClusters; + + std::vector unitCountLastHour; + std::vector productionLastHour; + std::vector pminOfAGroup; + }; + + StateForAnArea& operator[](size_t areaIndex); + +private: + std::vector thermal; +}; + +class State +{ +public: + explicit State(Data::Study& s); + + /*! + ** \brief Initialize some variables according an area index + ** + ** \param areaIndex Index of the area + */ + void initFromAreaIndex(const unsigned int areaIndex, uint numSpace); + + /*! + ** \brief Initialize some variable according a thermal cluster index + ** + ** We assume here that the variables related to an area + ** are properly initialized. + ** + ** \param areaWideIndex Index of the thermal cluster for the current area + */ + void initFromThermalClusterIndex(const unsigned int areaWideIndex); + + /*! + ** \brief End the year by smoothing the thermal units run + ** and computing costs. + ** We assume here that the variables related to an area + ** are properly initialized. + ** + ** \param areaWideIndex Index of the thermal cluster for the current area + */ + + void yearEndBuildFromThermalClusterIndex(const unsigned int areaWideIndex); + +private: + /*! + ** \brief Initialize some variable according a thermal cluster index + ** + ** Called in initFromAreaIndex to split code + ** + ** \param areaWideIndex Index of the thermal cluster for the current area + */ + void initFromThermalClusterIndexProduction(const unsigned int areaWideIndex); + + void yearEndBuildThermalClusterCalculateStartupCosts( + const uint& maxDurationON, + const std::array& ON_min, + const std::array& ON_opt, + const Data::ThermalCluster* currentCluster); + + std::array computeEconomicallyOptimalNbClustersONforEachHour( + const uint& maxDurationON, + const std::array& ON_min, + const std::array& ON_max) const; + + /*! + ** \brief Smooth the thermal units run after resolutions + ** using heuristics + ** + ** \param areaWideIndex Index of the thermal cluster for the current area + */ + void yearEndSmoothDispatchedUnitsCount(const unsigned int areaWideIndex, uint numSpace); + +public: + /*! + ** \brief Reset internal data + */ + void startANewYear(); + + /*! + ** \brief Reset thermal internal data for end of year calculations + */ + void yearEndResetThermal(); + + //! Current year + unsigned int year; + //! Current week for current year (zero-based) + unsigned int weekInTheYear; + //! Current hour in the year (zero-based) + unsigned int hourInTheYear; + //! Current hour in the week (zero-based) + unsigned int hourInTheWeek; + //! Current hour from the begining of the simulation + unsigned int hourInTheSimulation; + + //! The current area + Data::Area* area; + + //! The current thermal cluster (used in yearEndBuildForEachThermalCluster functions) + Data::ThermalCluster* thermalCluster; + + //! The current renewable cluster + Data::RenewableCluster* renewableCluster; + //! The Scratchpad for the current area + Data::AreaScratchpad* scratchpad; + //! The current link + Data::AreaLink* link; + + //! \name Adequacy + //@{ + /*! + ** \brief Spilled energy for all areas in the week + */ + Matrix<> resSpilled; + //@} + + //! \name Economy + //@{ + RESULTATS_HORAIRES* hourlyResults; + //! NTC Values + VALEURS_DE_NTC_ET_RESISTANCES ntc; + + //! Thermal production for the current thermal cluster for the whole year + double thermalClusterProductionForYear[HOURS_PER_YEAR]; + //! Number of unit dispatched for all clusters for the whole year for ucHeruistic (fast) or + //! ucMILP (accurate) + uint thermalClusterDispatchedUnitsCountForYear[HOURS_PER_YEAR]; + + //! Thermal operating cost for the current thermal cluster for the whole year + double thermalClusterOperatingCostForYear[HOURS_PER_YEAR]; + //! Thermal NP Cost for the current thermal cluster for the whole year + double thermalClusterNonProportionalCostForYear[HOURS_PER_YEAR]; + //! Minimum power of the cluster for the whole year + double thermalClusterPMinOfTheClusterForYear[HOURS_PER_YEAR]; + + double renewableClusterProduction; + + //! Dispatchable margin for the current area (valid only from weekForEachArea) + const double* dispatchableMargin; + //@} + + //! Probleme Hebdo + PROBLEME_HEBDO* problemeHebdo; + + //! Simulation mode: economy / adequacy / expansion + Data::SimulationMode simulationMode; + //! Study unit commitment mode: fast(ucHeuristic) / accurate(ucMILP) + Data::UnitCommitmentMode unitCommitmentMode; + //! Reference to the original study + Data::Study& study; + // Thermal data, used to compute overall cost, etc. + ThermalState thermal; + //! Index of the state in the state vector + unsigned int numSpace; + /*! + ** \brief Flag to know if the simplex has been used for the current week + */ + bool simplexRunNeeded; + + // Annual costs to be printed in output into separate files + // ----------------------------------------------------------------- + // Sum over all year's hours of : + // - sum over all areas of variable "overall cost" + // - sum over all links of variable "hurdle cost". + // That is : Somme(h in Y)[ Somme(a in areas)(OV. COST[h,a]) + Somme(l in links)(HURDLE + // COST[h,l]) ] + double annualSystemCost = 0.; + /// Sum of the weekly optimal costs over the year (first optimisation step) + double optimalSolutionCost1 = 0.; + /// Sum of the weekly optimal costs over the year (second optimisation step) + double optimalSolutionCost2 = 0.; + /// Average time spent in first optimization over the year (ms) + double averageOptimizationTime1 = 0.; + /// Average time spent in second optimization over the year (ms) + double averageOptimizationTime2 = 0.; + /// Average time spent updating the problem over the year (ms) + double averageUpdateTime = 0.; + // ----------------------------------------------------------------- +}; // class State + +} // namespace Antares::Solver::Variable + +#include "state.hxx" + +#endif // __SOLVER_VARIABLE_STATE_H__ diff --git a/src/solver/variable/include/antares/solver/variable/state.hxx b/src/solver/variable/include/antares/solver/variable/state.hxx new file mode 100644 index 0000000000..a6649f52ec --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/state.hxx @@ -0,0 +1,91 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STATE_HXX__ +#define __SOLVER_VARIABLE_STATE_HXX__ + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +inline void State::startANewYear() +{ + hourInTheSimulation = 0u; + + memset(thermalClusterProductionForYear, 0, sizeof(thermalClusterProductionForYear)); + memset(thermalClusterOperatingCostForYear, 0, sizeof(thermalClusterOperatingCostForYear)); + memset(thermalClusterNonProportionalCostForYear, + 0, + sizeof(thermalClusterNonProportionalCostForYear)); + memset(thermalClusterPMinOfTheClusterForYear, 0, sizeof(thermalClusterPMinOfTheClusterForYear)); + memset(thermalClusterDispatchedUnitsCountForYear, + 0, + sizeof(thermalClusterDispatchedUnitsCountForYear)); + + // Re-initializing annual costs (to be printed in output into separate files) + annualSystemCost = 0.; + optimalSolutionCost1 = 0.; + optimalSolutionCost2 = 0.; + averageOptimizationTime1 = 0.; + averageOptimizationTime2 = 0.; + averageUpdateTime = 0.; +} + +inline void State::yearEndResetThermal() +{ + memset(thermalClusterProductionForYear, 0, sizeof(thermalClusterProductionForYear)); + memset(thermalClusterOperatingCostForYear, 0, sizeof(thermalClusterOperatingCostForYear)); + memset(thermalClusterNonProportionalCostForYear, + 0, + sizeof(thermalClusterNonProportionalCostForYear)); + memset(thermalClusterPMinOfTheClusterForYear, 0, sizeof(thermalClusterPMinOfTheClusterForYear)); + memset(thermalClusterDispatchedUnitsCountForYear, + 0, + sizeof(thermalClusterDispatchedUnitsCountForYear)); +} + +inline void State::initFromAreaIndex(const unsigned int areaIndex, uint numSpace) +{ + area = study.areas[areaIndex]; + scratchpad = &area->scratchpad[numSpace]; + thermalCluster = nullptr; + + switch (simulationMode) + { + case Data::SimulationMode::Adequacy: + case Data::SimulationMode::Economy: + case Data::SimulationMode::Expansion: + { + hourlyResults = &problemeHebdo->ResultatsHoraires[areaIndex]; + break; + } + + case Data::SimulationMode::Unknown: + break; + } +} + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STATE_HXX__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/average.h b/src/solver/variable/include/antares/solver/variable/storage/average.h new file mode 100644 index 0000000000..380915e284 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/average.h @@ -0,0 +1,231 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_AVERAGE_H__ +#define __SOLVER_VARIABLE_STORAGE_AVERAGE_H__ + +#include "averagedata.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +template +struct Average: public NextT +{ +public: + //! Type of the net item in the list + typedef NextT NextType; + + enum + { + //! The count if item in the list + count = 1 + NextT::count, + + categoryFile = NextT::categoryFile | Variable::Category::FileLevel::allFile, + }; + + struct Data + { + double value; + uint32_t indice; + }; + + //! Name of the filter + static const char* Name() + { + return "average"; + } + +public: + Average() + { + } + +protected: + void initializeFromStudy(Antares::Data::Study& study) + { + avgdata.initializeFromStudy(study); + // Next + NextType::initializeFromStudy(study); + } + + void reset() + { + // Reset + avgdata.reset(); + // Next + NextType::reset(); + } + + void merge(uint year, const IntermediateValues& rhs) + { + avgdata.merge(year, rhs); + // Next + NextType::merge(year, rhs); + } + + template + void buildSurveyReport(SurveyResults& report, + const S& results, + int dataLevel, + int fileLevel, + int precision) const + { + if (!(fileLevel & Category::FileLevel::id)) + { + switch (precision) + { + case Category::hourly: + InternalExportValues(report, + Memory::RawPointer( + avgdata.hourly)); + break; + case Category::daily: + InternalExportValues(report, avgdata.daily); + break; + case Category::weekly: + InternalExportValues(report, + avgdata.weekly); + break; + case Category::monthly: + InternalExportValues(report, + avgdata.monthly); + break; + case Category::annual: + InternalExportValues<1, VCardT, Category::annual>(report, avgdata.year); + break; + } + } + // Next + NextType::template buildSurveyReport(report, + results, + dataLevel, + fileLevel, + precision); + } + + template + void buildDigest(SurveyResults& report, int digestLevel, int dataLevel) const + { + const bool isCluster = (VCardT::categoryFileLevel & Category::FileLevel::de) + || (VCardT::categoryFileLevel & Category::FileLevel::de_res); + const bool isBindingConstraint = VCardT::categoryFileLevel & Category::FileLevel::bc; + const bool isDigest = digestLevel & Category::digestAllYears; + if ((dataLevel & Category::DataLevel::area || dataLevel & Category::DataLevel::setOfAreas) + && isDigest && !isCluster && !isBindingConstraint) + { + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = (report.variableCaption == "LOLP") + ? "values" + : "EXP"; + + // Precision + report.precision[report.data.columnIndex] = PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + // Value + report.values[report.data.columnIndex][report.data.rowIndex] = avgdata.allYears; + // Non applicability + report.digestNonApplicableStatus[report.data.rowIndex][report.data.columnIndex] + = *report.isCurrentVarNA; + + ++(report.data.columnIndex); + } + // Next + NextType::template buildDigest(report, digestLevel, dataLevel); + } + + uint64_t memoryUsage() const + { + return avgdata.dynamicMemoryUsage() + NextType::memoryUsage(); + } + + template class DecoratorT> + Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const + { + if (Yuni::Static::Type::StrictlyEqual, Average>::Yes) + { + return avgdata.hourly; + } + return NextType::template hourlyValuesForSpatialAggregate(); + } + +public: + AverageData avgdata; + +private: + template + void InternalExportValues(SurveyResults& report, const double* array) const + { + assert(array); + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + // Caption + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = (report.variableCaption == "LOLP") ? "values" + : "EXP"; + // Precision + report.precision[report.data.columnIndex] = PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + // Non applicability + report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; + + // Values + switch (PrecisionT) + { + case Category::annual: + { + double& target = *(report.values[report.data.columnIndex]); + target = 0; + for (uint i = 0; i != avgdata.nbYearsCapacity; ++i) + { + target += array[i]; + } + avgdata.allYears = target; + break; + } + default: + (void)::memcpy(report.values[report.data.columnIndex], array, sizeof(double) * Size); + break; + } + + // Next column index + ++report.data.columnIndex; + } + +}; // class Average + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_AVERAGE_H__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/averagedata.h b/src/solver/variable/include/antares/solver/variable/storage/averagedata.h new file mode 100644 index 0000000000..0ed11ae239 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/averagedata.h @@ -0,0 +1,79 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_AVERAGE_DATA_H__ +#define __SOLVER_VARIABLE_STORAGE_AVERAGE_DATA_H__ + +#include +#include "antares/solver/variable/storage/intermediate.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +class AverageData +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + AverageData(); + //! Destructor + ~AverageData(); + + void initializeFromStudy(Data::Study& study); + + void reset(); + + void merge(unsigned int year, const IntermediateValues& rhs); + + uint64_t dynamicMemoryUsage() const + { + return sizeof(double) * HOURS_PER_YEAR + sizeof(double) * nbYearsCapacity; + } + +public: + double monthly[MONTHS_PER_YEAR]; + double weekly[WEEKS_PER_YEAR]; + double daily[DAYS_PER_YEAR]; + Antares::Memory::Stored::Type hourly; + double* year; + unsigned int nbYearsCapacity; + mutable double allYears; // FIX MEEE - Remove the mutable as soon as possible + std::vector yearsWeight; + float yearsWeightSum; + +}; // class AverageData + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_AVERAGE_DATA_H__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/empty.h b/src/solver/variable/include/antares/solver/variable/storage/empty.h new file mode 100644 index 0000000000..354c0f4545 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/empty.h @@ -0,0 +1,91 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_EMPTY_H__ +#define __SOLVER_VARIABLE_STORAGE_EMPTY_H__ + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +struct Empty +{ +public: + //! Name of the filter + const char* Name() + { + return NULL; + } + + enum + { + //! The count if item in the list + count = 0, + categoryFile = 0, + }; + +protected: + static void initializeFromStudy(const Data::Study&) + { + // Does nothing + } + + static void reset() + { + // Does nothing + } + + static void merge(unsigned int /*year*/, const IntermediateValues& /*rhs*/) + { + // Does nothing + } + + template + static void buildSurveyReport(SurveyResults&, const S&, int, int, int) + { + // Does nothing + } + + template + static void buildDigest(SurveyResults&, int, int) + { + // Does nothing + } + + static uint64_t memoryUsage() + { + return 0; + } + + template class DecoratorT> + static Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() + { + return Antares::Memory::Stored::NullValue(); + } + +}; // class Empty + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_EMPTY_H__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/fwd.h b/src/solver/variable/include/antares/solver/variable/storage/fwd.h new file mode 100644 index 0000000000..cca8a92e83 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/fwd.h @@ -0,0 +1,51 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_FORWARD_H__ +#define __SOLVER_VARIABLE_STORAGE_FORWARD_H__ + +#include "../categories.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +// Forward declaration +struct Empty; + +namespace R +{ +namespace AllYears +{ +template +struct Raw; + +template +struct Or; + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_FORWARD_H__ diff --git a/src/solver/variable/storage/intermediate.h b/src/solver/variable/include/antares/solver/variable/storage/intermediate.h similarity index 83% rename from src/solver/variable/storage/intermediate.h rename to src/solver/variable/include/antares/solver/variable/storage/intermediate.h index 48c24480c6..e7c1757c62 100644 --- a/src/solver/variable/storage/intermediate.h +++ b/src/solver/variable/include/antares/solver/variable/storage/intermediate.h @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_H__ #define __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_H__ #include #include -#include "../constants.h" + #include +#include "antares/antares/constants.h" + #include "../categories.h" #include "../surveyresults.h" @@ -137,11 +133,11 @@ class IntermediateValues final Antares::Data::StudyRuntimeInfos* pRuntimeInfo; //! Values for each month - Type month[maxMonths]; + Type month[MONTHS_PER_YEAR]; //! Values for each week - Type week[maxWeeksInAYear]; + Type week[WEEKS_PER_YEAR]; //! Values for each day in the year - Type day[maxDaysInAYear]; + Type day[DAYS_PER_YEAR]; //! Values for each hour in the year mutable Antares::Memory::Stored::Type hour; //! Year @@ -152,6 +148,7 @@ class IntermediateValues final IntermediateValues(const IntermediateValues&) { } + IntermediateValues& operator=(const IntermediateValues&) { return *this; diff --git a/src/solver/variable/include/antares/solver/variable/storage/intermediate.hxx b/src/solver/variable/include/antares/solver/variable/storage/intermediate.hxx new file mode 100644 index 0000000000..9dd74a235a --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/intermediate.hxx @@ -0,0 +1,125 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_HXX__ +#define __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_HXX__ + +#include + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +inline IntermediateValues::~IntermediateValues() +{ + Antares::Memory::Release(hour); +} + +inline void IntermediateValues::reset() +{ + Antares::Memory::Zero(HOURS_PER_YEAR, hour); + memset(month, 0, sizeof(month)); + memset(week, 0, sizeof(week)); + memset(day, 0, sizeof(day)); +} + +inline IntermediateValues::Type& IntermediateValues::operator[](const unsigned int index) +{ + return hour[index]; +} + +inline const IntermediateValues::Type& IntermediateValues::operator[]( + const unsigned int index) const +{ + return hour[index]; +} + +inline uint64_t IntermediateValues::MemoryUsage() +{ + return +sizeof(Type) * HOURS_PER_YEAR; +} + +template +inline void IntermediateValues::buildAnnualSurveyReport(SurveyResults& report, + int fileLevel, + int precision) const +{ + if (!(fileLevel & Category::FileLevel::id)) + { + switch (precision) + { + case Category::hourly: + internalExportAnnualValues(report, hour, false); + break; + case Category::daily: + internalExportAnnualValues(report, day, false); + break; + case Category::weekly: + internalExportAnnualValues(report, week, false); + break; + case Category::monthly: + internalExportAnnualValues(report, month, false); + break; + case Category::annual: + internalExportAnnualValues<1, VCardT>(report, &year, true); + break; + } + } +} + +template +void IntermediateValues::internalExportAnnualValues(SurveyResults& report, + const A& array, + bool annual) const +{ + using namespace Yuni; + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + // Caption + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = nullptr; + // Precision + report.precision[report.data.columnIndex] = PrecisionToPrintfFormat::Value(); + // Non applicability + report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; + + // Values + if (not annual) + { + (void)::memcpy(report.values[report.data.columnIndex], array, sizeof(double) * Size); + } + else + { + double& target = *(report.values[report.data.columnIndex]); + target = year; + } + + // Next column index + ++report.data.columnIndex; +} + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_HXX__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/minmax-data.h b/src/solver/variable/include/antares/solver/variable/storage/minmax-data.h new file mode 100644 index 0000000000..27bc3e89b4 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/minmax-data.h @@ -0,0 +1,58 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_MINMAX_DATA_H__ +#define __SOLVER_VARIABLE_STORAGE_MINMAX_DATA_H__ + +#include + +#include "antares/solver/variable/storage/intermediate.h" + +namespace Antares::Solver::Variable::R::AllYears +{ +class MinMaxData +{ +public: + struct Data + { + double value; + uint32_t indice; + }; + + MinMaxData() = default; + ~MinMaxData() = default; + + void resetInf(); + void resetSup(); + + void mergeInf(uint year, const IntermediateValues& rhs); + void mergeSup(uint year, const IntermediateValues& rhs); + + std::vector annual{1}; + std::vector monthly{MONTHS_PER_YEAR}; + std::vector weekly{WEEKS_PER_YEAR}; + std::vector daily{DAYS_PER_YEAR}; + std::vector hourly{HOURS_PER_YEAR}; + +}; // class MinMaxData + +} // namespace Antares::Solver::Variable::R::AllYears + +#endif // __SOLVER_VARIABLE_STORAGE_MINMAX_DATA_H__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/minmax.h b/src/solver/variable/include/antares/solver/variable/storage/minmax.h new file mode 100644 index 0000000000..6095863374 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/minmax.h @@ -0,0 +1,225 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_MINMAX_H__ +#define __SOLVER_VARIABLE_STORAGE_MINMAX_H__ + +#include "minmax-data.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +template +class Min; +template +class Max; + +template +struct MinMaxBase: public NextT +{ +public: + //! Type of the net item in the list + typedef NextT NextType; + + enum + { + //! The count if item in the list + count = 1 + NextT::count, + + categoryFile = NextT::categoryFile | Variable::Category::FileLevel::allFile, + }; + + //! Name of the filter + static const char* Name() + { + return "minmaxbase"; + } + +public: + MinMaxBase() + { + } + + ~MinMaxBase() + { + } + +protected: + void initializeFromStudy(Data::Study& study); + + template + void buildSurveyReport(SurveyResults& report, + const S& results, + int dataLevel, + int fileLevel, + int precision) const + { + if (fileLevel & Category::FileLevel::id) + { + switch (precision) + { + case Category::hourly: + InternalExportIndices(report, + Memory::RawPointer( + minmax.hourly.data()), + fileLevel); + break; + case Category::daily: + InternalExportIndices(report, + minmax.daily.data(), + fileLevel); + break; + case Category::weekly: + InternalExportIndices(report, + minmax.weekly.data(), + fileLevel); + break; + case Category::monthly: + InternalExportIndices(report, + minmax.monthly.data(), + fileLevel); + break; + case Category::annual: + InternalExportIndices<1, VCardT>(report, minmax.annual.data(), fileLevel); + break; + } + } + else + { + switch (precision) + { + case Category::hourly: + InternalExportValues(report, + Memory::RawPointer( + minmax.hourly.data())); + break; + case Category::daily: + InternalExportValues(report, minmax.daily.data()); + break; + case Category::weekly: + InternalExportValues(report, minmax.weekly.data()); + break; + case Category::monthly: + InternalExportValues(report, minmax.monthly.data()); + break; + case Category::annual: + InternalExportValues<1, VCardT>(report, minmax.annual.data()); + break; + } + } + // Next + NextType::template buildSurveyReport(report, + results, + dataLevel, + fileLevel, + precision); + } + + void reset(); + + void merge(uint year, const IntermediateValues& rhs); + + uint64_t memoryUsage() const + { + return sizeof(double) * HOURS_PER_YEAR + NextType::memoryUsage(); + } + + template class DecoratorT> + Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const + { + return NextType::template hourlyValuesForSpatialAggregate(); + } + +protected: + MinMaxData minmax; + +private: + template + static void InternalExportIndices(SurveyResults& report, + const MinMaxData::Data* array, + int fileLevel); + + template + static void InternalExportValues(SurveyResults& report, const MinMaxData::Data* array); + +}; // class MinMaxBase + +template +class Min: public MinMaxBase +{ +public: + //! Implementation + typedef MinMaxBase MinMaxImplementationType; + //! Type of the net item in the list + typedef NextT NextType; + +public: + //! Name of the filter + static const char* Name() + { + return "min"; + } + + enum + { + //! The count if item in the list + count = MinMaxImplementationType::count, + }; +}; + +template +class Max: public MinMaxBase +{ +public: + //! Implementation + typedef MinMaxBase MinMaxImplementationType; + //! Type of the net item in the list + typedef NextT NextType; + +public: + //! Name of the filter + static const char* Name() + { + return "max"; + } + + enum + { + //! The count if item in the list + count = MinMaxImplementationType::count, + }; +}; + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#include "minmax.hxx" + +#endif // __SOLVER_VARIABLE_STORAGE_MINMAX_H__ diff --git a/src/solver/variable/storage/minmax.hxx b/src/solver/variable/include/antares/solver/variable/storage/minmax.hxx similarity index 83% rename from src/solver/variable/storage/minmax.hxx rename to src/solver/variable/include/antares/solver/variable/storage/minmax.hxx index b2252d2a16..741e56cbba 100644 --- a/src/solver/variable/storage/minmax.hxx +++ b/src/solver/variable/include/antares/solver/variable/storage/minmax.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_STORAGE_MIN_HXX__ #define __SOLVER_VARIABLE_STORAGE_MIN_HXX__ @@ -42,7 +36,6 @@ namespace AllYears template inline void MinMaxBase::initializeFromStudy(Data::Study& study) { - minmax.initialize(); // Next NextType::initializeFromStudy(study); } @@ -52,9 +45,13 @@ inline void MinMaxBase::reset() { // Reset at the begining of the simulation if (OpInferior) + { minmax.resetInf(); + } else + { minmax.resetSup(); + } // Next NextType::reset(); } @@ -63,9 +60,13 @@ template inline void MinMaxBase::merge(uint year, const IntermediateValues& rhs) { if (OpInferior) + { minmax.mergeInf(year, rhs); + } else + { minmax.mergeSup(year, rhs); + } // Next NextType::merge(year, rhs); } @@ -98,7 +99,9 @@ void MinMaxBase::InternalExportIndices(SurveyResults& report, // Values double* v = report.values[report.data.columnIndex]; for (uint i = 0; i != Size; ++i) + { v[i] = (double)array[i].indice; + } // Next column index ++report.data.columnIndex; @@ -126,7 +129,9 @@ inline void MinMaxBase::InternalExportValues(SurveyResults& r // Values double* v = report.values[report.data.columnIndex]; for (uint i = 0; i != Size; ++i) + { v[i] = array[i].value; + } // Next column index ++report.data.columnIndex; diff --git a/src/solver/variable/include/antares/solver/variable/storage/raw.h b/src/solver/variable/include/antares/solver/variable/storage/raw.h new file mode 100644 index 0000000000..e71356953f --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/raw.h @@ -0,0 +1,253 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_RAW_H__ +#define __SOLVER_VARIABLE_STORAGE_RAW_H__ + +#include + +#include + +#include + +#include "rawdata.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +template +struct Raw: public NextT +{ +public: + //! Type of the net item in the list + typedef NextT NextType; + + enum + { + //! The count if item in the list + count = 1 + NextT::count, + + categoryFile = NextT::categoryFile | Variable::Category::FileLevel::allFile, + }; + + struct Data + { + double value; + uint32_t indice; + }; + + //! Name of the filter + static const char* Name() + { + return "raw"; + } + +public: + Raw() + { + } + + ~Raw() + { + } + +protected: + void initializeFromStudy(Antares::Data::Study& study); + + inline void reset() + { + rawdata.reset(); + // Next + NextType::reset(); + } + + inline void merge(uint year, const IntermediateValues& rhs) + { + rawdata.merge(year, rhs); + // Next + NextType::merge(year, rhs); + } + + template + void buildSurveyReport(SurveyResults& report, + const S& results, + int dataLevel, + int fileLevel, + int precision) const + { + if (fileLevel & FileFilter && !(fileLevel & Category::FileLevel::id)) + { + switch (precision) + { + case Category::hourly: + InternalExportValues( + report, + ::Antares::Memory::RawPointer(rawdata.hourly)); + break; + case Category::daily: + InternalExportValues(report, rawdata.daily); + break; + case Category::weekly: + InternalExportValues(report, + rawdata.weekly); + break; + case Category::monthly: + InternalExportValues(report, + rawdata.monthly); + break; + case Category::annual: + InternalExportValues(report, rawdata.year); + break; + } + } + // Next + NextType::template buildSurveyReport(report, + results, + dataLevel, + fileLevel, + precision); + } + + template + void buildDigest(SurveyResults& report, int digestLevel, int dataLevel) const + { + if ((dataLevel & Category::DataLevel::area || dataLevel & Category::DataLevel::setOfAreas) + && digestLevel & Category::digestAllYears) + { + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = "values"; + + // Precision + report.precision[report.data.columnIndex] = PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + // Value + report.values[report.data.columnIndex][report.data.rowIndex] = rawdata.allYears; + // Non applicability + report.digestNonApplicableStatus[report.data.rowIndex][report.data.columnIndex] + = *report.isCurrentVarNA; + + ++(report.data.columnIndex); + } + // Next + NextType::template buildDigest(report, digestLevel, dataLevel); + } + + uint64_t memoryUsage() const + { + return +sizeof(double) * HOURS_PER_YEAR + NextType::memoryUsage(); + } + + template class DecoratorT> + Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const + { + if (Yuni::Static::Type::StrictlyEqual, Raw>::Yes) + { + return rawdata.hourly; + } + return NextType::template hourlyValuesForSpatialAggregate(); + } + +public: + RawData rawdata; + +private: + template + void InternalExportValues(SurveyResults& report, const double* array) const + { + assert(array); + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + // Caption + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = "values"; + // Precision + report.precision[report.data.columnIndex] = Solver::Variable::PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + // Non applicability + report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; + + // Values + if (PrecisionT == Category::annual) + { + rawdata.allYears = 0.; + for (uint i = 0; i != rawdata.nbYearsCapacity; ++i) + { + rawdata.allYears += array[i]; + } + *(report.values[report.data.columnIndex]) = rawdata.allYears; + } + else + { + (void)::memcpy(report.values[report.data.columnIndex], array, sizeof(double) * Size); + } + + // Next column index + ++report.data.columnIndex; + } + + template + void InternalExportValuesMC(int precision, SurveyResults& report, const double* array) const + { + if (not(precision & Category::annual)) + { + return; + } + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + // Caption + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = "values"; + // Precision + report.precision[report.data.columnIndex] = Solver::Variable::PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + // Non applicability + report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; + + (void)::memcpy(report.data.matrix[report.data.columnIndex], + array, + report.data.nbYears * sizeof(double)); + + // Next column index + ++report.data.columnIndex; + } + +}; // class Raw + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#include "raw.hxx" + +#endif // __SOLVER_VARIABLE_STORAGE_RAW_H__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/raw.hxx b/src/solver/variable/include/antares/solver/variable/storage/raw.hxx new file mode 100644 index 0000000000..790d305109 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/raw.hxx @@ -0,0 +1,48 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_RAW_HXX__ +#define __SOLVER_VARIABLE_STORAGE_RAW_HXX__ + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +template +inline void Raw::initializeFromStudy(Antares::Data::Study& study) +{ + rawdata.initializeFromStudy(study); + // Next + NextType::initializeFromStudy(study); +} + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_RAW_HXX__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/rawdata.h b/src/solver/variable/include/antares/solver/variable/storage/rawdata.h new file mode 100644 index 0000000000..6a2c118c05 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/rawdata.h @@ -0,0 +1,75 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_RAWDATA_H__ +#define __SOLVER_VARIABLE_STORAGE_RAWDATA_H__ + +#include + +#include + +#include "intermediate.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +class RawData +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + */ + RawData(); + //! Destructor + ~RawData(); + //@} + +public: + void initializeFromStudy(const Data::Study& study); + void reset(); + void merge(unsigned int year, const IntermediateValues& rhs); + +public: + double monthly[MONTHS_PER_YEAR]; + double weekly[WEEKS_PER_YEAR]; + double daily[DAYS_PER_YEAR]; + Antares::Memory::Stored::Type hourly; + double* year; + mutable double allYears; + unsigned int nbYearsCapacity; + +}; // class RawData + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_RAWDATA_H__ diff --git a/src/solver/variable/storage/results.h b/src/solver/variable/include/antares/solver/variable/storage/results.h similarity index 77% rename from src/solver/variable/storage/results.h rename to src/solver/variable/include/antares/solver/variable/storage/results.h index c42674c337..e699d563e4 100644 --- a/src/solver/variable/storage/results.h +++ b/src/solver/variable/include/antares/solver/variable/storage/results.h @@ -1,36 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_STORAGE_RESULTS_H__ #define __SOLVER_VARIABLE_STORAGE_RESULTS_H__ #include -#include "intermediate.h" + #include "../categories.h" #include "fwd.h" +#include "intermediate.h" namespace Antares { @@ -49,11 +44,12 @@ class Results; ** are `Raw`, `Average`, `Min`, `Max`... This parameter is a static list. */ template class DecoratorForSpatialAggregateT> -class Results : public FirstDecoratorT +class Results: public FirstDecoratorT { public: //! Type of the first decorator typedef FirstDecoratorT DecoratorType; + enum { //! The count if item in the list @@ -112,11 +108,11 @@ class Results : public FirstDecoratorT } // namespace Solver } // namespace Antares -#include "results.hxx" +#include "average.h" #include "empty.h" -#include "raw.h" #include "minmax.h" -#include "average.h" +#include "raw.h" +#include "results.hxx" #include "stdDeviation.h" #endif // __SOLVER_VARIABLE_STORAGE_RESULTS_H__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/results.hxx b/src/solver/variable/include/antares/solver/variable/storage/results.hxx new file mode 100644 index 0000000000..24ab458b00 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/results.hxx @@ -0,0 +1,72 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_RESULTS_HXX__ +#define __SOLVER_VARIABLE_STORAGE_RESULTS_HXX__ + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +template class DecoratorForSpatialAggregateT> +inline void Results::initializeFromStudy( + Antares::Data::Study& study) +{ + DecoratorType::initializeFromStudy(study); +} + +template class DecoratorForSpatialAggregateT> +template +inline void Results::buildSurveyReport( + SurveyResults& report, + const S& results, + int dataLevel, + int fileLevel, + int precision) const +{ + // Ask to fullfil the report to the first decorator + DecoratorType::template buildSurveyReport(report, + results, + dataLevel, + fileLevel, + precision); +} + +template class DecoratorForSpatialAggregateT> +inline void Results::merge( + uint year, + const IntermediateValues& data) +{ + DecoratorType::merge(year, data); +} + +template class DecoratorForSpatialAggregateT> +inline void Results::reset() +{ + DecoratorType::reset(); +} + +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_RESULTS_HXX__ diff --git a/src/solver/variable/include/antares/solver/variable/storage/stdDeviation.h b/src/solver/variable/include/antares/solver/variable/storage/stdDeviation.h new file mode 100644 index 0000000000..44159d9cba --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/storage/stdDeviation.h @@ -0,0 +1,317 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_STORAGE_STD_DEVIATION_H__ +#define __SOLVER_VARIABLE_STORAGE_STD_DEVIATION_H__ + +#include +#include +#include + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace R +{ +namespace AllYears +{ +template +struct StdDeviation: public NextT +{ +public: + //! Type of the net item in the list + typedef NextT NextType; + + enum + { + //! The count if item in the list + count = 1 + NextT::count, + + categoryFile = NextT::categoryFile | Variable::Category::FileLevel::allFile, + }; + + struct Data + { + double value; + uint32_t indice; + }; + + //! Name of the filter + static const char* Name() + { + return "std deviation"; + } + +public: + StdDeviation() + { + using namespace Yuni; + stdDeviationHourly = nullptr; + } + + ~StdDeviation() + { + Antares::Memory::Release(stdDeviationHourly); + } + +protected: + void initializeFromStudy(Antares::Data::Study& study) + { + Antares::Memory::Allocate(stdDeviationHourly, HOURS_PER_YEAR); + // Next + NextType::initializeFromStudy(study); + + yearsWeight = study.parameters.getYearsWeight(); + yearsWeightSum = study.parameters.getYearsWeightSum(); + } + + void reset() + { + // Reset + (void)::memset(stdDeviationMonthly, 0, sizeof(double) * MONTHS_PER_YEAR); + (void)::memset(stdDeviationWeekly, 0, sizeof(double) * WEEKS_PER_YEAR); + (void)::memset(stdDeviationDaily, 0, sizeof(double) * DAYS_PER_YEAR); + Antares::Memory::Zero(HOURS_PER_YEAR, stdDeviationHourly); + stdDeviationYear = 0.; + // Next + NextType::reset(); + } + + void merge(unsigned int year, const IntermediateValues& rhs) + { + // Ratio take into account MC year weight + double pRatio = (double)yearsWeight[year] / (double)yearsWeightSum; + + unsigned int i; + // StdDeviation value for each hour throughout all years + for (i = 0; i != HOURS_PER_YEAR; ++i) + { + stdDeviationHourly[i] += rhs.hour[i] * rhs.hour[i] * pRatio; + } + // StdDeviation value for each day throughout all years + for (i = 0; i != DAYS_PER_YEAR; ++i) + { + stdDeviationDaily[i] += rhs.day[i] * rhs.day[i] * pRatio; + } + // StdDeviation value for each week throughout all years + for (i = 0; i != WEEKS_PER_YEAR; ++i) + { + stdDeviationWeekly[i] += rhs.week[i] * rhs.week[i] * pRatio; + } + // StdDeviation value for each month throughout all years + for (i = 0; i != MONTHS_PER_YEAR; ++i) + { + stdDeviationMonthly[i] += rhs.month[i] * rhs.month[i] * pRatio; + } + // StdDeviation value throughout all years + stdDeviationYear += rhs.year * rhs.year * pRatio; + + // Next + NextType::merge(year, rhs); + } + + template + void buildSurveyReport(SurveyResults& report, + const S& results, + int dataLevel, + int fileLevel, + int precision) const + { + if (!(fileLevel & Category::FileLevel::id)) + { + switch (precision) + { + case Category::hourly: + InternalExportValues( + report, + results, + Memory::RawPointer(stdDeviationHourly)); + break; + case Category::daily: + InternalExportValues(report, + results, + stdDeviationDaily); + break; + case Category::weekly: + InternalExportValues( + report, + results, + stdDeviationWeekly); + break; + case Category::monthly: + InternalExportValues( + report, + results, + stdDeviationMonthly); + break; + case Category::annual: + InternalExportValues(report, + results, + &stdDeviationYear); + break; + } + } + // Next + NextType::template buildSurveyReport(report, + results, + dataLevel, + fileLevel, + precision); + } + + uint64_t memoryUsage() const + { + return sizeof(double) * HOURS_PER_YEAR + NextType::memoryUsage(); + } + + template class DecoratorT> + Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const + { + if (Yuni::Static::Type::StrictlyEqual, StdDeviation>::Yes) + { + return stdDeviationHourly; + } + return NextType::template hourlyValuesForSpatialAggregate(); + } + +public: + double stdDeviationMonthly[MONTHS_PER_YEAR]; + double stdDeviationWeekly[WEEKS_PER_YEAR]; + double stdDeviationDaily[DAYS_PER_YEAR]; + Antares::Memory::Stored::Type stdDeviationHourly; + double stdDeviationYear; + +private: + template + void InternalExportValues(SurveyResults& report, const S& results, const A& array) const + { + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + // Caption + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = "std"; + + // Precision + report.precision[report.data.columnIndex] = PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + + // Non applicability + report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; + + // Values + double* target = report.values[report.data.columnIndex]; + // A mere copy + + auto squareRootChecked = [](double d) { return d >= 0 ? std::sqrt(d) : 0.; }; + + switch (PrecisionT) + { + case Category::hourly: + { + for (unsigned int i = 0; i != Size; ++i) + { + target[i] = squareRootChecked( + array[i] - results.avgdata.hourly[i] * results.avgdata.hourly[i]); + } + } + break; + case Category::daily: + { + for (unsigned int i = 0; i != Size; ++i) + { + target[i] = squareRootChecked( + array[i] - results.avgdata.daily[i] * results.avgdata.daily[i]); + } + } + break; + case Category::weekly: + { + for (unsigned int i = 0; i != Size; ++i) + { + target[i] = squareRootChecked( + array[i] - results.avgdata.weekly[i] * results.avgdata.weekly[i]); + } + } + break; + case Category::monthly: + { + for (unsigned int i = 0; i != Size; ++i) + { + target[i] = squareRootChecked( + array[i] - results.avgdata.monthly[i] * results.avgdata.monthly[i]); + } + } + break; + case Category::annual: + { + const double d = *array - results.avgdata.allYears * results.avgdata.allYears; + *target = squareRootChecked(d); + } + break; + } + + // Next column index + ++report.data.columnIndex; + } + + template + void InternalExportValuesMC(SurveyResults& report, const S& /*results*/, const A& array) const + { + if (not(PrecisionT & Category::annual)) + { + return; + } + assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); + + // Caption + report.captions[0][report.data.columnIndex] = report.variableCaption; + report.captions[1][report.data.columnIndex] = report.variableUnit; + report.captions[2][report.data.columnIndex] = "std"; + + // Precision + report.precision[report.data.columnIndex] = PrecisionToPrintfFormat< + VCardT::decimal>::Value(); + + // Non applicability + report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; + + (void)::memcpy(report.data.matrix[report.data.columnIndex], array, Size * sizeof(double)); + + // Next column index + ++report.data.columnIndex; + } + +private: + std::vector yearsWeight; + float yearsWeightSum; + +}; // class StdDeviation + +} // namespace AllYears +} // namespace R +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_STORAGE_STD_DEVIATION_H__ diff --git a/src/solver/variable/include/antares/solver/variable/surveyresults.h b/src/solver/variable/include/antares/solver/variable/surveyresults.h new file mode 100644 index 0000000000..93435c98f5 --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/surveyresults.h @@ -0,0 +1,26 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __SOLVER_VARIABLE_SURVEY_RESULTS_H__ +#define __SOLVER_VARIABLE_SURVEY_RESULTS_H__ + +#include "surveyresults/surveyresults.h" + +#endif // __SOLVER_VARIABLE_SURVEY_RESULTS_H__ diff --git a/src/solver/variable/surveyresults/data.h b/src/solver/variable/include/antares/solver/variable/surveyresults/data.h similarity index 78% rename from src/solver/variable/surveyresults/data.h rename to src/solver/variable/include/antares/solver/variable/surveyresults/data.h index 330e2eaf2d..6f0ebff473 100644 --- a/src/solver/variable/surveyresults/data.h +++ b/src/solver/variable/include/antares/solver/variable/surveyresults/data.h @@ -1,37 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_SURVEY_RESULTS_DATA_H__ #define __SOLVER_VARIABLE_SURVEY_RESULTS_DATA_H__ #include -#include "../constants.h" #include + #include #include +#include "antares/antares/constants.h" namespace Antares { diff --git a/src/solver/variable/surveyresults/reportbuilder.hxx b/src/solver/variable/include/antares/solver/variable/surveyresults/reportbuilder.hxx similarity index 77% rename from src/solver/variable/surveyresults/reportbuilder.hxx rename to src/solver/variable/include/antares/solver/variable/surveyresults/reportbuilder.hxx index 85f49dd3a5..6354169b96 100644 --- a/src/solver/variable/surveyresults/reportbuilder.hxx +++ b/src/solver/variable/include/antares/solver/variable/surveyresults/reportbuilder.hxx @@ -1,45 +1,40 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_SURVEYRESULTS_REPORT_BUILDER_HXX__ #define __SOLVER_VARIABLE_SURVEYRESULTS_REPORT_BUILDER_HXX__ +#include + #include -#include #include +#include #include #include +#include -#include "../endoflist.h" #include "../categories.h" -#include "../surveyresults.h" +#include "../endoflist.h" #include "../info.h" -#include -#include +#include "../surveyresults.h" #define SEP Yuni::IO::Separator @@ -58,17 +53,20 @@ struct VariablesStatsByDataLevel { enum { - nextFileLevel = (CFile * 2 > (int)Category::maxFileLevel) ? 1 : CFile * 2, - currentVariableCount = NextT::template Statistics::count, - nextVariableCount = VariablesStatsByDataLevel::count, + nextFileLevel = (CFile * 2 > (int)Category::FileLevel::maxFileLevel) ? 1 : CFile * 2, + currentVariableCount = NextT::template Statistics < CDataLevel, + CFile > ::count, + nextVariableCount = VariablesStatsByDataLevel < NextT, + CDataLevel, + nextFileLevel > ::count, //! Hpw many variables for this data level - count = currentVariableCount + nextVariableCount, + count = (int)currentVariableCount + (int)nextVariableCount, }; }; template -struct VariablesStatsByDataLevel +struct VariablesStatsByDataLevel { enum { @@ -81,10 +79,14 @@ struct BrowseAllVariables { enum { - nextFileLevel = (CFile * 2 > (int)Category::maxFileLevel) ? 1 : CFile * 2, - nextDataLevel = (CDataLevel * 2 > (int)Category::maxDataLevel) ? 1 : CDataLevel * 2, - currentValue = NextT::template Statistics::count, - nextValue = BrowseAllVariables::maxValue, + nextFileLevel = (CFile * 2 > (int)Category::FileLevel::maxFileLevel) ? 1 : CFile * 2, + nextDataLevel = (CDataLevel * 2 > (int)Category::DataLevel::maxDataLevel) ? 1 + : CDataLevel * 2, + currentValue = NextT::template Statistics < CDataLevel, + CFile > ::count, + nextValue = BrowseAllVariables < NextT, + nextDataLevel, + nextFileLevel > ::maxValue, maxValue = (currentValue > (int)nextValue) ? currentValue : (int)nextValue, }; @@ -96,24 +98,29 @@ struct BrowseAllVariables list.template buildSurveyResults(results); // Go to the next status BrowseAllVariables::template buildSurveyResults( - list, results); + list, + results); } }; template -struct BrowseAllVariables +struct BrowseAllVariables { enum { - maxValue = NextT::template Statistics::count + maxValue = NextT::template Statistics < Category::DataLevel::maxDataLevel, + Category::FileLevel::maxFileLevel > ::count }; template static void buildSurveyResults(const L& list, S& results) { // Exporting data for the current state - list.template buildSurveyResults( - results); + list.template buildSurveyResults(results); // This is the final available state } }; @@ -123,6 +130,7 @@ class SurveyReportBuilderFile { public: using ListType = NextT; + enum { //! A non-zero value to write down the results for the simulation @@ -134,9 +142,13 @@ public: static void Run(const ListType& list, SurveyResults& results, unsigned int numSpace) { if (globalResults) + { RunGlobalResults(list, results); + } else + { RunAnnual(list, results, numSpace); + } // The survey type using SurveyRBFileType = SurveyReportBuilderFile; @@ -177,10 +189,11 @@ private: // Specialization for the final state (dummy) template -class SurveyReportBuilderFile +class SurveyReportBuilderFile { public: using ListType = NextT; + // dead end static inline void Run(const ListType&, SurveyResults&, unsigned int) { @@ -193,6 +206,7 @@ class SurveyReportBuilder public: //! List using ListType = NextT; + enum { nextDataLevel = CDataLevel * 2, @@ -201,17 +215,23 @@ public: static void Run(const ListType& list, SurveyResults& results, unsigned int numSpace = 9999) { // Area - Thermal clusters - Links - if (CDataLevel & Category::area || CDataLevel & Category::link - || CDataLevel & Category::thermalAggregate) + if (CDataLevel & Category::DataLevel::area || CDataLevel & Category::DataLevel::link + || CDataLevel & Category::DataLevel::thermalAggregate) + { RunForEachArea(list, results, numSpace); + } // Set of Areas - if (CDataLevel & Category::setOfAreas) + if (CDataLevel & Category::DataLevel::setOfAreas) + { RunForEachSetOfAreas(list, results, numSpace); + } // Binding constraints level - if (CDataLevel & Category::bindingConstraint) + if (CDataLevel & Category::DataLevel::bindingConstraint) + { RunForEachBindingConstraint(list, results, numSpace); + } // Go to the next data level SurveyReportBuilder::Run(list, results, numSpace); @@ -226,11 +246,11 @@ public: // Digest file : areas part std::string digestBuffer; - list.buildDigest(results, Category::digestAllYears, Category::area); + list.buildDigest(results, Category::digestAllYears, Category::DataLevel::area); results.exportDigestAllYears(digestBuffer); // Degest file : districts part - list.buildDigest(results, Category::digestAllYears, Category::setOfAreas); + list.buildDigest(results, Category::digestAllYears, Category::DataLevel::setOfAreas); results.exportDigestAllYears(digestBuffer); // Digest: Flow linear (only if selected by user) @@ -238,7 +258,7 @@ public: { logs.debug() << " . Digest, flow linear"; results.data.matrix.fill(std::numeric_limits::quiet_NaN()); - list.buildDigest(results, Category::digestFlowLinear, Category::area); + list.buildDigest(results, Category::digestFlowLinear, Category::DataLevel::area); results.exportDigestMatrix("Links (FLOW LIN.)", digestBuffer); } @@ -247,7 +267,7 @@ public: { logs.debug() << " . Digest, flow quad"; results.data.matrix.fill(std::numeric_limits::quiet_NaN()); - list.buildDigest(results, Category::digestFlowQuad, Category::area); + list.buildDigest(results, Category::digestFlowQuad, Category::DataLevel::area); results.exportDigestMatrix("Links (FLOW QUAD.)", digestBuffer); } // THIS FILE IS DEPRECATED !!! @@ -262,8 +282,8 @@ private: using namespace Yuni; // No need to do anything for any area here if no zonal variables were selected. - uint selectedZonalVarsCount - = results.data.study.parameters.variablesPrintInfo.getNbSelectedZonalVars(); + uint selectedZonalVarsCount = results.data.study.parameters.variablesPrintInfo + .getNbSelectedZonalVars(); // All values related to an area // Note: A thermal cluster is attached to an area @@ -296,7 +316,7 @@ private: skipDirectory = skipDirectory || !selectedZonalVarsCount; // Generating the report for each area - if (CDataLevel & Category::area && !skipDirectory) + if (CDataLevel & Category::DataLevel::area && !skipDirectory) { logs.info() << "Exporting results : " << area.name; // The new output @@ -307,11 +327,15 @@ private: } // Thermal clusters for the current area - if (CDataLevel & Category::thermalAggregate) + if (CDataLevel & Category::DataLevel::thermalAggregate) + { RunForEachThermalCluster(list, results, numSpace); + } // Links - if (CDataLevel & Category::link && !area.links.empty()) + if (CDataLevel & Category::DataLevel::link && !area.links.empty()) + { RunForEachLink(list, results, numSpace); + } } } @@ -320,21 +344,19 @@ private: unsigned int numSpace) { // Only do something if there is at least one column to write somewhere - // See below: if (CDataLevel & Category::thermalAggregate) - if (VariablesStatsByDataLevel::count) + // See below: if (CDataLevel & Category::DataLevel::thermalAggregate) + if (VariablesStatsByDataLevel::count) { auto& area = *results.data.area; - auto end = area.thermal.list.end(); - for (auto i = area.thermal.list.begin(); i != end; ++i) + for (auto& cluster: area.thermal.list.each_enabled_and_not_mustrun()) { - auto& cluster = *(i->second); - results.data.thermalCluster = &cluster; + results.data.thermalCluster = cluster.get(); - logs.info() << "Exporting results : " << area.name << " :: " << cluster.name(); + logs.info() << "Exporting results : " << area.name << " :: " << cluster->name(); // The new output results.data.output.clear(); results.data.output << results.data.originalOutput << SEP << "areas" << SEP - << area.id << SEP << "thermal" << SEP << cluster.id(); + << area.id << SEP << "thermal" << SEP << cluster->id(); SurveyReportBuilderFile::Run(list, results, numSpace); } @@ -346,12 +368,14 @@ private: using namespace Yuni; // No need to do anything for any link here if no link variables were selected. - uint selectedLinkVarsCount - = results.data.study.parameters.variablesPrintInfo.getNbSelectedLinkVars(); + uint selectedLinkVarsCount = results.data.study.parameters.variablesPrintInfo + .getNbSelectedLinkVars(); if (!selectedLinkVarsCount) + { return; + } - int count_int = VariablesStatsByDataLevel::count; + int count_int = VariablesStatsByDataLevel::count; if (count_int) { auto& area = *results.data.area; @@ -365,8 +389,8 @@ private: // Skipping the creation of a result directory if it is meant to be empty. // ... Getting few indicators value before deciding if we skip the results directory // creation. - bool printingSynthesis - = GlobalT; // Are we printing synthesis or year-by-year results ? + bool printingSynthesis = GlobalT; // Are we printing synthesis or year-by-year + // results ? bool filterAllYearByYear = !(link.filterYearByYear & Data::filterAll); bool filterAllSynthesis = !(link.filterSynthesis & Data::filterAll); @@ -384,8 +408,9 @@ private: results.data.output.clear(); results.data.output << results.data.originalOutput << SEP << "links" << SEP << area.id << " - " << results.data.link->with->id; - SurveyReportBuilderFile::Run( - list, results, numSpace); + SurveyReportBuilderFile::Run(list, + results, + numSpace); } } } @@ -400,10 +425,12 @@ private: // No need to do anything for any district (set of areas) here if no zonal variables were // selected. - uint selectedZonalVarsCount - = results.data.study.parameters.variablesPrintInfo.getNbSelectedZonalVars(); + uint selectedZonalVarsCount = results.data.study.parameters.variablesPrintInfo + .getNbSelectedZonalVars(); if (!selectedZonalVarsCount) + { return; + } results.data.area = nullptr; results.data.thermalCluster = nullptr; @@ -416,7 +443,9 @@ private: for (unsigned int i = 0; i != sets.size(); ++i) { if (!sets.hasOutput(i) || !sets.resultSize(i)) + { continue; + } logs.info() << "Exporting results : " << sets.caption(i); // The new output @@ -436,7 +465,7 @@ private: using namespace Yuni; // Generating the report for each binding constraint - if (CDataLevel & Category::bindingConstraint) + if (CDataLevel & Category::DataLevel::bindingConstraint) { logs.info() << "Exporting results : binding constraints"; // The new output @@ -449,10 +478,11 @@ private: }; // class SurveyReportBuilder template -class SurveyReportBuilder +class SurveyReportBuilder { public: using ListType = NextT; + // Dead end static void Run(const ListType&, SurveyResults&, unsigned int) { diff --git a/src/solver/variable/include/antares/solver/variable/surveyresults/surveyresults.h b/src/solver/variable/include/antares/solver/variable/surveyresults/surveyresults.h new file mode 100644 index 0000000000..fa6a5e501d --- /dev/null +++ b/src/solver/variable/include/antares/solver/variable/surveyresults/surveyresults.h @@ -0,0 +1,153 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#ifndef __SOLVER_VARIABLE_SURVEY_RESULTS_SURVEY_RESULTS_H__ +#define __SOLVER_VARIABLE_SURVEY_RESULTS_SURVEY_RESULTS_H__ + +#include +#include + +#include +#include +#include +#include "antares/antares/constants.h" + +#include "../categories.h" +#include "data.h" + +namespace Antares::Solver::Variable +{ +/*! +** \brief Class utility for building CSV results files +*/ +class SurveyResults +{ +public: + //! Precision + typedef Yuni::CString<10, false> PrecisionType; + //! Caption + typedef Yuni::CString<128, false> CaptionType; + +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + ** + ** \param maxVars The maximum total of variables that we may need for writing + ** the report + ** \param s Reference to the study + ** \param o The output folder + ** \param year The current year, if any + */ + SurveyResults(const Data::Study& s, const Yuni::String& o, IResultWriter& writer); + /*! + ** \brief Destructor + */ + ~SurveyResults(); + //@} + + /*! + ** \brief Write the data into a file + */ + void saveToFile(int dataLevel, int fileLevel, int precisionLevel); + + /*! + ** \brief Export informations about the current study + ** + ** It is composed by several files to completely describe the system + ** and provide a good support for Excel macros. + */ + void exportGridInfos(); + + // Reset a line of values to zero. + void resetValuesAtLine(uint); + + /*! + ** \brief Export the digest file + */ + void exportDigestAllYears(std::string& buffer); + + void exportDigestMatrix(const char* title, std::string& buffer); + +public: + //! Data (not related to the template parameter) + Solver::Variable::Private::SurveyResultsData data; + + //! Caption for the current variable + CaptionType variableCaption; + std::string variableUnit; + + //! Matrix where to store all results + double** values; + + enum + { + captionCount = 3, + }; + + //! Array to store all variable names + CaptionType* captions[captionCount]; + + //! Precision to for each column (in the printf format) + PrecisionType* precision; + + //! Non applicable status for each column (in the printf format) + bool* nonApplicableStatus; + // Digest file non applicable status ( dim : nb vars x max(nb areas, nb sets of areas) ) + uint digestSize; // Useful dimension for digest file non applicable statut management. + bool** digestNonApplicableStatus; + + //! The total number of variables + uint maxVariables; + + //! Flag to known if we are in the year-by-year mode + bool yearByYearResults; + + //! When looping over output variables, is current variable non applicable ? + //! In the static type list of variables, there is a need to convey the non applicable status to + //! variables statistic results through an instance of the current class. Furthermore, some + //! unusual variables are actually "multi-variables", that is they contain actually several + //! variables. Therefore, the following is a pointer on the current output variable's non + //! applicable status. In case of a multi-variable, it is a pointer on the current + //! sub-variable's non applicable status. This pointer references a TEMPORARY boolean value. It + //! is NEVER used to allocate a table. + bool* isCurrentVarNA; + //! Same thing for print status (do we print the current output variable ?) + bool* isPrinted; + // File writer + IResultWriter& pResultWriter; + +private: + template + void AppendDoubleValue(uint& error, + const double v, + StringT& buffer, + ConvertT& conversionBuffer, + const PrecisionT& precision, + const bool isNotApplicable); + + void writeDateToFileDescriptor(uint row, int precisionLevel); + +}; // class SurveyResults + +} // namespace Antares::Solver::Variable + +#endif // __SOLVER_VARIABLE_SURVEY_RESULTS_SURVEY_RESULTS_H__ diff --git a/src/solver/variable/variable.h b/src/solver/variable/include/antares/solver/variable/variable.h similarity index 88% rename from src/solver/variable/variable.h rename to src/solver/variable/include/antares/solver/variable/variable.h index 56f0f9a69d..279ba9da3d 100644 --- a/src/solver/variable/variable.h +++ b/src/solver/variable/include/antares/solver/variable/variable.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_VARIABLE_H__ #define __SOLVER_VARIABLE_VARIABLE_H__ @@ -34,14 +28,14 @@ #include #include + +#include "categories.h" #include "container.h" -#include "surveyresults.h" -#include "storage/intermediate.h" -#include "storage/results.h" #include "endoflist.h" -#include "constants.h" -#include "categories.h" #include "info.h" +#include "storage/intermediate.h" +#include "storage/results.h" +#include "surveyresults.h" namespace Antares { @@ -53,7 +47,7 @@ namespace Variable ** \brief Interface for any variable */ template -class IVariable : protected NextT +class IVariable: protected NextT { public: //! Child @@ -71,22 +65,18 @@ class IVariable : protected NextT //! Results typedef typename Storage::ResultsType StoredResultType; - // Default values - enum - { - categoryDataLevel = VCardType::categoryDataLevel, - categoryFileLevel = VCardType::categoryFileLevel, - }; + static constexpr uint8_t categoryDataLevel = VCardType::categoryDataLevel; + static constexpr uint8_t categoryFileLevel = VCardType::categoryFileLevel; template struct Statistics { enum { - count - = ((categoryDataLevel & CDataLevel && categoryFileLevel & CFile) - ? (NextType::template Statistics::count + ResultsType::count) - : NextType::template Statistics::count), + count = ((categoryDataLevel & CDataLevel && categoryFileLevel & CFile) + ? (NextType::template Statistics::count + + ResultsType::count) + : NextType::template Statistics::count), }; }; @@ -111,7 +101,6 @@ class IVariable : protected NextT void getPrintStatusFromStudy(Data::Study& study); void supplyMaxNumberOfColumns(Data::Study& study); - public: //! \name Constructor //@{ @@ -227,7 +216,7 @@ class IVariable : protected NextT void yearEnd(uint year); template - void yearEndSpatialAggregates(V& allVars, uint year); + void yearEndSpatialAggregates(V& allVars, uint year, unsigned int numSpace); template void yearEndSpatialAggregates(V& allVars, uint year, const SetT& set); diff --git a/src/solver/variable/variable.hxx b/src/solver/variable/include/antares/solver/variable/variable.hxx similarity index 80% rename from src/solver/variable/variable.hxx rename to src/solver/variable/include/antares/solver/variable/variable.hxx index d147707b8b..6b2ba73a55 100644 --- a/src/solver/variable/variable.hxx +++ b/src/solver/variable/include/antares/solver/variable/variable.hxx @@ -1,33 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __SOLVER_VARIABLE_VARIABLE_HXX__ #define __SOLVER_VARIABLE_VARIABLE_HXX__ #include + #include namespace Antares::Solver::Variable @@ -52,7 +47,9 @@ inline IVariable::IVariable() // Initializing default print to true for (uint i = 0; i < pColumnCount; i++) + { isPrinted[i] = true; + } } template @@ -109,19 +106,21 @@ inline void IVariable::broadcastNonApplicability(bool app if (VCardType::isPossiblyNonApplicable != 0 && applyNonApplicable) { for (uint i = 0; i != pColumnCount; ++i) + { isNonApplicable[i] = true; + } } else { for (uint i = 0; i != pColumnCount; ++i) + { isNonApplicable[i] = false; + } } NextType::broadcastNonApplicability(applyNonApplicable); } - - template inline void IVariable::simulationBegin() { @@ -134,6 +133,7 @@ inline void IVariable::simulationEnd() { NextType::simulationEnd(); } + template size_t IVariable::getMaxNumberColumns() const { @@ -156,10 +156,12 @@ inline void IVariable::yearEnd(uint year) template template -inline void IVariable::yearEndSpatialAggregates(V& allVars, uint year) +inline void IVariable::yearEndSpatialAggregates(V& allVars, + uint year, + unsigned int numSpace) { // Next variable - NextType::template yearEndSpatialAggregates(allVars, year); + NextType::template yearEndSpatialAggregates(allVars, year, numSpace); } template @@ -283,8 +285,11 @@ inline void IVariable::buildSurveyReport(SurveyResults& r results.isPrinted = isPrinted; results.isCurrentVarNA = isNonApplicable; - VariableAccessorType::template BuildSurveyReport( - results, pResults, dataLevel, fileLevel, precision); + VariableAccessorType::template BuildSurveyReport(results, + pResults, + dataLevel, + fileLevel, + precision); } } @@ -309,8 +314,10 @@ inline void IVariable::buildAnnualSurveyReport(SurveyResu && (precision & VCardType::precision)) { // Getting its intermediate results - static_cast(this)->localBuildAnnualSurveyReport( - results, fileLevel, precision, numSpace); + static_cast(this)->localBuildAnnualSurveyReport(results, + fileLevel, + precision, + numSpace); } } @@ -326,16 +333,18 @@ inline void IVariable::buildDigest(SurveyResults& results { // Generate the Digest for the local results (areas part) if (VCardType::columnCount != 0 - && (VCardType::categoryDataLevel & Category::setOfAreas - || VCardType::categoryDataLevel & Category::area - || VCardType::categoryDataLevel & Category::link)) + && (VCardType::categoryDataLevel & Category::DataLevel::setOfAreas + || VCardType::categoryDataLevel & Category::DataLevel::area + || VCardType::categoryDataLevel & Category::DataLevel::link)) { // Initializing pointer on variable non applicable and print stati arrays to beginning results.isPrinted = isPrinted; results.isCurrentVarNA = isNonApplicable; - VariableAccessorType::template BuildDigest( - results, pResults, digestLevel, dataLevel); + VariableAccessorType::template BuildDigest(results, + pResults, + digestLevel, + dataLevel); } // Ask to build the digest to the next variable NextType::buildDigest(results, digestLevel, dataLevel); @@ -351,13 +360,15 @@ template inline uint64_t IVariable::memoryUsage() const { uint64_t r = VariableAccessorType::Value(pResults); - if ((int)VCardT::columnCount != (int)Category::dynamicColumns) + if (VCardT::columnCount != (int)Category::dynamicColumns) { // Intermediate values if (VCardT::hasIntermediateValues) { for (uint i = 0; i != (uint)VCardT::columnCount; ++i) + { r += IntermediateValues::MemoryUsage(); + } } } r += NextType::memoryUsage(); @@ -424,6 +435,7 @@ struct RetrieveResultsAssignment { Yes = 1 }; + template static void Do(ResultsT& varResults, O** result) { @@ -438,6 +450,7 @@ struct RetrieveResultsAssignment<0> { Yes = 0 }; + template static void Do(ResultsT&, O**) { @@ -452,8 +465,8 @@ template inline const double* IVariable::retrieveHourlyResultsForCurrentYear( uint numSpace) const { - using AssignT - = RetrieveResultsAssignment::Yes>; + using AssignT = RetrieveResultsAssignment< + Yuni::Static::Type::StrictlyEqual::Yes>; return (AssignT::Yes) ? nullptr : NextType::template retrieveHourlyResultsForCurrentYear(numSpace); @@ -465,11 +478,13 @@ inline void IVariable::retrieveResultsForArea( typename Storage::ResultsType** result, const Data::Area* area) { - using AssignT - = RetrieveResultsAssignment::Yes>; + using AssignT = RetrieveResultsAssignment< + Yuni::Static::Type::StrictlyEqual::Yes>; AssignT::Do(pResults, result); if (!AssignT::Yes) + { NextType::template retrieveResultsForArea(result, area); + } } template @@ -478,11 +493,13 @@ inline void IVariable::retrieveResultsForThermalCluster( typename Storage::ResultsType** result, const Data::ThermalCluster* cluster) { - using AssignT - = RetrieveResultsAssignment::Yes>; + using AssignT = RetrieveResultsAssignment< + Yuni::Static::Type::StrictlyEqual::Yes>; AssignT::Do(pResults, result); if (!AssignT::Yes) + { NextType::template retrieveResultsForThermalCluster(result, cluster); + } } template @@ -491,11 +508,13 @@ inline void IVariable::retrieveResultsForLink( typename Storage::ResultsType** result, const Data::AreaLink* link) { - using AssignT - = RetrieveResultsAssignment::Yes>; + using AssignT = RetrieveResultsAssignment< + Yuni::Static::Type::StrictlyEqual::Yes>; AssignT::Do(pResults, result); if (!AssignT::Yes) + { NextType::template retrieveResultsForLink(result, link); + } } namespace // anonymous @@ -534,8 +553,8 @@ struct HourlyResultsForCurrentYear template inline Antares::Memory::Stored::ConstReturnType - IVariable::retrieveRawHourlyValuesForCurrentYear(uint column, - uint /* numSpace */) const +IVariable::retrieveRawHourlyValuesForCurrentYear(uint column, + uint /* numSpace */) const { return HourlyResultsForCurrentYear::Get(pResults, column); } @@ -547,7 +566,6 @@ inline const typename Storage::ResultsType& IVariable::RetrieveVariableList(PredicateT& predicat NextType::RetrieveVariableList(predicate); } - -// ============================================================================= +// ============================================================================= // Each output variable gets its print status from the study parameters // ============================================================================= @@ -640,47 +661,48 @@ void IVariable::RetrieveVariableList(PredicateT& predicat // VCardType::columnCount. Recall that a variable can be single, dynamic or multiple. namespace // anonymous { - // Case : the variable is multiple - template - class GetPrintStatusHelper - { - public: - static void Do(Data::Study& study, bool* isPrinted) - { - for (uint i = 0; i != VCardT::columnCount; ++i) - { - // Shifting inside the variables print info collection until reaching the print info - // associated with the current name, and then getting its print status. - isPrinted[i] = study.parameters.variablesPrintInfo.isPrinted(VCardT::Multiple::Caption(i)); - } - } - }; - - // Case : the variable is single - template - class GetPrintStatusHelper +// Case : the variable is multiple +template +class GetPrintStatusHelper +{ +public: + static void Do(Data::Study& study, bool* isPrinted) { - public: - static void Do(Data::Study& study, bool* isPrinted) + for (uint i = 0; i != VCardT::columnCount; ++i) { // Shifting inside the variables print info collection until reaching the print info // associated with the current name, and then getting its print status. - isPrinted[0] = study.parameters.variablesPrintInfo.isPrinted(VCardT::Caption()); + isPrinted[i] = study.parameters.variablesPrintInfo.isPrinted( + VCardT::Multiple::Caption(i)); } - }; + } +}; - // Case : the variable is dynamic - template - class GetPrintStatusHelper +// Case : the variable is single +template +class GetPrintStatusHelper +{ +public: + static void Do(Data::Study& study, bool* isPrinted) { - public: - static void Do(Data::Study& study, bool* isPrinted) - { - // Shifting inside the variables print info collection until reaching the print info - // associated with the current name, and then getting its print status. - isPrinted[0] = study.parameters.variablesPrintInfo.isPrinted(VCardT::Caption()); - } - }; + // Shifting inside the variables print info collection until reaching the print info + // associated with the current name, and then getting its print status. + isPrinted[0] = study.parameters.variablesPrintInfo.isPrinted(VCardT::Caption()); + } +}; + +// Case : the variable is dynamic +template +class GetPrintStatusHelper +{ +public: + static void Do(Data::Study& study, bool* isPrinted) + { + // Shifting inside the variables print info collection until reaching the print info + // associated with the current name, and then getting its print status. + isPrinted[0] = study.parameters.variablesPrintInfo.isPrinted(VCardT::Caption()); + } +}; } // namespace template @@ -691,65 +713,63 @@ inline void IVariable::getPrintStatusFromStudy(Data::Stud NextType::getPrintStatusFromStudy(study); } - - // ======================================================================= -// Each output variable supplies the maximum number of columns it takes +// Each output variable supplies the maximum number of columns it takes // in an ouptut report to the variable print info instance // ======================================================================= -// The class SupplyMaxNbColumnsHelper is used to make a different Do(...) treatment depending on current -// VCardType::columnCount : recall that a variable can be single, dynamic or multiple. +// The class SupplyMaxNbColumnsHelper is used to make a different Do(...) treatment depending on +// current VCardType::columnCount : recall that a variable can be single, dynamic or multiple. namespace // anonymous { - // Case : the variable is multiple - template - class SupplyMaxNbColumnsHelper +// Case : the variable is multiple +template +class SupplyMaxNbColumnsHelper +{ +public: + static void Do(Data::Study& study, uint maxNumberColumns) { - public: - static void Do(Data::Study& study, uint maxNumberColumns) + for (uint i = 0; i != VCardT::columnCount; ++i) { - for (uint i = 0; i != VCardT::columnCount; ++i) - { - study.parameters.variablesPrintInfo.setMaxColumns(VCardT::Multiple::Caption(i), maxNumberColumns); - } + study.parameters.variablesPrintInfo.setMaxColumns(VCardT::Multiple::Caption(i), + maxNumberColumns); } - }; + } +}; - // Case : the variable is single - template - class SupplyMaxNbColumnsHelper +// Case : the variable is single +template +class SupplyMaxNbColumnsHelper +{ +public: + static void Do(Data::Study& study, uint maxNumberColumns) { - public: - static void Do(Data::Study& study, uint maxNumberColumns) - { - study.parameters.variablesPrintInfo.setMaxColumns(VCardT::Caption(), maxNumberColumns); - } - }; + study.parameters.variablesPrintInfo.setMaxColumns(VCardT::Caption(), maxNumberColumns); + } +}; - // Case : the variable is dynamic - template - class SupplyMaxNbColumnsHelper +// Case : the variable is dynamic +template +class SupplyMaxNbColumnsHelper +{ +public: + static void Do(Data::Study& study, uint maxNumberColumns) { - public: - static void Do(Data::Study& study, uint maxNumberColumns) - { - study.parameters.variablesPrintInfo.setMaxColumns(VCardT::Caption(), maxNumberColumns); - } - }; + study.parameters.variablesPrintInfo.setMaxColumns(VCardT::Caption(), maxNumberColumns); + } +}; } // namespace template inline void IVariable::supplyMaxNumberOfColumns(Data::Study& study) { auto max_columns = static_cast(this)->getMaxNumberColumns(); - SupplyMaxNbColumnsHelper::Do(study, static_cast(max_columns)); + SupplyMaxNbColumnsHelper::Do(study, + static_cast(max_columns)); // Go to the next variable NextType::supplyMaxNumberOfColumns(study); } } // namespace Antares::Solver::Variable - - #endif // __SOLVER_VARIABLE_VARIABLE_HXX__ diff --git a/src/solver/variable/print.h b/src/solver/variable/print.h deleted file mode 100644 index 1c5fe82585..0000000000 --- a/src/solver/variable/print.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_PRINT_H__ -#define __SOLVER_VARIABLE_PRINT_H__ - -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -class PrintInfosStdCout final -{ -public: - PrintInfosStdCout() : pIndent(0) - { - } - - template - void beginNode() - { - printVCard(); - ++pIndent; - } - - template - void addVCard() - { - printVCard(); - } - - void endNode() - { - --pIndent; - } - -private: - template - void printVCard() - { - pBuffer.clear(); - pBuffer.resize(1 + pBuffer.size() + pIndent * 4, " "); - pBuffer += (IsNodeT ? "+ " : " "); - pBuffer += VCardT::Caption(); - pBuffer.resize(29, " "); - pBuffer += VCardT::Unit(); - pBuffer.resize(37, " "); - pBuffer += VCardT::Description(); - Antares::logs.info() << pBuffer; - } - - void printIndent() - { - if (pIndent) - { - for (uint i = 0; i != pIndent; ++i) - pBuffer += " "; - } - } - -private: - uint pIndent; - Yuni::String pBuffer; -}; - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_PRINT_H__ diff --git a/src/solver/variable/state.cpp b/src/solver/variable/state.cpp index 726cb1b478..ca8d5b2677 100644 --- a/src/solver/variable/state.cpp +++ b/src/solver/variable/state.cpp @@ -1,42 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include "state.h" +#include "antares/solver/variable/state.h" -using namespace Yuni; +#include + +#include namespace Antares::Solver::Variable { ThermalState::ThermalState(const Data::AreaList& areas) { thermal.resize(areas.size()); - for (const auto& [id, area] : areas) + for (const auto& [id, area]: areas) { assert(area); thermal[area->index].initializeFromArea(*area); @@ -50,7 +44,7 @@ ThermalState::StateForAnArea& ThermalState::operator[](size_t areaIndex) void ThermalState::StateForAnArea::initializeFromArea(const Data::Area& area) { - const auto count = area.thermal.clusterCount(); + const auto count = area.thermal.list.enabledCount(); thermalClustersProductions.resize(count); numberOfUnitsONbyCluster.resize(count); thermalClustersOperatingCost.resize(count); @@ -60,19 +54,14 @@ void ThermalState::StateForAnArea::initializeFromArea(const Data::Area& area) pminOfAGroup.resize(count, 0); } -State::State(Data::Study& s) : - hourInTheSimulation(0u), - dispatchableMargin(nullptr), - studyMode(s.parameters.mode), - unitCommitmentMode(s.parameters.unitCommitment.ucMode), - study(s), - thermal(s.areas), - simplexRunNeeded(true), - annualSystemCost(0.), - optimalSolutionCost1(0.), - optimalSolutionCost2(0.), - averageOptimizationTime1(0.), - averageOptimizationTime2(0.) +State::State(Data::Study& s): + hourInTheSimulation(0u), + dispatchableMargin(nullptr), + simulationMode(s.parameters.mode), + unitCommitmentMode(s.parameters.unitCommitment.ucMode), + study(s), + thermal(s.areas), + simplexRunNeeded(true) { } @@ -80,12 +69,12 @@ void State::initFromThermalClusterIndex(const uint clusterAreaWideIndex) { // asserts assert(area); - assert(clusterAreaWideIndex < area->thermal.clusterCount()); + assert(clusterAreaWideIndex < area->thermal.list.enabledCount()); // alias to the current thermal cluster - thermalCluster = area->thermal.clusters[clusterAreaWideIndex]; - double thermalClusterAvailableProduction - = thermalCluster->series->getAvailablePower(hourInTheYear, this->year); + thermalCluster = area->thermal.list.enabledClusterAt(clusterAreaWideIndex).get(); + double thermalClusterAvailableProduction = thermalCluster->series.getCoefficient(this->year, + hourInTheYear); // Minimum power of a group of the cluster for the current hour in the year double thermalClusterPMinOfAGroup = 0.; @@ -95,25 +84,26 @@ void State::initFromThermalClusterIndex(const uint clusterAreaWideIndex) // When the cluster is in must-run mode, the production value // directly comes from the time-series // it doen't exist from the solver perspective - assert(thermalCluster->series); - assert(hourInTheYear < thermalCluster->series->timeSeries.height); + assert(hourInTheYear < thermalCluster->series.timeSeries.height); thermal[area->index].thermalClustersProductions[clusterAreaWideIndex] = thermalClusterAvailableProduction; thermal[area->index].PMinOfClusters[clusterAreaWideIndex] = 0.; - thermal[area->index].numberOfUnitsONbyCluster[clusterAreaWideIndex] - = 0; // will be calculated during the smoothing + thermal[area->index].numberOfUnitsONbyCluster[clusterAreaWideIndex] = 0; // will be + // calculated + // during the + // smoothing } else { // otherwise from the solver (most of the time) - if (studyMode != Data::stdmAdequacy) // Economy + if (simulationMode != Data::SimulationMode::Adequacy) // Economy { - thermalClusterPMinOfAGroup - = problemeHebdo->PaliersThermiquesDuPays[area->index] - .pminDUnGroupeDuPalierThermique[thermalCluster->index]; // one by cluster + thermalClusterPMinOfAGroup = problemeHebdo->PaliersThermiquesDuPays[area->index] + .pminDUnGroupeDuPalierThermique + [thermalCluster->index]; // one by cluster thermal[area->index].PMinOfClusters[clusterAreaWideIndex] = problemeHebdo->PaliersThermiquesDuPays[area->index] .PuissanceDisponibleEtCout[thermalCluster->index] @@ -130,18 +120,23 @@ void State::initFromThermalClusterIndex(const uint clusterAreaWideIndex) = hourlyResults->ProductionThermique[hourInTheWeek] .ProductionThermiqueDuPalier[thermalCluster->index]; - if (unitCommitmentMode == Antares::Data::UnitCommitmentMode::ucMILP) // Economy accurate - thermal[area->index].numberOfUnitsONbyCluster[clusterAreaWideIndex] - = static_cast(hourlyResults->ProductionThermique[hourInTheWeek] - .NombreDeGroupesEnMarcheDuPalier[thermalCluster->index]); - else + switch (unitCommitmentMode) + { + using ucMode = Antares::Data::UnitCommitmentMode; + case ucMode::ucHeuristicAccurate: + case ucMode::ucMILP: + thermal[area->index].numberOfUnitsONbyCluster[clusterAreaWideIndex] = static_cast( + hourlyResults->ProductionThermique[hourInTheWeek] + .NombreDeGroupesEnMarcheDuPalier[thermalCluster->index]); + break; + default: // Economy Fast or Adequacy -- will be calculated during the smoothing thermal[area->index].numberOfUnitsONbyCluster[clusterAreaWideIndex] = 0; + } } - initFromThermalClusterIndexProduction(clusterAreaWideIndex); - if (studyMode != Data::stdmAdequacy) + if (simulationMode != Data::SimulationMode::Adequacy) { // Minimum power of a group of the cluster, one per year for each cluster - from the // solver @@ -155,7 +150,7 @@ void State::initFromThermalClusterIndex(const uint clusterAreaWideIndex) void State::initFromThermalClusterIndexProduction(const uint clusterAreaWideIndex) { - uint serieIndex = thermalCluster->series->timeseriesNumbers[0][this->year]; + uint serieIndex = thermalCluster->series.timeseriesNumbers[this->year]; if (thermal[area->index].thermalClustersProductions[clusterAreaWideIndex] > 0.) { @@ -169,26 +164,36 @@ void State::initFromThermalClusterIndexProduction(const uint clusterAreaWideInde if (p > thermal[area->index].productionLastHour[clusterAreaWideIndex]) { - newUnitCount - = static_cast(Math::Ceil(p / thermalCluster->nominalCapacityWithSpinning)); + newUnitCount = static_cast( + std::ceil(p / thermalCluster->nominalCapacityWithSpinning)); if (newUnitCount > thermalCluster->unitCount) + { newUnitCount = thermalCluster->unitCount; + } if (newUnitCount < previousUnitCount) + { newUnitCount = previousUnitCount; + } } else { if (thermalCluster->minStablePower > 0.) { - newUnitCount - = static_cast(Math::Ceil(p / thermalCluster->nominalCapacityWithSpinning)); + newUnitCount = static_cast( + std::ceil(p / thermalCluster->nominalCapacityWithSpinning)); if (newUnitCount > thermalCluster->unitCount) + { newUnitCount = thermalCluster->unitCount; + } } else + { newUnitCount = thermalCluster->unitCount; + } if (newUnitCount > previousUnitCount) + { newUnitCount = previousUnitCount; + } } // calculating the operating cost for the current hour @@ -204,8 +209,9 @@ void State::initFromThermalClusterIndexProduction(const uint clusterAreaWideInde } // Fixed price - thermal[area->index].thermalClustersOperatingCost[clusterAreaWideIndex] - += thermalCluster->fixedCost * newUnitCount; + thermal[area->index].thermalClustersOperatingCost[clusterAreaWideIndex] += thermalCluster + ->fixedCost + * newUnitCount; // Storing the new unit count for the next hour thermal[area->index].unitCountLastHour[clusterAreaWideIndex] = newUnitCount; @@ -221,43 +227,46 @@ void State::initFromThermalClusterIndexProduction(const uint clusterAreaWideInde void State::yearEndBuildFromThermalClusterIndex(const uint clusterAreaWideIndex) { - uint maxDurationON; // nombre d'heures de fonctionnement d'un groupe au delà duquel un + uint maxDurationON; // nombre d'heures de fonctionnement d'un groupe au delà duquel un // arrêt/redémarrage est préférable uint maxUnitNeeded = 0; uint startHourForCurrentYear = study.runtime->rangeLimits.hour[Data::rangeBegin]; - uint endHourForCurrentYear - = startHourForCurrentYear + study.runtime->rangeLimits.hour[Data::rangeCount]; + uint endHourForCurrentYear = startHourForCurrentYear + + study.runtime->rangeLimits.hour[Data::rangeCount]; - assert(endHourForCurrentYear <= Variable::maxHoursInAYear); + assert(endHourForCurrentYear <= HOURS_PER_YEAR); // Nombre minimal de groupes en fonctionnement à l'heure h (determiné par Peff et Pnom) - std::array ON_min; + std::array ON_min; // Nombre maximal de groupes en fonctionnement à l'heure h (determine par Peff et Pmin) - std::array ON_max; + std::array ON_max; // Nombre de groupes économiquement optimal en fonctionnement à l'heure h - std::array ON_opt {}; - + std::array ON_opt{}; // Get cluster properties - Data::ThermalCluster* currentCluster = area->thermal.clusters[clusterAreaWideIndex]; + Data::ThermalCluster* currentCluster = area->thermal.list.enabledClusterAt(clusterAreaWideIndex) + .get(); - assert(endHourForCurrentYear <= Variable::maxHoursInAYear); - assert(endHourForCurrentYear <= currentCluster->series->timeSeries.height); + assert(endHourForCurrentYear <= HOURS_PER_YEAR); + assert(endHourForCurrentYear <= currentCluster->series.timeSeries.height); assert(currentCluster); - assert(currentCluster->series); if (currentCluster->fixedCost > 0.) { maxDurationON = static_cast( - Math::Floor(currentCluster->startupCost / currentCluster->fixedCost)); + std::floor(currentCluster->startupCost / currentCluster->fixedCost)); if (maxDurationON > endHourForCurrentYear) + { maxDurationON = endHourForCurrentYear; + } } else + { maxDurationON = endHourForCurrentYear; + } // min, and max unit ON calculation - const auto& availableProduction = currentCluster->series->getAvailablePowerYearly(this->year); + const auto& availableProduction = currentCluster->series.getColumn(this->year); for (uint h = startHourForCurrentYear; h < endHourForCurrentYear; ++h) { maxUnitNeeded = 0u; @@ -271,8 +280,8 @@ void State::yearEndBuildFromThermalClusterIndex(const uint clusterAreaWideIndex) { // When the cluster is in must-run mode, the production value // directly comes from the time-series - thermalClusterProduction - = thermalClusterAvailableProduction; // in mustrun, production==available + thermalClusterProduction = thermalClusterAvailableProduction; // in mustrun, + // production==available // production } else @@ -282,95 +291,110 @@ void State::yearEndBuildFromThermalClusterIndex(const uint clusterAreaWideIndex) } if (thermalClusterProduction <= 0.) + { continue; + } - uint serieIndex = currentCluster->series->timeseriesNumbers[0][this->year]; - thermalClusterOperatingCostForYear[h] - = thermalClusterProduction * currentCluster->getOperatingCost(serieIndex, h); + uint serieIndex = currentCluster->series.timeseriesNumbers[this->year]; + thermalClusterOperatingCostForYear[h] = thermalClusterProduction + * currentCluster->getOperatingCost(serieIndex, h); switch (unitCommitmentMode) { - case Antares::Data::UnitCommitmentMode::ucHeuristic: - { - // ON_min[h] = static_cast(Math::Ceil(thermalClusterProduction / - // currentCluster->nominalCapacityWithSpinning)); // code 5.0.3b<7 - // 5.0.3b7 - if (thermal[area->index].pminOfAGroup[clusterAreaWideIndex] > 0.) - { - ON_min[h] = Math::Max( - Math::Min(static_cast( - Math::Floor(thermalClusterPMinOfTheClusterForYear[h] - / thermal[area->index].pminOfAGroup[clusterAreaWideIndex])), - static_cast( - Math::Ceil(thermalClusterAvailableProduction - / currentCluster->nominalCapacityWithSpinning))), - static_cast( - Math::Ceil(thermalClusterProduction / currentCluster->nominalCapacityWithSpinning))); - } - else - ON_min[h] = static_cast(Math::Ceil( - thermalClusterProduction / currentCluster->nominalCapacityWithSpinning)); - break; - } - case Antares::Data::UnitCommitmentMode::ucMILP: - { - ON_min[h] = Math::Max( - static_cast(Math::Ceil(thermalClusterProduction / currentCluster->nominalCapacityWithSpinning)), - thermalClusterDispatchedUnitsCountForYear[h]); // eq. to thermalClusterON for - // that hour + case Antares::Data::UnitCommitmentMode::ucHeuristicFast: + { + // ON_min[h] = static_cast(std::ceil(thermalClusterProduction / + // currentCluster->nominalCapacityWithSpinning)); // code 5.0.3b<7 + // 5.0.3b7 + if (thermal[area->index].pminOfAGroup[clusterAreaWideIndex] > 0.) + { + ON_min[h] = std::max( + std::min(static_cast( + std::floor(thermalClusterPMinOfTheClusterForYear[h] + / thermal[area->index].pminOfAGroup[clusterAreaWideIndex])), + static_cast( + std::ceil(thermalClusterAvailableProduction + / currentCluster->nominalCapacityWithSpinning))), + static_cast(std::ceil(thermalClusterProduction + / currentCluster->nominalCapacityWithSpinning))); + } + else + { + ON_min[h] = static_cast(std::ceil( + thermalClusterProduction / currentCluster->nominalCapacityWithSpinning)); + } + break; + } + case Antares::Data::UnitCommitmentMode::ucMILP: + case Antares::Data::UnitCommitmentMode::ucHeuristicAccurate: + { + ON_min[h] = std::max( + static_cast( + std::ceil(thermalClusterProduction / currentCluster->nominalCapacityWithSpinning)), + thermalClusterDispatchedUnitsCountForYear[h]); // eq. to thermalClusterON for + // that hour - break; - } - case Antares::Data::UnitCommitmentMode::ucUnknown: - { - logs.warning() << "Unknown unit-commitment mode"; - break; - } + break; + } + case Antares::Data::UnitCommitmentMode::ucUnknown: + { + logs.warning() << "Unknown unit-commitment mode"; + break; + } } - ON_max[h] = static_cast(Math::Ceil( - thermalClusterAvailableProduction / currentCluster->nominalCapacityWithSpinning)); + ON_max[h] = static_cast(std::ceil(thermalClusterAvailableProduction + / currentCluster->nominalCapacityWithSpinning)); if (currentCluster->minStablePower > 0.) { maxUnitNeeded = static_cast( - Math::Floor(thermalClusterProduction / currentCluster->minStablePower)); + std::floor(thermalClusterProduction / currentCluster->minStablePower)); if (ON_max[h] > maxUnitNeeded) + { ON_max[h] = maxUnitNeeded; + } } if (ON_max[h] < ON_min[h]) + { ON_max[h] = ON_min[h]; + } } if (maxDurationON > 0) + { ON_opt = computeEconomicallyOptimalNbClustersONforEachHour(maxDurationON, ON_min, ON_max); + } // Calculation of non linear and startup costs yearEndBuildThermalClusterCalculateStartupCosts(maxDurationON, ON_min, ON_opt, currentCluster); } -void State::yearEndBuildThermalClusterCalculateStartupCosts(const uint& maxDurationON, - const std::array& ON_min, - const std::array& ON_opt, - const Data::ThermalCluster* currentCluster) +void State::yearEndBuildThermalClusterCalculateStartupCosts( + const uint& maxDurationON, + const std::array& ON_min, + const std::array& ON_opt, + const Data::ThermalCluster* currentCluster) { uint startHourForCurrentYear = study.runtime->rangeLimits.hour[Data::rangeBegin]; - uint endHourForCurrentYear - = startHourForCurrentYear + study.runtime->rangeLimits.hour[Data::rangeCount]; + uint endHourForCurrentYear = startHourForCurrentYear + + study.runtime->rangeLimits.hour[Data::rangeCount]; for (uint hour = startHourForCurrentYear; hour < endHourForCurrentYear; ++hour) { double thermalClusterStartupCostForYear = 0; double thermalClusterFixedCostForYear = 0; - // based on duration, if maxDurationON==0 we choose the mininum of ON clusters, otherwise, the - // optimal number. + // based on duration, if maxDurationON==0 we choose the mininum of ON clusters, otherwise, + // the optimal number. uint optimalCount = (maxDurationON == 0) ? ON_min[hour] : ON_opt[hour]; // NODU cannot be > unit count if (optimalCount > currentCluster->unitCount) + { optimalCount = currentCluster->unitCount; + } thermalClusterFixedCostForYear = currentCluster->fixedCost * optimalCount; @@ -378,19 +402,18 @@ void State::yearEndBuildThermalClusterCalculateStartupCosts(const uint& maxDurat { // nombre de groupes démarrés à l'heure h int delta = (maxDurationON == 0) ? ON_min[hour] - ON_min[hour - 1] - : ON_opt[hour] - ON_opt[hour - 1]; + : ON_opt[hour] - ON_opt[hour - 1]; - (delta > 0) - ? (thermalClusterStartupCostForYear = currentCluster->startupCost * delta) - : (thermalClusterStartupCostForYear = 0.); + (delta > 0) ? (thermalClusterStartupCostForYear = currentCluster->startupCost * delta) + : (thermalClusterStartupCostForYear = 0.); } // Aggregated variables for output // NP Cost = SU + Fx // Op. Cost = (P.lvl * P.Cost) + NP.Cost - thermalClusterNonProportionalCostForYear[hour] - = thermalClusterStartupCostForYear + thermalClusterFixedCostForYear; + thermalClusterNonProportionalCostForYear[hour] = thermalClusterStartupCostForYear + + thermalClusterFixedCostForYear; thermalClusterOperatingCostForYear[hour] += thermalClusterNonProportionalCostForYear[hour]; // Other variables for output @@ -399,17 +422,17 @@ void State::yearEndBuildThermalClusterCalculateStartupCosts(const uint& maxDurat } } -std::array -State::computeEconomicallyOptimalNbClustersONforEachHour(const uint& maxDurationON, - const std::array& ON_min, - const std::array& ON_max) const +std::array State::computeEconomicallyOptimalNbClustersONforEachHour( + const uint& maxDurationON, + const std::array& ON_min, + const std::array& ON_max) const { uint startHourForCurrentYear = study.runtime->rangeLimits.hour[Data::rangeBegin]; - uint endHourForCurrentYear - = startHourForCurrentYear + study.runtime->rangeLimits.hour[Data::rangeCount]; + uint endHourForCurrentYear = startHourForCurrentYear + + study.runtime->rangeLimits.hour[Data::rangeCount]; // Nombre de groupes économiquement optimal en fonctionnement à l'heure h - std::array ON_opt; + std::array ON_opt; uint nivmax; // valeur maximale de ON_opt[h] , progressivement réactualisée à la baisse uint nivmin; // valeur minimale de ON_opt[h] , progressivement réactualisée à la hausse @@ -438,7 +461,9 @@ State::computeEconomicallyOptimalNbClustersONforEachHour(const uint& maxDuration for (uint k = 1; k <= maxDurationON; ++k) { if (h + k >= endHourForCurrentYear) + { break; // fin de l'année dépassée + } if (ON_max[h + k] <= ON_min[h]) { nivmax = ON_min[h]; @@ -446,12 +471,14 @@ State::computeEconomicallyOptimalNbClustersONforEachHour(const uint& maxDuration } // point très bas rencontré sur ON_max : il vaut mieux arrêter les // groupes dès l'heure h if (ON_max[h + k] - < nivmax) // point moins bas rencontré sur ON_max : la borne sup du - // nombre optimal de groupes à conserver en h diminue + < nivmax) // point moins bas rencontré sur ON_max : la borne sup du + // nombre optimal de groupes à conserver en h diminue { nivmax = ON_max[h + k]; if (nivmax < nivmin) + { break; + } } if (ON_min[h + k] > ON_min[h]) // on est sûr que ON_opt[h] > ON_min[h] { @@ -464,9 +491,8 @@ State::computeEconomicallyOptimalNbClustersONforEachHour(const uint& maxDuration // nivmin=nivmax groupes de h à h+k-1 = h+portee-1 else if (ON_min[h + k] >= nivmin) { - portee = k; // durée provisoire qui pourra être allongée - nivmin - = ON_min[h + k]; // niveau provisoire qui pourra être augmenté + portee = k; // durée provisoire qui pourra être allongée + nivmin = ON_min[h + k]; // niveau provisoire qui pourra être augmenté } } } @@ -476,7 +502,7 @@ State::computeEconomicallyOptimalNbClustersONforEachHour(const uint& maxDuration { ON_opt[h] = ON_min[h]; // la puissance appelée après h ne justifie pas de // maintenir des groupes appelés au-delà du minimum - ++h; // on progresse d'exactement une heure + ++h; // on progresse d'exactement une heure } else { diff --git a/src/solver/variable/state.h b/src/solver/variable/state.h deleted file mode 100644 index 7969a41906..0000000000 --- a/src/solver/variable/state.h +++ /dev/null @@ -1,247 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STATE_H__ -#define __SOLVER_VARIABLE_STATE_H__ - -#include -#include -#include -#include "constants.h" -#include -#include -#include "../simulation/sim_structure_donnees.h" -#include "../simulation/sim_structure_probleme_economique.h" -#include "../simulation/sim_extern_variables_globales.h" - -namespace Antares::Solver::Variable -{ -class ThermalState -{ -public: - explicit ThermalState(const Data::AreaList& areas); - - class StateForAnArea - { - public: - void initializeFromArea(const Data::Area& area); - //! Thermal production for thermal clusters for the current hour in the year - std::vector thermalClustersProductions; - - //! The operating cost for all clusters at the current hour (production level*production - //! cost + NP Cost) - std::vector thermalClustersOperatingCost; - - //! Number of units turned ON by cluster for the current hour in the year with the ucMILP - //! (accurate) unit commitment mode - std::vector numberOfUnitsONbyCluster; - - //! Minimum power of all clusters for the current hour in the year - std::vector PMinOfClusters; - - std::vector unitCountLastHour; - std::vector productionLastHour; - std::vector pminOfAGroup; - }; - - StateForAnArea& operator[](size_t areaIndex); - -private: - std::vector thermal; -}; - -class State -{ -public: - explicit State(Data::Study& s); - - /*! - ** \brief Initialize some variables according an area index - ** - ** \param areaIndex Index of the area - */ - void initFromAreaIndex(const unsigned int areaIndex, uint numSpace); - - /*! - ** \brief Initialize some variable according a thermal cluster index - ** - ** We assume here that the variables related to an area - ** are properly initialized. - ** - ** \param areaWideIndex Index of the thermal cluster for the current area - */ - void initFromThermalClusterIndex(const unsigned int areaWideIndex); - - /*! - ** \brief End the year by smoothing the thermal units run - ** and computing costs. - ** We assume here that the variables related to an area - ** are properly initialized. - ** - ** \param areaWideIndex Index of the thermal cluster for the current area - */ - - void yearEndBuildFromThermalClusterIndex(const unsigned int areaWideIndex); - -private: - /*! - ** \brief Initialize some variable according a thermal cluster index - ** - ** Called in initFromAreaIndex to split code - ** - ** \param areaWideIndex Index of the thermal cluster for the current area - */ - void initFromThermalClusterIndexProduction(const unsigned int areaWideIndex); - - void yearEndBuildThermalClusterCalculateStartupCosts( - const uint& maxDurationON, - const std::array& ON_min, - const std::array& ON_opt, - const Data::ThermalCluster* currentCluster); - - std::array computeEconomicallyOptimalNbClustersONforEachHour( - const uint& maxDurationON, - const std::array& ON_min, - const std::array& ON_max) const; - - /*! - ** \brief Smooth the thermal units run after resolutions - ** using heuristics - ** - ** \param areaWideIndex Index of the thermal cluster for the current area - */ - void yearEndSmoothDispatchedUnitsCount(const unsigned int areaWideIndex, uint numSpace); - -public: - /*! - ** \brief Reset internal data - */ - void startANewYear(); - - /*! - ** \brief Reset thermal internal data for end of year calculations - */ - void yearEndResetThermal(); - - //! Current year - unsigned int year; - //! Current week for current year (zero-based) - unsigned int weekInTheYear; - //! Current hour in the year (zero-based) - unsigned int hourInTheYear; - //! Current hour in the week (zero-based) - unsigned int hourInTheWeek; - //! Current hour from the begining of the simulation - unsigned int hourInTheSimulation; - - //! The current area - Data::Area* area; - - //! The current thermal cluster (used in yearEndBuildForEachThermalCluster functions) - Data::ThermalCluster* thermalCluster; - - //! The current renewable cluster - Data::RenewableCluster* renewableCluster; - //! The Scratchpad for the current area - Data::AreaScratchpad* scratchpad; - //! The current link - Data::AreaLink* link; - - //! \name Adequacy - //@{ - /*! - ** \brief Spilled energy for all areas in the week - */ - Matrix<> resSpilled; - //@} - - //! \name Economy - //@{ - RESULTATS_HORAIRES* hourlyResults; - //! NTC Values - VALEURS_DE_NTC_ET_RESISTANCES ntc; - - //! Thermal production for the current thermal cluster for the whole year - double thermalClusterProductionForYear[Variable::maxHoursInAYear]; - //! Number of unit dispatched for all clusters for the whole year for ucHeruistic (fast) or - //! ucMILP (accurate) - uint thermalClusterDispatchedUnitsCountForYear[Variable::maxHoursInAYear]; - - //! Thermal operating cost for the current thermal cluster for the whole year - double thermalClusterOperatingCostForYear[Variable::maxHoursInAYear]; - //! Thermal NP Cost for the current thermal cluster for the whole year - double thermalClusterNonProportionalCostForYear[Variable::maxHoursInAYear]; - //! Minimum power of the cluster for the whole year - double thermalClusterPMinOfTheClusterForYear[Variable::maxHoursInAYear]; - - double renewableClusterProduction; - - //! Dispatchable margin for the current area (valid only from weekForEachArea) - const double* dispatchableMargin; - //@} - - //! Probleme Hebdo - PROBLEME_HEBDO* problemeHebdo; - - //! Study mode: economy / adequacy - Data::StudyMode studyMode; - //! Study unit commitment mode: fast(ucHeuristic) / accurate(ucMILP) - Data::UnitCommitmentMode unitCommitmentMode; - //! Reference to the original study - Data::Study& study; - // Thermal data, used to compute overall cost, etc. - ThermalState thermal; - //! Index of the state in the state vector - unsigned int numSpace; - /*! - ** \brief Flag to know if the simplex has been used for the current week - */ - bool simplexRunNeeded; - - // Annual costs to be printed in output into separate files - // ----------------------------------------------------------------- - // Sum over all year's hours of : - // - sum over all areas of variable "overall cost" - // - sum over all links of variable "hurdle cost". - // That is : Somme(h in Y)[ Somme(a in areas)(OV. COST[h,a]) + Somme(l in links)(HURDLE - // COST[h,l]) ] - double annualSystemCost; - // Sum of the weekly optimal costs over the year (first optimisation step) - double optimalSolutionCost1; - // Sum of the weekly optimal costs over the year (second optimisation step) - double optimalSolutionCost2; - // Average time spent in first optimization over the year (ms) - double averageOptimizationTime1; - // Average time spent in second optimization over the year (ms) - double averageOptimizationTime2; - // ----------------------------------------------------------------- -}; // class State - -} // namespace Antares::Solver::Variable - -#include "state.hxx" - -#endif // __SOLVER_VARIABLE_STATE_H__ diff --git a/src/solver/variable/state.hxx b/src/solver/variable/state.hxx deleted file mode 100644 index dca9b0a9b5..0000000000 --- a/src/solver/variable/state.hxx +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STATE_HXX__ -#define __SOLVER_VARIABLE_STATE_HXX__ - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -inline void State::startANewYear() -{ - hourInTheSimulation = 0u; - - memset(thermalClusterProductionForYear, 0, sizeof(thermalClusterProductionForYear)); - memset(thermalClusterOperatingCostForYear, 0, sizeof(thermalClusterOperatingCostForYear)); - memset(thermalClusterNonProportionalCostForYear, - 0, - sizeof(thermalClusterNonProportionalCostForYear)); - memset(thermalClusterPMinOfTheClusterForYear, 0, sizeof(thermalClusterPMinOfTheClusterForYear)); - memset(thermalClusterDispatchedUnitsCountForYear, - 0, - sizeof(thermalClusterDispatchedUnitsCountForYear)); - - // Re-initializing annual costs (to be printed in output into separate files) - annualSystemCost = 0.; - optimalSolutionCost1 = 0.; - optimalSolutionCost2 = 0.; - averageOptimizationTime1 = 0.; - averageOptimizationTime2 = 0.; -} - -inline void State::yearEndResetThermal() -{ - memset(thermalClusterProductionForYear, 0, sizeof(thermalClusterProductionForYear)); - memset(thermalClusterOperatingCostForYear, 0, sizeof(thermalClusterOperatingCostForYear)); - memset(thermalClusterNonProportionalCostForYear, - 0, - sizeof(thermalClusterNonProportionalCostForYear)); - memset(thermalClusterPMinOfTheClusterForYear, 0, sizeof(thermalClusterPMinOfTheClusterForYear)); - memset(thermalClusterDispatchedUnitsCountForYear, - 0, - sizeof(thermalClusterDispatchedUnitsCountForYear)); -} - -inline void State::initFromAreaIndex(const unsigned int areaIndex, uint numSpace) -{ - area = study.areas[areaIndex]; - scratchpad = &area->scratchpad[numSpace]; - thermalCluster = nullptr; - - switch (studyMode) - { - case Data::stdmEconomy: - { - hourlyResults = &problemeHebdo->ResultatsHoraires[areaIndex]; - break; - } - case Data::stdmAdequacy: - { - hourlyResults = &problemeHebdo->ResultatsHoraires[areaIndex]; - break; - } - case Data::stdmUnknown: - break; - case Data::stdmExpansion: - break; - case Data::stdmMax: - break; - } -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STATE_HXX__ diff --git a/src/solver/variable/storage/average.h b/src/solver/variable/storage/average.h deleted file mode 100644 index cc09b72533..0000000000 --- a/src/solver/variable/storage/average.h +++ /dev/null @@ -1,229 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_AVERAGE_H__ -#define __SOLVER_VARIABLE_STORAGE_AVERAGE_H__ - -#include "averagedata.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -template -struct Average : public NextT -{ -public: - //! Type of the net item in the list - typedef NextT NextType; - - enum - { - //! The count if item in the list - count = 1 + NextT::count, - - categoryFile = NextT::categoryFile | Variable::Category::allFile, - }; - - struct Data - { - double value; - uint32_t indice; - }; - - //! Name of the filter - static const char* Name() - { - return "average"; - } - -public: - Average() - { - } - -protected: - void initializeFromStudy(Antares::Data::Study& study) - { - avgdata.initializeFromStudy(study); - // Next - NextType::initializeFromStudy(study); - } - - void reset() - { - // Reset - avgdata.reset(); - // Next - NextType::reset(); - } - - void merge(uint year, const IntermediateValues& rhs) - { - avgdata.merge(year, rhs); - // Next - NextType::merge(year, rhs); - } - - template - void buildSurveyReport(SurveyResults& report, - const S& results, - int dataLevel, - int fileLevel, - int precision) const - { - if (!(fileLevel & Category::id)) - { - switch (precision) - { - case Category::hourly: - InternalExportValues( - report, Memory::RawPointer(avgdata.hourly)); - break; - case Category::daily: - InternalExportValues(report, - avgdata.daily); - break; - case Category::weekly: - InternalExportValues(report, - avgdata.weekly); - break; - case Category::monthly: - InternalExportValues(report, - avgdata.monthly); - break; - case Category::annual: - InternalExportValues<1, VCardT, Category::annual>(report, avgdata.year); - break; - } - } - // Next - NextType::template buildSurveyReport( - report, results, dataLevel, fileLevel, precision); - } - - template - void buildDigest(SurveyResults& report, int digestLevel, int dataLevel) const - { - const bool isCluster = (VCardT::categoryFileLevel & Category::de) - || (VCardT::categoryFileLevel & Category::de_res); - const bool isBindingConstraint = VCardT::categoryFileLevel & Category::bc; - const bool isDigest = digestLevel & Category::digestAllYears; - if ((dataLevel & Category::area || dataLevel & Category::setOfAreas) && isDigest - && !isCluster && !isBindingConstraint) - { - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] - = (report.variableCaption == "LOLP") ? "values" : "EXP"; - - // Precision - report.precision[report.data.columnIndex] - = PrecisionToPrintfFormat::Value(); - // Value - report.values[report.data.columnIndex][report.data.rowIndex] = avgdata.allYears; - // Non applicability - report.digestNonApplicableStatus[report.data.rowIndex][report.data.columnIndex] - = *report.isCurrentVarNA; - - ++(report.data.columnIndex); - } - // Next - NextType::template buildDigest(report, digestLevel, dataLevel); - } - - uint64_t memoryUsage() const - { - return avgdata.dynamicMemoryUsage() + NextType::memoryUsage(); - } - - template class DecoratorT> - Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const - { - if (Yuni::Static::Type::StrictlyEqual, Average>::Yes) - return avgdata.hourly; - return NextType::template hourlyValuesForSpatialAggregate(); - } - -public: - AverageData avgdata; - -private: - template - void InternalExportValues(SurveyResults& report, const double* array) const - { - assert(array); - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - // Caption - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] - = (report.variableCaption == "LOLP") ? "values" : "EXP"; - // Precision - report.precision[report.data.columnIndex] - = PrecisionToPrintfFormat::Value(); - // Non applicability - report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; - - // Values - switch (PrecisionT) - { - case Category::annual: - { - double& target = *(report.values[report.data.columnIndex]); - target = 0; - for (uint i = 0; i != avgdata.nbYearsCapacity; ++i) - target += array[i]; - avgdata.allYears = target; - break; - } - default: - (void)::memcpy(report.values[report.data.columnIndex], array, sizeof(double) * Size); - break; - } - - // Next column index - ++report.data.columnIndex; - } - -}; // class Average - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_AVERAGE_H__ diff --git a/src/solver/variable/storage/averagedata.cpp b/src/solver/variable/storage/averagedata.cpp index 8818d8817b..4a88945bb6 100644 --- a/src/solver/variable/storage/averagedata.cpp +++ b/src/solver/variable/storage/averagedata.cpp @@ -1,47 +1,39 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/variable/storage/averagedata.h" + #include -#include "intermediate.h" -#include "averagedata.h" + +#include "antares/solver/variable/storage/intermediate.h" using namespace Yuni; -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears +namespace Antares::Solver::Variable::R::AllYears { -AverageData::AverageData() : hourly(nullptr), year(nullptr), nbYearsCapacity(0), allYears(0.) +AverageData::AverageData(): + hourly(nullptr), + year(nullptr), + nbYearsCapacity(0), + allYears(0.) { } @@ -53,16 +45,16 @@ AverageData::~AverageData() void AverageData::reset() { - Antares::Memory::Zero(maxHoursInAYear, hourly); - (void)::memset(monthly, 0, sizeof(double) * maxMonths); - (void)::memset(weekly, 0, sizeof(double) * maxWeeksInAYear); - (void)::memset(daily, 0, sizeof(double) * maxDaysInAYear); + Antares::Memory::Zero(HOURS_PER_YEAR, hourly); + (void)::memset(monthly, 0, sizeof(double) * MONTHS_PER_YEAR); + (void)::memset(weekly, 0, sizeof(double) * WEEKS_PER_YEAR); + (void)::memset(daily, 0, sizeof(double) * DAYS_PER_YEAR); (void)::memset(year, 0, sizeof(double) * nbYearsCapacity); } void AverageData::initializeFromStudy(Data::Study& study) { - Antares::Memory::Allocate(hourly, maxHoursInAYear); + Antares::Memory::Allocate(hourly, HOURS_PER_YEAR); nbYearsCapacity = study.runtime->rangeLimits.year[Data::rangeEnd] + 1; year = new double[nbYearsCapacity]; @@ -78,23 +70,27 @@ void AverageData::merge(unsigned int y, const IntermediateValues& rhs) double ratio = (double)yearsWeight[y] / (double)yearsWeightSum; // Average value for each hour throughout all years - for (i = 0; i != maxHoursInAYear; ++i) + for (i = 0; i != HOURS_PER_YEAR; ++i) + { hourly[i] += rhs.hour[i] * ratio; + } // Average value for each day throughout all years - for (i = 0; i != maxDaysInAYear; ++i) + for (i = 0; i != DAYS_PER_YEAR; ++i) + { daily[i] += rhs.day[i] * ratio; + } // Average value for each week throughout all years - for (i = 0; i != maxWeeksInAYear; ++i) + for (i = 0; i != WEEKS_PER_YEAR; ++i) + { weekly[i] += rhs.week[i] * ratio; + } // Average value for each month throughout all years - for (i = 0; i != maxMonths; ++i) + for (i = 0; i != MONTHS_PER_YEAR; ++i) + { monthly[i] += rhs.month[i] * ratio; + } // Average value throughout all years year[y] += rhs.year * ratio; } -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver::Variable::R::AllYears diff --git a/src/solver/variable/storage/averagedata.h b/src/solver/variable/storage/averagedata.h deleted file mode 100644 index 8f7d4d4109..0000000000 --- a/src/solver/variable/storage/averagedata.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_AVERAGE_DATA_H__ -#define __SOLVER_VARIABLE_STORAGE_AVERAGE_DATA_H__ - -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -class AverageData -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - AverageData(); - //! Destructor - ~AverageData(); - - void initializeFromStudy(Data::Study& study); - - void reset(); - - void merge(unsigned int year, const IntermediateValues& rhs); - - uint64_t dynamicMemoryUsage() const - { - return sizeof(double) * maxHoursInAYear + sizeof(double) * nbYearsCapacity; - } - -public: - double monthly[maxMonths]; - double weekly[maxWeeksInAYear]; - double daily[maxDaysInAYear]; - Antares::Memory::Stored::Type hourly; - double* year; - unsigned int nbYearsCapacity; - mutable double allYears; // FIX MEEE - Remove the mutable as soon as possible - std::vector yearsWeight; - float yearsWeightSum; - -}; // class AverageData - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_AVERAGE_DATA_H__ diff --git a/src/solver/variable/storage/empty.h b/src/solver/variable/storage/empty.h deleted file mode 100644 index 6d5c86973a..0000000000 --- a/src/solver/variable/storage/empty.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_EMPTY_H__ -#define __SOLVER_VARIABLE_STORAGE_EMPTY_H__ - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -struct Empty -{ -public: - //! Name of the filter - const char* Name() - { - return NULL; - } - enum - { - //! The count if item in the list - count = 0, - categoryFile = 0, - }; - -protected: - static void initializeFromStudy(const Data::Study&) - { - // Does nothing - } - - static void reset() - { - // Does nothing - } - - static void merge(unsigned int /*year*/, const IntermediateValues& /*rhs*/) - { - // Does nothing - } - - template - static void buildSurveyReport(SurveyResults&, const S&, int, int, int) - { - // Does nothing - } - - template - static void buildDigest(SurveyResults&, int, int) - { - // Does nothing - } - - static uint64_t memoryUsage() - { - return 0; - } - - template class DecoratorT> - static Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() - { - return Antares::Memory::Stored::NullValue(); - } - -}; // class Empty - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_EMPTY_H__ diff --git a/src/solver/variable/storage/fwd.h b/src/solver/variable/storage/fwd.h deleted file mode 100644 index b5eb707ba9..0000000000 --- a/src/solver/variable/storage/fwd.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_FORWARD_H__ -#define __SOLVER_VARIABLE_STORAGE_FORWARD_H__ - -#include "../categories.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -// Forward declaration -struct Empty; - -namespace R -{ -namespace AllYears -{ -template -struct Raw; - -template -struct Or; - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_FORWARD_H__ diff --git a/src/solver/variable/storage/intermediate.cpp b/src/solver/variable/storage/intermediate.cpp index 3cd34effb7..4799085aaf 100644 --- a/src/solver/variable/storage/intermediate.cpp +++ b/src/solver/variable/storage/intermediate.cpp @@ -1,50 +1,45 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/variable/storage/intermediate.h" + #include #include + #include -#include "intermediate.h" using namespace Yuni; -namespace Antares +namespace Antares::Solver::Variable { -namespace Solver +IntermediateValues::IntermediateValues(): + pRange(nullptr), + calendar(nullptr), + year(0.) { -namespace Variable -{ -IntermediateValues::IntermediateValues() : pRange(nullptr), calendar(nullptr), year(0.) -{ - Antares::Memory::Allocate(hour, maxHoursInAYear); - Antares::Memory::Zero(maxHoursInAYear, hour); - (void)::memset(month, 0, sizeof(Type) * maxMonths); - (void)::memset(week, 0, sizeof(Type) * maxWeeksInAYear); - (void)::memset(day, 0, sizeof(Type) * maxDaysInAYear); + Antares::Memory::Allocate(hour, HOURS_PER_YEAR); + Antares::Memory::Zero(HOURS_PER_YEAR, hour); + (void)::memset(month, 0, sizeof(Type) * MONTHS_PER_YEAR); + (void)::memset(week, 0, sizeof(Type) * WEEKS_PER_YEAR); + (void)::memset(day, 0, sizeof(Type) * DAYS_PER_YEAR); } void IntermediateValues::initializeFromStudy(Data::Study& study) @@ -67,7 +62,9 @@ void IntermediateValues::computeStatisticsAdequacyForTheCurrentYear() // For each day in the year for (uint i = pRange->hour[Data::rangeBegin]; i <= pRange->hour[Data::rangeEnd]; ++i) + { year += hour[i]; + } } void IntermediateValues::computeStatisticsForTheCurrentYear() @@ -90,9 +87,9 @@ void IntermediateValues::computeStatisticsForTheCurrentYear() { double d = 0.; // One day - for (j = 0; j != maxHoursInADay; ++j) + for (j = 0; j != HOURS_PER_DAY; ++j) { - assert(indx < maxHoursInAYear); + assert(indx < HOURS_PER_YEAR); d += hour[indx]; ++indx; } @@ -101,10 +98,14 @@ void IntermediateValues::computeStatisticsForTheCurrentYear() } // weeks - for (i = 0; i != maxWeeksInAYear; ++i) + for (i = 0; i != WEEKS_PER_YEAR; ++i) + { week[i] = 0.; + } for (i = pRange->day[Data::rangeBegin]; i <= pRange->day[Data::rangeEnd]; ++i) + { week[calendar->days[i].week] += day[i]; + } // x(m) indx = calendar->months[pRange->month[Data::rangeBegin]].daysYear.first; @@ -141,22 +142,28 @@ void IntermediateValues::computeStatisticsOrForTheCurrentYear() { day[i] = 0.; // One day - for (j = 0; j != maxHoursInADay; ++j) + for (j = 0; j != HOURS_PER_DAY; ++j) { - assert(indx < maxHoursInAYear); + assert(indx < HOURS_PER_YEAR); if (hour[indx] > 0.) + { day[i] = 100.; + } ++indx; } } // weeks - for (i = 0; i != maxWeeksInAYear; ++i) + for (i = 0; i != WEEKS_PER_YEAR; ++i) + { week[i] = 0.; + } for (i = pRange->day[Data::rangeBegin]; i <= pRange->day[Data::rangeEnd]; ++i) { if (day[i] > 0) + { week[calendar->days[i].week] = 100.; + } } // x(m) @@ -213,26 +220,32 @@ void IntermediateValues::computeDailyAveragesForCurrentYear() { // Compute sum of hourly values on the current day of year day_sum = 0.; - for (uint h = 0; h != maxHoursInADay; ++h) + for (uint h = 0; h != HOURS_PER_DAY; ++h) { day_sum += hour[indx]; ++indx; } - day[d] = day_sum / maxHoursInADay; + day[d] = day_sum / HOURS_PER_DAY; } } void IntermediateValues::computeWeeklyAveragesForCurrentYear() { // Re-initialization (a previous MC year could have left non-nil values) - for (int w = 0; w != maxWeeksInAYear; ++w) + for (int w = 0; w != WEEKS_PER_YEAR; ++w) + { week[w] = 0.; + } // Compute weekly averages for each week in the year for (uint d = pRange->day[Data::rangeBegin]; d <= pRange->day[Data::rangeEnd]; ++d) + { week[calendar->days[d].week] += day[d]; + } for (uint w = pRange->week[Data::rangeBegin]; w <= pRange->week[Data::rangeEnd]; ++w) + { week[w] /= pRuntimeInfo->simulationDaysPerWeek[w]; + } } void IntermediateValues::computeMonthlyAveragesForCurrentYear() @@ -290,10 +303,12 @@ void IntermediateValues::computeProbabilitiesForTheCurrentYear() { d = 0.; // One day - for (j = 0; j != maxHoursInADay; ++j) + for (j = 0; j != HOURS_PER_DAY; ++j) { if (hour[indx] > 0.) + { d = ratio; + } ++indx; } day[i] = d; @@ -309,8 +324,10 @@ void IntermediateValues::computeProbabilitiesForTheCurrentYear() } // weeks - for (i = 0; i != maxWeeksInAYear; ++i) + for (i = 0; i != WEEKS_PER_YEAR; ++i) + { week[i] = 0.; + } for (i = pRange->day[Data::rangeBegin]; i <= pRange->day[Data::rangeEnd]; ++i) { if (day[i] > 0.) @@ -330,7 +347,9 @@ void IntermediateValues::computeProbabilitiesForTheCurrentYear() { assert(indx < 7 * 53 + 1); if (day[indx] > 0.) + { d = ratio; + } ++indx; } month[i] = d; @@ -345,17 +364,23 @@ void IntermediateValues::adjustValuesWhenRelatedToAPrice() // Months ratio = 1. / pRange->month[Data::rangeCount]; for (i = pRange->month[Data::rangeBegin]; i <= pRange->month[Data::rangeEnd]; ++i) + { month[i] *= ratio; + } // Weeks ratio = 1. / pRange->week[Data::rangeCount]; for (i = pRange->week[Data::rangeBegin]; i <= pRange->week[Data::rangeEnd]; ++i) + { week[i] *= ratio; + } // Days ratio = 1. / pRange->day[Data::rangeCount]; for (i = pRange->day[Data::rangeBegin]; i <= pRange->day[Data::rangeEnd]; ++i) + { day[i] *= ratio; + } // Year year /= pRange->hour[Data::rangeCount]; @@ -367,6 +392,4 @@ void IntermediateValues::adjustValuesAdequacyWhenRelatedToAPrice() year /= pRange->hour[Data::rangeCount]; } -} // namespace Variable -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver::Variable diff --git a/src/solver/variable/storage/intermediate.hxx b/src/solver/variable/storage/intermediate.hxx deleted file mode 100644 index 865b068ef4..0000000000 --- a/src/solver/variable/storage/intermediate.hxx +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_HXX__ -#define __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_HXX__ - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -inline IntermediateValues::~IntermediateValues() -{ - Antares::Memory::Release(hour); -} - -inline void IntermediateValues::reset() -{ - Antares::Memory::Zero(maxHoursInAYear, hour); - memset(month, 0, sizeof(month)); - memset(week, 0, sizeof(week)); - memset(day, 0, sizeof(day)); -} - -inline IntermediateValues::Type& IntermediateValues::operator[](const unsigned int index) -{ - return hour[index]; -} - -inline const IntermediateValues::Type& IntermediateValues::operator[]( - const unsigned int index) const -{ - return hour[index]; -} - -inline uint64_t IntermediateValues::MemoryUsage() -{ - return +sizeof(Type) * maxHoursInAYear; -} - -template -inline void IntermediateValues::buildAnnualSurveyReport(SurveyResults& report, - int fileLevel, - int precision) const -{ - if (!(fileLevel & Category::id)) - { - switch (precision) - { - case Category::hourly: - internalExportAnnualValues(report, hour, false); - break; - case Category::daily: - internalExportAnnualValues(report, day, false); - break; - case Category::weekly: - internalExportAnnualValues(report, week, false); - break; - case Category::monthly: - internalExportAnnualValues(report, month, false); - break; - case Category::annual: - internalExportAnnualValues<1, VCardT>(report, &year, true); - break; - } - } -} - -template -void IntermediateValues::internalExportAnnualValues(SurveyResults& report, - const A& array, - bool annual) const -{ - using namespace Yuni; - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - // Caption - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] = nullptr; - // Precision - report.precision[report.data.columnIndex] = PrecisionToPrintfFormat::Value(); - // Non applicability - report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; - - // Values - if (not annual) - { - (void)::memcpy(report.values[report.data.columnIndex], array, sizeof(double) * Size); - } - else - { - double& target = *(report.values[report.data.columnIndex]); - target = year; - } - - // Next column index - ++report.data.columnIndex; -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_INTERMEDIATE_HXX__ diff --git a/src/solver/variable/storage/minmax-data.cpp b/src/solver/variable/storage/minmax-data.cpp index 43ee735ea1..ea59610820 100644 --- a/src/solver/variable/storage/minmax-data.cpp +++ b/src/solver/variable/storage/minmax-data.cpp @@ -1,158 +1,60 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include "intermediate.h" -#include "minmax-data.h" -#include +#include "antares/solver/variable/storage/minmax-data.h" -using namespace Yuni; +#include "antares/solver/variable/storage/intermediate.h" namespace Antares::Solver::Variable::R::AllYears { -namespace // anonymous -{ -double eps = 1.e-7; +constexpr double eps = 1.e-7; -template -struct ArrayInitializer +static void initArray(bool opInferior, std::vector& array) { - static void Init(Antares::Memory::Array& array) + for (auto& data: array) { - for (uint i = 0; i != Size; ++i) - { - MinMaxData::Data& data = array[i]; - data.value = DBL_MAX; // +inf - data.indice = (uint32_t)(-1); // invalid indice - } + data.value = opInferior ? DBL_MAX : -DBL_MAX; // +inf or -inf + data.indice = (uint32_t)(-1); // invalid indice } +} - static void Init(MinMaxData::Data* array) - { - for (uint i = 0; i != Size; ++i) - { - MinMaxData::Data& data = array[i]; - data.value = DBL_MAX; // +inf - data.indice = (uint32_t)(-1); // invalid indice - } - } - -}; // class ArrayInitializer - -template -struct ArrayInitializer +static void mergeArray(bool opInferior, + unsigned year, + std::vector& results, + const double* values) { - static void Init(Antares::Memory::Array& array) - { - for (uint i = 0; i != Size; ++i) - { - // Contrary to what we could guess, DBL_MIN is not the smallest number - // you can hold in a double, but the smallest positive number you can - // hold in a double - MinMaxData::Data& data = array[i]; - data.value = -DBL_MAX; // -inf - data.indice = (uint32_t)(-1); // invalid indice - } - } - - static void Init(MinMaxData::Data* array) + for (unsigned i = 0; i != results.size(); ++i) { - for (uint i = 0; i != Size; ++i) - { - // Contrary to what we could guess, DBL_MIN is not the smallest number - // you can hold in a double, but the smallest positive number you can - // hold in a double - MinMaxData::Data& data = array[i]; - data.value = -DBL_MAX; // -inf - data.indice = (uint32_t)(-1); // invalid indice - } - } + MinMaxData::Data& data = results[i]; -}; // class ArrayInitializer - -template -struct MergeArray -{ - template - static void Do(const uint year, - Antares::Memory::Array& results, - const U& values) - { - for (uint i = 0; i != Size; ++i) + if (opInferior) { - MinMaxData::Data& data = results[i]; if (values[i] < data.value - eps) { data.value = values[i]; data.indice = year + 1; // The year is zero-based } } - } - - template - static void Do(const uint year, MinMaxData::Data* results, const U& values) - { - for (uint i = 0; i != Size; ++i) - { - if (values[i] < results[i].value - eps) - { - results[i].value = values[i]; - results[i].indice = year + 1; // The year is zero-based - } - } - } - -}; // class MergeArray - -template -struct MergeArray<0, Size> -{ - template - static void Do(const uint year, - Antares::Memory::Array& results, - const U& values) - { - for (uint i = 0; i != Size; ++i) - { - MinMaxData::Data& data = results[i]; - if (values[i] > data.value + eps) - { - data.value = values[i]; - data.indice = year + 1; // The year is zero-based - } - } - } - - template - static void Do(const uint year, MinMaxData::Data* results, const U& values) - { - for (uint i = 0; i != Size; ++i) + else { - MinMaxData::Data& data = results[i]; if (values[i] > data.value + eps) { data.value = values[i]; @@ -160,63 +62,42 @@ struct MergeArray<0, Size> } } } - -}; // class MergeArray - -} // anonymous namespace - -MinMaxData::MinMaxData() : hourly(nullptr) -{ -} - -MinMaxData::~MinMaxData() -{ - Antares::Memory::Release(hourly); } void MinMaxData::resetInf() { - ArrayInitializer<1, true>::Init(&annual); - ArrayInitializer::Init(monthly); - ArrayInitializer::Init(weekly); - ArrayInitializer::Init(daily); - ArrayInitializer::Init(hourly); + initArray(true, annual); + initArray(true, monthly); + initArray(true, weekly); + initArray(true, daily); + initArray(true, hourly); } void MinMaxData::resetSup() { - ArrayInitializer<1, false>::Init(&annual); - ArrayInitializer::Init(monthly); - ArrayInitializer::Init(weekly); - ArrayInitializer::Init(daily); - ArrayInitializer::Init(hourly); -} - -void MinMaxData::initialize() -{ - Antares::Memory::Allocate(hourly, maxHoursInAYear); + initArray(false, annual); + initArray(false, monthly); + initArray(false, weekly); + initArray(false, daily); + initArray(false, hourly); } void MinMaxData::mergeInf(uint year, const IntermediateValues& rhs) { - MergeArray::Do(year, monthly, rhs.month); - MergeArray::Do(year, weekly, rhs.week); - MergeArray::Do(year, daily, rhs.day); - MergeArray::Do(year, hourly, rhs.hour); - MergeArray::Do(year, &annual, &rhs.year); + mergeArray(true, year, monthly, rhs.month); + mergeArray(true, year, weekly, rhs.week); + mergeArray(true, year, daily, rhs.day); + mergeArray(true, year, hourly, rhs.hour); + mergeArray(true, year, annual, &rhs.year); } void MinMaxData::mergeSup(uint year, const IntermediateValues& rhs) { - MergeArray::Do(year, monthly, rhs.month); - MergeArray::Do(year, weekly, rhs.week); - MergeArray::Do(year, daily, rhs.day); - MergeArray::Do(year, hourly, rhs.hour); - MergeArray::Do(year, &annual, &rhs.year); + mergeArray(false, year, monthly, rhs.month); + mergeArray(false, year, weekly, rhs.week); + mergeArray(false, year, daily, rhs.day); + mergeArray(false, year, hourly, rhs.hour); + mergeArray(false, year, annual, &rhs.year); } } // namespace Antares::Solver::Variable::R::AllYears - - - - diff --git a/src/solver/variable/storage/minmax-data.h b/src/solver/variable/storage/minmax-data.h deleted file mode 100644 index 0a1175b6d6..0000000000 --- a/src/solver/variable/storage/minmax-data.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_MINMAX_DATA_H__ -#define __SOLVER_VARIABLE_STORAGE_MINMAX_DATA_H__ - -#include -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -class MinMaxData -{ -public: - struct Data - { - double value; - uint32_t indice; - }; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - MinMaxData(); - //! Destructor - ~MinMaxData(); - - void initialize(); - - void resetInf(); - void resetSup(); - - void mergeInf(uint year, const IntermediateValues& rhs); - void mergeSup(uint year, const IntermediateValues& rhs); - -public: - Data annual; - Data monthly[maxMonths]; - Data weekly[maxWeeksInAYear]; - Data daily[maxDaysInAYear]; - Antares::Memory::Stored::Type hourly; - -}; // class MinMaxData - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_MINMAX_DATA_H__ diff --git a/src/solver/variable/storage/minmax.h b/src/solver/variable/storage/minmax.h deleted file mode 100644 index 20ef4b9051..0000000000 --- a/src/solver/variable/storage/minmax.h +++ /dev/null @@ -1,217 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_MINMAX_H__ -#define __SOLVER_VARIABLE_STORAGE_MINMAX_H__ - -#include "minmax-data.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -template -class Min; -template -class Max; - -template -struct MinMaxBase : public NextT -{ -public: - //! Type of the net item in the list - typedef NextT NextType; - - enum - { - //! The count if item in the list - count = 1 + NextT::count, - - categoryFile = NextT::categoryFile | Variable::Category::allFile, - }; - - //! Name of the filter - static const char* Name() - { - return "minmaxbase"; - } - -public: - MinMaxBase() - { - } - - ~MinMaxBase() - { - } - -protected: - void initializeFromStudy(Data::Study& study); - - template - void buildSurveyReport(SurveyResults& report, - const S& results, - int dataLevel, - int fileLevel, - int precision) const - { - if (fileLevel & Category::id) - { - switch (precision) - { - case Category::hourly: - InternalExportIndices( - report, Memory::RawPointer(minmax.hourly), fileLevel); - break; - case Category::daily: - InternalExportIndices(report, minmax.daily, fileLevel); - break; - case Category::weekly: - InternalExportIndices(report, minmax.weekly, fileLevel); - break; - case Category::monthly: - InternalExportIndices(report, minmax.monthly, fileLevel); - break; - case Category::annual: - InternalExportIndices<1, VCardT>(report, &minmax.annual, fileLevel); - break; - } - } - else - { - switch (precision) - { - case Category::hourly: - InternalExportValues(report, - Memory::RawPointer(minmax.hourly)); - break; - case Category::daily: - InternalExportValues(report, minmax.daily); - break; - case Category::weekly: - InternalExportValues(report, minmax.weekly); - break; - case Category::monthly: - InternalExportValues(report, minmax.monthly); - break; - case Category::annual: - InternalExportValues<1, VCardT>(report, &minmax.annual); - break; - } - } - // Next - NextType::template buildSurveyReport( - report, results, dataLevel, fileLevel, precision); - } - - void reset(); - - void merge(uint year, const IntermediateValues& rhs); - - uint64_t memoryUsage() const - { - return sizeof(double) * maxHoursInAYear + NextType::memoryUsage(); - } - - template class DecoratorT> - Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const - { - return NextType::template hourlyValuesForSpatialAggregate(); - } - -protected: - MinMaxData minmax; - -private: - template - static void InternalExportIndices(SurveyResults& report, - const MinMaxData::Data* array, - int fileLevel); - - template - static void InternalExportValues(SurveyResults& report, const MinMaxData::Data* array); - -}; // class MinMaxBase - -template -class Min : public MinMaxBase -{ -public: - //! Implementation - typedef MinMaxBase MinMaxImplementationType; - //! Type of the net item in the list - typedef NextT NextType; - -public: - //! Name of the filter - static const char* Name() - { - return "min"; - } - enum - { - //! The count if item in the list - count = MinMaxImplementationType::count, - }; -}; - -template -class Max : public MinMaxBase -{ -public: - //! Implementation - typedef MinMaxBase MinMaxImplementationType; - //! Type of the net item in the list - typedef NextT NextType; - -public: - //! Name of the filter - static const char* Name() - { - return "max"; - } - enum - { - //! The count if item in the list - count = MinMaxImplementationType::count, - }; -}; - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#include "minmax.hxx" - -#endif // __SOLVER_VARIABLE_STORAGE_MINMAX_H__ diff --git a/src/solver/variable/storage/raw.h b/src/solver/variable/storage/raw.h deleted file mode 100644 index 39d8bffc25..0000000000 --- a/src/solver/variable/storage/raw.h +++ /dev/null @@ -1,245 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_RAW_H__ -#define __SOLVER_VARIABLE_STORAGE_RAW_H__ - -#include -#include -#include "rawdata.h" -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -template -struct Raw : public NextT -{ -public: - //! Type of the net item in the list - typedef NextT NextType; - - enum - { - //! The count if item in the list - count = 1 + NextT::count, - - categoryFile = NextT::categoryFile | Variable::Category::allFile, - }; - - struct Data - { - double value; - uint32_t indice; - }; - - //! Name of the filter - static const char* Name() - { - return "raw"; - } - -public: - Raw() - { - } - - ~Raw() - { - } - -protected: - void initializeFromStudy(Antares::Data::Study& study); - - inline void reset() - { - rawdata.reset(); - // Next - NextType::reset(); - } - - inline void merge(uint year, const IntermediateValues& rhs) - { - rawdata.merge(year, rhs); - // Next - NextType::merge(year, rhs); - } - - template - void buildSurveyReport(SurveyResults& report, - const S& results, - int dataLevel, - int fileLevel, - int precision) const - { - if (fileLevel & FileFilter && !(fileLevel & Category::id)) - { - switch (precision) - { - case Category::hourly: - InternalExportValues( - report, ::Antares::Memory::RawPointer(rawdata.hourly)); - break; - case Category::daily: - InternalExportValues(report, - rawdata.daily); - break; - case Category::weekly: - InternalExportValues(report, - rawdata.weekly); - break; - case Category::monthly: - InternalExportValues(report, - rawdata.monthly); - break; - case Category::annual: - InternalExportValues(report, rawdata.year); - break; - } - } - // Next - NextType::template buildSurveyReport( - report, results, dataLevel, fileLevel, precision); - } - - template - void buildDigest(SurveyResults& report, int digestLevel, int dataLevel) const - { - if ((dataLevel & Category::area || dataLevel & Category::setOfAreas) - && digestLevel & Category::digestAllYears) - { - assert(report.data.columnIndex < report.maxVariables - && "Column index out of bounds"); - - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] = "values"; - - // Precision - report.precision[report.data.columnIndex] - = PrecisionToPrintfFormat::Value(); - // Value - report.values[report.data.columnIndex][report.data.rowIndex] = rawdata.allYears; - // Non applicability - report.digestNonApplicableStatus[report.data.rowIndex][report.data.columnIndex] - = *report.isCurrentVarNA; - - ++(report.data.columnIndex); - } - // Next - NextType::template buildDigest(report, digestLevel, dataLevel); - } - - uint64_t memoryUsage() const - { - return +sizeof(double) * maxHoursInAYear + NextType::memoryUsage(); - } - - template class DecoratorT> - Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const - { - if (Yuni::Static::Type::StrictlyEqual, Raw>::Yes) - return rawdata.hourly; - return NextType::template hourlyValuesForSpatialAggregate(); - } - -public: - RawData rawdata; - -private: - template - void InternalExportValues(SurveyResults& report, const double* array) const - { - assert(array); - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - // Caption - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] = "values"; - // Precision - report.precision[report.data.columnIndex] - = Solver::Variable::PrecisionToPrintfFormat::Value(); - // Non applicability - report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; - - // Values - if (PrecisionT == Category::annual) - { - rawdata.allYears = 0.; - for (uint i = 0; i != rawdata.nbYearsCapacity; ++i) - rawdata.allYears += array[i]; - *(report.values[report.data.columnIndex]) = rawdata.allYears; - } - else - (void)::memcpy(report.values[report.data.columnIndex], array, sizeof(double) * Size); - - // Next column index - ++report.data.columnIndex; - } - - template - void InternalExportValuesMC(int precision, SurveyResults& report, const double* array) const - { - if (not(precision & Category::annual)) - return; - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - // Caption - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] = "values"; - // Precision - report.precision[report.data.columnIndex] - = Solver::Variable::PrecisionToPrintfFormat::Value(); - // Non applicability - report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; - - (void)::memcpy( - report.data.matrix[report.data.columnIndex], array, report.data.nbYears * sizeof(double)); - - // Next column index - ++report.data.columnIndex; - } - -}; // class Raw - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#include "raw.hxx" - -#endif // __SOLVER_VARIABLE_STORAGE_RAW_H__ diff --git a/src/solver/variable/storage/raw.hxx b/src/solver/variable/storage/raw.hxx deleted file mode 100644 index eba2cf7a48..0000000000 --- a/src/solver/variable/storage/raw.hxx +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_RAW_HXX__ -#define __SOLVER_VARIABLE_STORAGE_RAW_HXX__ - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -template -inline void Raw::initializeFromStudy(Antares::Data::Study& study) -{ - rawdata.initializeFromStudy(study); - // Next - NextType::initializeFromStudy(study); -} - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_RAW_HXX__ diff --git a/src/solver/variable/storage/rawdata.cpp b/src/solver/variable/storage/rawdata.cpp index df5c55118a..4baf8531bd 100644 --- a/src/solver/variable/storage/rawdata.cpp +++ b/src/solver/variable/storage/rawdata.cpp @@ -1,46 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/variable/storage/rawdata.h" + #include -#include "rawdata.h" using namespace Yuni; -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears +namespace Antares::Solver::Variable::R::AllYears { -RawData::RawData() : hourly(nullptr), year(nullptr), allYears(0.) +RawData::RawData(): + hourly(nullptr), + year(nullptr), + allYears(0.) { } @@ -52,7 +42,7 @@ RawData::~RawData() void RawData::initializeFromStudy(const Data::Study& study) { - Antares::Memory::Allocate(hourly, maxHoursInAYear); + Antares::Memory::Allocate(hourly, HOURS_PER_YEAR); nbYearsCapacity = study.runtime->rangeLimits.year[Data::rangeEnd] + 1; year = new double[nbYearsCapacity]; } @@ -60,10 +50,10 @@ void RawData::initializeFromStudy(const Data::Study& study) void RawData::reset() { // Reset - Antares::Memory::Zero(maxHoursInAYear, hourly); - (void)::memset(monthly, 0, sizeof(double) * maxMonths); - (void)::memset(weekly, 0, sizeof(double) * maxWeeksInAYear); - (void)::memset(daily, 0, sizeof(double) * maxDaysInAYear); + Antares::Memory::Zero(HOURS_PER_YEAR, hourly); + (void)::memset(monthly, 0, sizeof(double) * MONTHS_PER_YEAR); + (void)::memset(weekly, 0, sizeof(double) * WEEKS_PER_YEAR); + (void)::memset(daily, 0, sizeof(double) * DAYS_PER_YEAR); (void)::memset(year, 0, sizeof(double) * nbYearsCapacity); } @@ -71,23 +61,27 @@ void RawData::merge(unsigned int y, const IntermediateValues& rhs) { unsigned int i; // StdDeviation value for each hour throughout all years - for (i = 0; i != maxHoursInAYear; ++i) + for (i = 0; i != HOURS_PER_YEAR; ++i) + { hourly[i] += rhs.hour[i]; + } // StdDeviation value for each day throughout all years - for (i = 0; i != maxDaysInAYear; ++i) + for (i = 0; i != DAYS_PER_YEAR; ++i) + { daily[i] += rhs.day[i]; + } // StdDeviation value for each week throughout all years - for (i = 0; i != maxWeeksInAYear; ++i) + for (i = 0; i != WEEKS_PER_YEAR; ++i) + { weekly[i] += rhs.week[i]; + } // StdDeviation value for each month throughout all years - for (i = 0; i != maxMonths; ++i) + for (i = 0; i != MONTHS_PER_YEAR; ++i) + { monthly[i] += rhs.month[i]; + } // StdDeviation value throughout all years year[y] += rhs.year; } -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver::Variable::R::AllYears diff --git a/src/solver/variable/storage/rawdata.h b/src/solver/variable/storage/rawdata.h deleted file mode 100644 index 8601cdc432..0000000000 --- a/src/solver/variable/storage/rawdata.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_RAWDATA_H__ -#define __SOLVER_VARIABLE_STORAGE_RAWDATA_H__ - -#include -#include -#include "intermediate.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -class RawData -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - */ - RawData(); - //! Destructor - ~RawData(); - //@} - -public: - void initializeFromStudy(const Data::Study& study); - void reset(); - void merge(unsigned int year, const IntermediateValues& rhs); - -public: - double monthly[maxMonths]; - double weekly[maxWeeksInAYear]; - double daily[maxDaysInAYear]; - Antares::Memory::Stored::Type hourly; - double* year; - mutable double allYears; - unsigned int nbYearsCapacity; - -}; // class RawData - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_RAWDATA_H__ diff --git a/src/solver/variable/storage/results.hxx b/src/solver/variable/storage/results.hxx deleted file mode 100644 index c35c606fc9..0000000000 --- a/src/solver/variable/storage/results.hxx +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_RESULTS_HXX__ -#define __SOLVER_VARIABLE_STORAGE_RESULTS_HXX__ - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -template class DecoratorForSpatialAggregateT> -inline void Results::initializeFromStudy( - Antares::Data::Study& study) -{ - DecoratorType::initializeFromStudy(study); -} - -template class DecoratorForSpatialAggregateT> -template -inline void Results::buildSurveyReport( - SurveyResults& report, - const S& results, - int dataLevel, - int fileLevel, - int precision) const -{ - // Ask to fullfil the report to the first decorator - DecoratorType::template buildSurveyReport( - report, results, dataLevel, fileLevel, precision); -} - -template class DecoratorForSpatialAggregateT> -inline void Results::merge( - uint year, - const IntermediateValues& data) -{ - DecoratorType::merge(year, data); -} - -template class DecoratorForSpatialAggregateT> -inline void Results::reset() -{ - DecoratorType::reset(); -} - -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_RESULTS_HXX__ diff --git a/src/solver/variable/storage/stdDeviation.h b/src/solver/variable/storage/stdDeviation.h deleted file mode 100644 index 33129b666b..0000000000 --- a/src/solver/variable/storage/stdDeviation.h +++ /dev/null @@ -1,290 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_STORAGE_STD_DEVIATION_H__ -#define __SOLVER_VARIABLE_STORAGE_STD_DEVIATION_H__ - -#include -#include -#include - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace R -{ -namespace AllYears -{ -template -struct StdDeviation : public NextT -{ -public: - //! Type of the net item in the list - typedef NextT NextType; - - enum - { - //! The count if item in the list - count = 1 + NextT::count, - - categoryFile = NextT::categoryFile | Variable::Category::allFile, - }; - - struct Data - { - double value; - uint32_t indice; - }; - - //! Name of the filter - static const char* Name() - { - return "std deviation"; - } - -public: - StdDeviation() - { - using namespace Yuni; - stdDeviationHourly = nullptr; - } - - ~StdDeviation() - { - Antares::Memory::Release(stdDeviationHourly); - } - -protected: - void initializeFromStudy(Antares::Data::Study& study) - { - Antares::Memory::Allocate(stdDeviationHourly, maxHoursInAYear); - // Next - NextType::initializeFromStudy(study); - - yearsWeight = study.parameters.getYearsWeight(); - yearsWeightSum = study.parameters.getYearsWeightSum(); - } - - void reset() - { - // Reset - (void)::memset(stdDeviationMonthly, 0, sizeof(double) * maxMonths); - (void)::memset(stdDeviationWeekly, 0, sizeof(double) * maxWeeksInAYear); - (void)::memset(stdDeviationDaily, 0, sizeof(double) * maxDaysInAYear); - Antares::Memory::Zero(maxHoursInAYear, stdDeviationHourly); - stdDeviationYear = 0.; - // Next - NextType::reset(); - } - - void merge(unsigned int year, const IntermediateValues& rhs) - { - // Ratio take into account MC year weight - double pRatio = (double)yearsWeight[year] / (double)yearsWeightSum; - - unsigned int i; - // StdDeviation value for each hour throughout all years - for (i = 0; i != maxHoursInAYear; ++i) - stdDeviationHourly[i] += rhs.hour[i] * rhs.hour[i] * pRatio; - // StdDeviation value for each day throughout all years - for (i = 0; i != maxDaysInAYear; ++i) - stdDeviationDaily[i] += rhs.day[i] * rhs.day[i] * pRatio; - // StdDeviation value for each week throughout all years - for (i = 0; i != maxWeeksInAYear; ++i) - stdDeviationWeekly[i] += rhs.week[i] * rhs.week[i] * pRatio; - // StdDeviation value for each month throughout all years - for (i = 0; i != maxMonths; ++i) - stdDeviationMonthly[i] += rhs.month[i] * rhs.month[i] * pRatio; - // StdDeviation value throughout all years - stdDeviationYear += rhs.year * rhs.year * pRatio; - - // Next - NextType::merge(year, rhs); - } - - template - void buildSurveyReport(SurveyResults& report, - const S& results, - int dataLevel, - int fileLevel, - int precision) const - { - if (!(fileLevel & Category::id)) - { - switch (precision) - { - case Category::hourly: - InternalExportValues( - report, results, Memory::RawPointer(stdDeviationHourly)); - break; - case Category::daily: - InternalExportValues( - report, results, stdDeviationDaily); - break; - case Category::weekly: - InternalExportValues( - report, results, stdDeviationWeekly); - break; - case Category::monthly: - InternalExportValues( - report, results, stdDeviationMonthly); - break; - case Category::annual: - InternalExportValues( - report, results, &stdDeviationYear); - break; - } - } - // Next - NextType::template buildSurveyReport( - report, results, dataLevel, fileLevel, precision); - } - - uint64_t memoryUsage() const - { - return sizeof(double) * maxHoursInAYear + NextType::memoryUsage(); - } - - template class DecoratorT> - Antares::Memory::Stored::ConstReturnType hourlyValuesForSpatialAggregate() const - { - if (Yuni::Static::Type::StrictlyEqual, StdDeviation>::Yes) - return stdDeviationHourly; - return NextType::template hourlyValuesForSpatialAggregate(); - } - -public: - double stdDeviationMonthly[maxMonths]; - double stdDeviationWeekly[maxWeeksInAYear]; - double stdDeviationDaily[maxDaysInAYear]; - Antares::Memory::Stored::Type stdDeviationHourly; - double stdDeviationYear; - -private: - template - void InternalExportValues(SurveyResults& report, const S& results, const A& array) const - { - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - // Caption - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] = "std"; - - // Precision - report.precision[report.data.columnIndex] - = PrecisionToPrintfFormat::Value(); - - // Non applicability - report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; - - // Values - double* target = report.values[report.data.columnIndex]; - // A mere copy - - switch (PrecisionT) - { - case Category::hourly: - { - for (unsigned int i = 0; i != Size; ++i) - target[i] = Yuni::Math::SquareRoot( - array[i] - results.avgdata.hourly[i] * results.avgdata.hourly[i]); - } - break; - case Category::daily: - { - for (unsigned int i = 0; i != Size; ++i) - target[i] = Yuni::Math::SquareRoot( - array[i] - results.avgdata.daily[i] * results.avgdata.daily[i]); - } - break; - case Category::weekly: - { - for (unsigned int i = 0; i != Size; ++i) - target[i] = Yuni::Math::SquareRoot( - array[i] - results.avgdata.weekly[i] * results.avgdata.weekly[i]); - } - break; - case Category::monthly: - { - for (unsigned int i = 0; i != Size; ++i) - target[i] = Yuni::Math::SquareRoot( - array[i] - results.avgdata.monthly[i] * results.avgdata.monthly[i]); - } - break; - case Category::annual: - { - const double d = *array - results.avgdata.allYears * results.avgdata.allYears; - *target = Yuni::Math::SquareRoot(d); - } - break; - } - - // Next column index - ++report.data.columnIndex; - } - - template - void InternalExportValuesMC(SurveyResults& report, const S& /*results*/, const A& array) const - { - if (not(PrecisionT & Category::annual)) - return; - assert(report.data.columnIndex < report.maxVariables && "Column index out of bounds"); - - // Caption - report.captions[0][report.data.columnIndex] = report.variableCaption; - report.captions[1][report.data.columnIndex] = report.variableUnit; - report.captions[2][report.data.columnIndex] = "std"; - - // Precision - report.precision[report.data.columnIndex] - = PrecisionToPrintfFormat::Value(); - - // Non applicability - report.nonApplicableStatus[report.data.columnIndex] = *report.isCurrentVarNA; - - (void)::memcpy(report.data.matrix[report.data.columnIndex], array, Size * sizeof(double)); - - // Next column index - ++report.data.columnIndex; - } - -private: - std::vector yearsWeight; - float yearsWeightSum; - -}; // class StdDeviation - -} // namespace AllYears -} // namespace R -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_STORAGE_STD_DEVIATION_H__ diff --git a/src/solver/variable/surveyresults.h b/src/solver/variable/surveyresults.h deleted file mode 100644 index 88de69f55e..0000000000 --- a/src/solver/variable/surveyresults.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_SURVEY_RESULTS_H__ -#define __SOLVER_VARIABLE_SURVEY_RESULTS_H__ - -#include "surveyresults/surveyresults.h" - -#endif // __SOLVER_VARIABLE_SURVEY_RESULTS_H__ diff --git a/src/solver/variable/surveyresults/surveyresults.cpp b/src/solver/variable/surveyresults/surveyresults.cpp index 052e7ab383..bb763a1b80 100644 --- a/src/solver/variable/surveyresults/surveyresults.cpp +++ b/src/solver/variable/surveyresults/surveyresults.cpp @@ -1,50 +1,42 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include "antares/solver/variable/surveyresults/surveyresults.h" + #include +#include + #include -#include -#include "surveyresults.h" + #include -#include -#include +#include +#include +#include using namespace Yuni; using namespace Antares; #define SEP IO::Separator -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Private +namespace Antares::Solver::Variable::Private { void InternalExportDigestLinksMatrix(const Data::Study& study, const char* title, @@ -80,11 +72,13 @@ void InternalExportDigestLinksMatrix(const Data::Study& study, else { v = matrix[x][y]; - if (Math::NaN(v)) + if (std::isnan(v)) + { buffer.append("\t--"); + } else { - if (Math::Zero(v)) + if (Utils::isZero(v)) { buffer.append("\t0"); } @@ -93,16 +87,24 @@ void InternalExportDigestLinksMatrix(const Data::Study& study, // The snprintf routine is required since we may not have the ending zero // with the standard printf. The conversion may require a bigger buffer. #ifdef YUNI_OS_MSVC - sizePrintf = ::sprintf_s( - conversionBuffer + 1, sizeof(conversionBuffer) - 2, "%.0f", v); + sizePrintf = ::sprintf_s(conversionBuffer + 1, + sizeof(conversionBuffer) - 2, + "%.0f", + v); #else - sizePrintf = ::snprintf( - conversionBuffer + 1, sizeof(conversionBuffer) - 2, "%.0f", v); + sizePrintf = ::snprintf(conversionBuffer + 1, + sizeof(conversionBuffer) - 2, + "%.0f", + v); #endif if (sizePrintf >= 0) + { buffer.append((const char*)conversionBuffer); + } else + { buffer.append("\tERR"); + } } } } @@ -125,43 +127,45 @@ static void ExportGridInfosAreas(const Data::Study& study, "min stable power\tmin up/down time\tspinning\tco2\t" "marginal cost\tfixed cost\tstartup cost\tmarket bid cost\tspread cost\n"; - study.areas.each([&](const Data::Area& area) { - out << area.id << '\t'; - out << area.name << '\n'; - - // Areas - { - auto end = area.links.end(); - for (auto i = area.links.begin(); i != end; ++i) - outLinks << area.id << '\t' << i->second->with->id << '\n'; - } - - // Thermal clusters - for (uint i = 0; i != area.thermal.clusterCount(); ++i) - { - assert(NULL != area.thermal.clusters[i]); - auto& cluster = *(area.thermal.clusters[i]); - - outThermal << area.id << '\t'; - outThermal << cluster.id() << '\t'; - outThermal << cluster.name() << '\t'; - outThermal << Data::ThermalCluster::GroupName(cluster.groupID) << '\t'; - outThermal << cluster.unitCount << '\t'; - outThermal << cluster.nominalCapacity << '\t'; - outThermal << cluster.minStablePower << '\t'; - outThermal << cluster.minUpTime << '\t'; - outThermal << cluster.minDownTime << '\t'; - outThermal << cluster.spinning << '\t'; - outThermal << cluster.emissions.factors[Antares::Data::Pollutant::CO2] << '\t'; - outThermal << cluster.marginalCost << '\t'; - outThermal << cluster.fixedCost << '\t'; - outThermal << cluster.startupCost << '\t'; - outThermal << cluster.marketBidCost << '\t'; - outThermal << cluster.spreadCost << '\n'; - - } // each thermal cluster - }); // each area - auto add = [&writer, &originalOutput](const YString& filename, Clob&& buffer) { + study.areas.each( + [&out, &outLinks, &outThermal](const Data::Area& area) + { + out << area.id << '\t'; + out << area.name << '\n'; + + // Areas + { + auto end = area.links.end(); + for (auto i = area.links.begin(); i != end; ++i) + { + outLinks << area.id << '\t' << i->second->with->id << '\n'; + } + } + + // Thermal clusters + for (auto& cluster: area.thermal.list.each_enabled()) + { + outThermal << area.id << '\t'; + outThermal << cluster->id() << '\t'; + outThermal << cluster->name() << '\t'; + outThermal << Data::ThermalCluster::GroupName(cluster->groupID) << '\t'; + outThermal << cluster->unitCount << '\t'; + outThermal << cluster->nominalCapacity << '\t'; + outThermal << cluster->minStablePower << '\t'; + outThermal << cluster->minUpTime << '\t'; + outThermal << cluster->minDownTime << '\t'; + outThermal << cluster->spinning << '\t'; + outThermal << cluster->emissions.factors[Antares::Data::Pollutant::CO2] << '\t'; + outThermal << cluster->marginalCost << '\t'; + outThermal << cluster->fixedCost << '\t'; + outThermal << cluster->startupCost << '\t'; + outThermal << cluster->marketBidCost << '\t'; + outThermal << cluster->spreadCost << '\n'; + + } // each thermal cluster + }); // each area + auto add = [&writer, &originalOutput](const YString& filename, Clob&& buffer) + { YString path; path << originalOutput << SEP << "grid" << SEP << filename; writer.addEntryFromBuffer(path.c_str(), buffer); @@ -172,16 +176,16 @@ static void ExportGridInfosAreas(const Data::Study& study, add("thermal.txt", std::move(outThermal)); } -SurveyResultsData::SurveyResultsData(const Data::Study& s, const String& o) : - columnIndex((uint)-1), - thermalCluster(nullptr), - area(nullptr), - link(nullptr), - setOfAreasIndex((uint)-1), - study(s), - nbYears(s.parameters.nbYears), - effectiveNbYears(s.parameters.effectiveNbYears), - originalOutput(o) +SurveyResultsData::SurveyResultsData(const Data::Study& s, const String& o): + columnIndex((uint)-1), + thermalCluster(nullptr), + area(nullptr), + link(nullptr), + setOfAreasIndex((uint)-1), + study(s), + nbYears(s.parameters.nbYears), + effectiveNbYears(s.parameters.effectiveNbYears), + originalOutput(o) { } @@ -197,23 +201,17 @@ void SurveyResultsData::initialize(uint maxVariables) switch (study.parameters.mode) { - case Data::stdmEconomy: + case Data::SimulationMode::Adequacy: + case Data::SimulationMode::Economy: + case Data::SimulationMode::Expansion: { matrix.resize(study.areas.size(), study.areas.size()); // The initialization will be done later //::MatrixFill(&matrix, std::numeric_limits::quiet_NaN()); break; } - case Data::stdmAdequacy: - { - matrix.resize(study.areas.size(), study.areas.size()); - // The initialization will be done later - //::MatrixFill(&matrix, std::numeric_limits::quiet_NaN()); - break; - } - case Data::stdmUnknown: - case Data::stdmExpansion: - case Data::stdmMax: + + case Data::SimulationMode::Unknown: break; } } @@ -223,10 +221,7 @@ void SurveyResultsData::exportGridInfos(IResultWriter& writer) output.clear(); Solver::Variable::Private::ExportGridInfosAreas(study, originalOutput, writer); } -} // namespace Private -} // namespace Variable -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver::Variable::Private namespace Antares { @@ -234,9 +229,7 @@ namespace Solver { namespace Variable { -static inline uint GetRangeLimit(const Data::Study& study, - int precisionLevel, - int index) +static inline uint GetRangeLimit(const Data::Study& study, int precisionLevel, int index) { assert(study.runtime && "invalid runtime data"); switch (precisionLevel) @@ -271,15 +264,23 @@ inline void SurveyResults::writeDateToFileDescriptor(uint row, int precisionLeve out << '\t' << row << '\t'; uint d = 1 + hourinfo.dayMonth; // 1 + h.day; if (d < 10) + { out << '0' << d; + } else + { out << d; + } out << '\t'; out << calendar.text.months[hourinfo.month].shortUpperName << '\t'; if (hourinfo.dayHour < 10) + { out << '0' << (uint)hourinfo.dayHour; + } else + { out << (uint)hourinfo.dayHour; + } out.append(":00", 3); break; } @@ -292,9 +293,13 @@ inline void SurveyResults::writeDateToFileDescriptor(uint row, int precisionLeve out << '\t'; uint dp1 = 1 + dayinfo.dayMonth; if (dp1 < 10) + { out << '0' << dp1; + } else + { out << dp1; + } out << '\t' << calendar.text.months[dayinfo.month].shortUpperName; break; } @@ -302,18 +307,26 @@ inline void SurveyResults::writeDateToFileDescriptor(uint row, int precisionLeve { out << '\t'; if (row - 1 < calendar.maxWeeksInYear) + { out << calendar.weeks[row - 1].userweek; + } else + { out << '?'; + } break; } case Category::monthly: { assert(row - 1 < 12); if (row - 1 < 12) + { out << '\t' << row << '\t' << calendar.text.months[row - 1].shortUpperName; + } else + { out.append("\t\t", 2); + } break; } case Category::annual: @@ -339,34 +352,42 @@ inline void SurveyResults::AppendDoubleValue(uint& error, return; } - if (not Math::Zero(v)) + if (!Utils::isZero(v)) { - if (Math::NaN(v)) + if (std::isnan(v)) { buffer.append("\tNaN", 4); if (++error == 1) { // We should disabled errors on NaN if the quadratic optimization has failed if (not data.study.runtime->quadraticOptimizationHasFailed) + { logs.error() << "'NaN' value detected"; + } } } else { - if (Math::Infinite(v)) + if (std::isinf(v)) { buffer.append((v > 0) ? "\t+inf" : "\t-inf", 5); if (++error == 1) + { logs.error() << "'infinite' value detected"; + } } else { #ifdef YUNI_OS_MSVC - int sizePrintf = ::sprintf_s( - conversionBuffer + 1, sizeof(conversionBuffer) - 2, precision.c_str(), v); + int sizePrintf = ::sprintf_s(conversionBuffer + 1, + sizeof(conversionBuffer) - 2, + precision.c_str(), + v); #else - int sizePrintf = ::snprintf( - conversionBuffer + 1, sizeof(conversionBuffer) - 2, precision.c_str(), v); + int sizePrintf = ::snprintf(conversionBuffer + 1, + sizeof(conversionBuffer) - 2, + precision.c_str(), + v); #endif if (sizePrintf >= 0) @@ -376,12 +397,16 @@ inline void SurveyResults::AppendDoubleValue(uint& error, buffer.append((const char*)conversionBuffer, 1 + sizePrintf); } else + { buffer += "\tERR"; + } } } } else + { buffer.append("\t0", 2); + } } /*! @@ -484,19 +509,19 @@ static inline void WriteIndexHeaderToFileDescriptor(int precisionLevel, assert(Row < SurveyResults::captionCount); for (uint x = 0; x != columnIndex; ++x) + { s << '\t' << captions[Row][x]; + } s += '\n'; } -SurveyResults::SurveyResults(const Data::Study& s, - const String& o, - IResultWriter& writer) : - data(s, o), - yearByYearResults(false), - isCurrentVarNA(nullptr), - isPrinted(nullptr), - pResultWriter(writer) -{ +SurveyResults::SurveyResults(const Data::Study& s, const String& o, IResultWriter& writer): + data(s, o), + yearByYearResults(false), + isCurrentVarNA(nullptr), + isPrinted(nullptr), + pResultWriter(writer) +{ variableCaption.reserve(10); maxVariables = s.parameters.variablesPrintInfo.getTotalMaxColumnsCount(); @@ -509,23 +534,29 @@ SurveyResults::SurveyResults(const Data::Study& s, values = new ValueType[maxVariables]; for (uint i = 0; i != maxVariables; ++i) { - values[i] = new double[maxHoursInAYear]; - memset(values[i], 0, sizeof(double) * maxHoursInAYear); + values[i] = new double[HOURS_PER_YEAR]; + memset(values[i], 0, sizeof(double) * HOURS_PER_YEAR); } // captions for (uint i = 0; i != captionCount; ++i) + { captions[i] = new CaptionType[maxVariables]; + } // precision precision = new PrecisionType[maxVariables]; for (uint i = 0; i != maxVariables; ++i) + { precision[i] = PrecisionToPrintfFormat<0>::Value(); + } // non applicable status nonApplicableStatus = new bool[maxVariables]; for (uint i = 0; i != maxVariables; ++i) + { nonApplicableStatus[i] = false; + } uint nbAreas = s.areas.size(); uint nbSetsOfAreas = s.areas.size(); @@ -535,7 +566,9 @@ SurveyResults::SurveyResults(const Data::Study& s, { digestNonApplicableStatus[i] = new bool[maxVariables]; for (uint v = 0; v < maxVariables; v++) + { digestNonApplicableStatus[i][v] = false; + } } } @@ -544,23 +577,31 @@ SurveyResults::~SurveyResults() if (values) { for (uint i = 0; i != maxVariables; ++i) + { delete[] values[i]; + } delete[] values; } for (uint i = 0; i != captionCount; ++i) + { delete[] captions[i]; + } delete[] precision; delete[] nonApplicableStatus; for (uint i = 0; i < digestSize; i++) + { delete[] digestNonApplicableStatus[i]; + } delete[] digestNonApplicableStatus; } void SurveyResults::resetValuesAtLine(uint j) { for (uint i = 0; i < maxVariables; i++) + { values[i][j] = 0.; + } } void SurveyResults::exportDigestAllYears(std::string& buffer) @@ -598,7 +639,7 @@ void SurveyResults::exportDigestAllYears(std::string& buffer) for (auto j = data.rowCaptions.begin(); j != end; ++j, ++y) { // asserts - assert(y < maxHoursInAYear); + assert(y < HOURS_PER_YEAR); buffer.append("\t").append(j->c_str()); @@ -606,7 +647,7 @@ void SurveyResults::exportDigestAllYears(std::string& buffer) for (uint i = 0; i != data.columnIndex; ++i) { assert(i < maxVariables && "i greater can not be greater than maxVariables"); - assert(y < maxHoursInAYear && "y can not be greater than maxHoursInAYear"); + assert(y < HOURS_PER_YEAR && "y can not be greater than HOURS_PER_YEAR"); if (digestNonApplicableStatus[y][i]) { @@ -614,7 +655,7 @@ void SurveyResults::exportDigestAllYears(std::string& buffer) continue; } - if (Math::Zero(values[i][y])) + if (Utils::isZero(values[i][y])) { buffer.append("\t0"); } @@ -634,9 +675,13 @@ void SurveyResults::exportDigestAllYears(std::string& buffer) values[i][y]); #endif if (sizePrintf >= 0) + { buffer.append((const char*)conversionBuffer); + } else + { buffer.append("\tERR"); + } } } @@ -666,9 +711,13 @@ void SurveyResults::saveToFile(int dataLevel, int fileLevel, int precisionLevel) // Big header if (data.area) + { data.fileBuffer << data.area->name; + } else + { data.fileBuffer << "system"; + } data.fileBuffer << '\t'; Category::DataLevelToStream(data.fileBuffer, dataLevel); @@ -679,7 +728,9 @@ void SurveyResults::saveToFile(int dataLevel, int fileLevel, int precisionLevel) data.fileBuffer << '\n'; if (data.link) + { data.fileBuffer << data.link->with->name; + } data.fileBuffer << "\tVARIABLES\tBEGIN\tEND\n"; data.fileBuffer << '\t' << data.columnIndex << '\t' << (heightBegin + 1) << '\t' << heightEnd << '\n'; @@ -690,21 +741,39 @@ void SurveyResults::saveToFile(int dataLevel, int fileLevel, int precisionLevel) if (data.area) { auto& areaname = data.area->name; - WriteIndexHeaderToFileDescriptor<0>( - precisionLevel, data.fileBuffer, areaname, captions, data.columnIndex); - WriteIndexHeaderToFileDescriptor<1>( - precisionLevel, data.fileBuffer, areaname, captions, data.columnIndex); - WriteIndexHeaderToFileDescriptor<2>( - precisionLevel, data.fileBuffer, areaname, captions, data.columnIndex); + WriteIndexHeaderToFileDescriptor<0>(precisionLevel, + data.fileBuffer, + areaname, + captions, + data.columnIndex); + WriteIndexHeaderToFileDescriptor<1>(precisionLevel, + data.fileBuffer, + areaname, + captions, + data.columnIndex); + WriteIndexHeaderToFileDescriptor<2>(precisionLevel, + data.fileBuffer, + areaname, + captions, + data.columnIndex); } else { - WriteIndexHeaderToFileDescriptor<0>( - precisionLevel, data.fileBuffer, "system", captions, data.columnIndex); - WriteIndexHeaderToFileDescriptor<1>( - precisionLevel, data.fileBuffer, "system", captions, data.columnIndex); - WriteIndexHeaderToFileDescriptor<2>( - precisionLevel, data.fileBuffer, "system", captions, data.columnIndex); + WriteIndexHeaderToFileDescriptor<0>(precisionLevel, + data.fileBuffer, + "system", + captions, + data.columnIndex); + WriteIndexHeaderToFileDescriptor<1>(precisionLevel, + data.fileBuffer, + "system", + captions, + data.columnIndex); + WriteIndexHeaderToFileDescriptor<2>(precisionLevel, + data.fileBuffer, + "system", + captions, + data.columnIndex); } char conversionBuffer[256]; @@ -714,14 +783,16 @@ void SurveyResults::saveToFile(int dataLevel, int fileLevel, int precisionLevel) #ifndef NDEBUG // A few preliminary checks for (uint x = 0; x != data.columnIndex; ++x) + { assert(not precision[x].empty() && "invalid precision"); + } #endif // Each row for (uint y = heightBegin; y < heightEnd; ++y) { // Asserts - assert(y < maxHoursInAYear); + assert(y < HOURS_PER_YEAR); // Index writeDateToFileDescriptor(y + 1, precisionLevel); @@ -729,12 +800,14 @@ void SurveyResults::saveToFile(int dataLevel, int fileLevel, int precisionLevel) assert(data.columnIndex <= maxVariables); for (uint x = 0; x != data.columnIndex; ++x) + { AppendDoubleValue(error, - values[x][y], - data.fileBuffer, - conversionBuffer, - precision[x], - nonApplicableStatus[x]); + values[x][y], + data.fileBuffer, + conversionBuffer, + precision[x], + nonApplicableStatus[x]); + } // End of line data.fileBuffer += '\n'; diff --git a/src/solver/variable/surveyresults/surveyresults.h b/src/solver/variable/surveyresults/surveyresults.h deleted file mode 100644 index f804de05e6..0000000000 --- a/src/solver/variable/surveyresults/surveyresults.h +++ /dev/null @@ -1,160 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __SOLVER_VARIABLE_SURVEY_RESULTS_SURVEY_RESULTS_H__ -#define __SOLVER_VARIABLE_SURVEY_RESULTS_SURVEY_RESULTS_H__ - -#include -#include -#include "../constants.h" -#include -#include "../categories.h" -#include "data.h" -#include -#include - -namespace Antares::Solver::Variable -{ -/*! -** \brief Class utility for building CSV results files -*/ -class SurveyResults -{ -public: - //! Precision - typedef Yuni::CString<10, false> PrecisionType; - //! Caption - typedef Yuni::CString<128, false> CaptionType; - -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - ** - ** \param maxVars The maximum total of variables that we may need for writing - ** the report - ** \param s Reference to the study - ** \param o The output folder - ** \param year The current year, if any - */ - SurveyResults(const Data::Study& s, - const Yuni::String& o, - IResultWriter& writer); - /*! - ** \brief Destructor - */ - ~SurveyResults(); - //@} - - /*! - ** \brief Write the data into a file - */ - void saveToFile(int dataLevel, int fileLevel, int precisionLevel); - - /*! - ** \brief Export informations about the current study - ** - ** It is composed by several files to completely describe the system - ** and provide a good support for Excel macros. - */ - void exportGridInfos(); - - // Reset a line of values to zero. - void resetValuesAtLine(uint); - - /*! - ** \brief Export the digest file - */ - void exportDigestAllYears(std::string& buffer); - - void exportDigestMatrix(const char* title, std::string& buffer); - -public: - //! Data (not related to the template parameter) - Solver::Variable::Private::SurveyResultsData data; - - //! Caption for the current variable - CaptionType variableCaption; - std::string variableUnit; - - //! Matrix where to store all results - double** values; - - enum - { - captionCount = 3, - }; - //! Array to store all variable names - CaptionType* captions[captionCount]; - - //! Precision to for each column (in the printf format) - PrecisionType* precision; - - //! Non applicable status for each column (in the printf format) - bool* nonApplicableStatus; - // Digest file non applicable status ( dim : nb vars x max(nb areas, nb sets of areas) ) - uint digestSize; // Useful dimension for digest file non applicable statut management. - bool** digestNonApplicableStatus; - - //! The total number of variables - uint maxVariables; - - //! Flag to known if we are in the year-by-year mode - bool yearByYearResults; - - //! When looping over output variables, is current variable non applicable ? - //! In the static type list of variables, there is a need to convey the non applicable status to - //! variables statistic results through an instance of the current class. Furthermore, some - //! unusual variables are actually "multi-variables", that is they contain actually several - //! variables. Therefore, the following is a pointer on the current output variable's non - //! applicable status. In case of a multi-variable, it is a pointer on the current - //! sub-variable's non applicable status. This pointer references a TEMPORARY boolean value. It - //! is NEVER used to allocate a table. - bool* isCurrentVarNA; - //! Same thing for print status (do we print the current output variable ?) - bool* isPrinted; - // File writer - IResultWriter& pResultWriter; - -private: - template - void AppendDoubleValue(uint& error, - const double v, - StringT& buffer, - ConvertT& conversionBuffer, - const PrecisionT& precision, - const bool isNotApplicable); - - void writeDateToFileDescriptor(uint row, int precisionLevel); - -}; // class SurveyResults - -} // namespace Antares::Solver::Variable - - - -#endif // __SOLVER_VARIABLE_SURVEY_RESULTS_SURVEY_RESULTS_H__ diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 3b39ab8f85..fcbc5cd6b2 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -34,6 +34,7 @@ if (${RECENT_BOOST}) add_subdirectory(end-to-end) add_subdirectory(src) add_subdirectory(kirchhoff-cbuilder) + add_subdirectory(inmemory-study) else() message(STATUS "Boost >= 1.60.0 is required for end-to-end tests, found ${Boost_VERSION}. Skipping") endif() @@ -65,13 +66,32 @@ if(Python3_Interpreter_FOUND) WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/run-study-tests" ) + add_test( + NAME milp-cbc + COMMAND Python3::Interpreter -m pytest -m json --solver-path=$ --use-ortools --ortools-solver coin + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/run-study-tests" + ) + + add_test( + NAME parallel + COMMAND Python3::Interpreter -m pytest -m json --solver-path=$ --force-parallel + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/run-study-tests" + ) + # The Kirchhoff constraint builder is built only if BUILD_TOOLS=ON if (BUILD_TOOLS) add_test( NAME kirchhoff - COMMAND Python3::Interpreter -m pytest -m kirchhoff --exe_kirchhoff_path=$ kirchhoff_pytest.py + COMMAND Python3::Interpreter -m pytest -m kirchhoff --exe_kirchhoff_path=$ kirchhoff_pytest.py WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/kirchhoff-cbuilder" ) + + add_test( + NAME tsgenerator + COMMAND Python3::Interpreter -m pytest -m tsgenerator --tsgenerator_path=$ antares_tools/ts-generator/ts-generator.py + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/run-study-tests" + ) + endif() set_property(TEST unfeasible PROPERTY LABELS study sirius) diff --git a/src/tests/end-to-end/CMakeLists.txt b/src/tests/end-to-end/CMakeLists.txt index 9830013131..6c2031e372 100644 --- a/src/tests/end-to-end/CMakeLists.txt +++ b/src/tests/end-to-end/CMakeLists.txt @@ -1,3 +1,2 @@ -add_subdirectory(utils) add_subdirectory(simple_study) add_subdirectory(binding_constraints) \ No newline at end of file diff --git a/src/tests/end-to-end/binding_constraints/CMakeLists.txt b/src/tests/end-to-end/binding_constraints/CMakeLists.txt index c65327c73f..72e2e46f62 100644 --- a/src/tests/end-to-end/binding_constraints/CMakeLists.txt +++ b/src/tests/end-to-end/binding_constraints/CMakeLists.txt @@ -12,22 +12,19 @@ add_executable(tests-binding_constraints target_link_libraries(tests-binding_constraints PRIVATE - test_utils Boost::unit_test_framework + model_antares antares-solver-simulation antares-solver-hydro antares-solver-ts-generator - antares-solver-aleatoire + Antares::tests::in-memory-study ) target_include_directories(tests-binding_constraints PRIVATE ${CMAKE_SOURCE_DIR}/solver - ${CMAKE_CURRENT_SOURCE_DIR}/../utils ) add_test(NAME end-to-end-binding_constraints COMMAND tests-binding_constraints) set_property(TEST end-to-end-binding_constraints PROPERTY LABELS end-to-end) set_target_properties(tests-binding_constraints PROPERTIES FOLDER Unit-tests/end_to_end) - -copy_dependency(sirius_solver tests-binding_constraints) diff --git a/src/tests/end-to-end/binding_constraints/test_binding_constraints.cpp b/src/tests/end-to-end/binding_constraints/test_binding_constraints.cpp index a9ddebe59d..10f91f2a40 100644 --- a/src/tests/end-to-end/binding_constraints/test_binding_constraints.cpp +++ b/src/tests/end-to-end/binding_constraints/test_binding_constraints.cpp @@ -1,19 +1,37 @@ -#define BOOST_TEST_MODULE test-end-to-end tests_binding_constraints -#define BOOST_TEST_DYN_LINK +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test - end - to - end tests_binding_constraints #define WIN32_LEAN_AND_MEAN -#include #include +#include -#include "utils.h" +#include "in-memory-study.h" namespace utf = boost::unit_test; namespace tt = boost::test_tools; - // ================================= // The Basic fixture for BC tests // ================================= -struct StudyForBCTest : public StudyBuilder +struct StudyForBCTest: public StudyBuilder { using StudyBuilder::StudyBuilder; StudyForBCTest(); @@ -31,13 +49,9 @@ StudyForBCTest::StudyForBCTest() Area* area1 = addAreaToStudy("Area 1"); Area* area2 = addAreaToStudy("Area 2"); - TimeSeriesConfigurer(area1->load.series->timeSeries) - .setColumnCount(1) - .fillColumnWith(0, 0); + TimeSeriesConfigurer(area1->load.series.timeSeries).setColumnCount(1).fillColumnWith(0, 0); - TimeSeriesConfigurer(area2->load.series->timeSeries) - .setColumnCount(1) - .fillColumnWith(0, 100); + TimeSeriesConfigurer(area2->load.series.timeSeries).setColumnCount(1).fillColumnWith(0, 100); link = AreaAddLinkBetweenAreas(area1, area2); @@ -46,17 +60,17 @@ StudyForBCTest::StudyForBCTest() cluster = addClusterToArea(area1, "some cluster"); ThermalClusterConfig(cluster.get()) - .setNominalCapacity(100.) - .setAvailablePower(0, 100.) - .setCosts(50.) - .setUnitCount(1); -}; + .setNominalCapacity(100.) + .setAvailablePower(0, 100.) + .setCosts(50.) + .setUnitCount(1); +} // ====================================================== // Study fixture containing a BC on the link capacity // ====================================================== -struct StudyWithBConLink : public StudyForBCTest +struct StudyWithBConLink: public StudyForBCTest { using StudyForBCTest::StudyForBCTest; StudyWithBConLink(); @@ -69,12 +83,11 @@ StudyWithBConLink::StudyWithBConLink() BC->enabled(true); } - // ======================================================= -// Study fixture containing a BC on the thermal cluster +// Study fixture containing a BC on the thermal cluster // ======================================================= -struct StudyWithBConCluster : public StudyForBCTest +struct StudyWithBConCluster: public StudyForBCTest { using StudyForBCTest::StudyForBCTest; StudyWithBConCluster(); @@ -87,9 +100,9 @@ StudyWithBConCluster::StudyWithBConCluster() BC->enabled(true); } -BOOST_FIXTURE_TEST_SUITE(TESTS_BINDING_CONSTRAINTS_ON_A_LINK, StudyWithBConLink) +BOOST_AUTO_TEST_SUITE(TESTS_BINDING_CONSTRAINTS_ON_A_LINK) -BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_90) +BOOST_FIXTURE_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_90, StudyWithBConLink) { setNumberMCyears(1); @@ -97,9 +110,7 @@ BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_90) BC->operatorType(BindingConstraint::opEquality); double rhsValue = 90.; - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, rhsValue); + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, rhsValue); simulation->create(); simulation->run(); @@ -109,8 +120,7 @@ BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_90) BOOST_TEST(output.flow(link).hour(0) == rhsValue, tt::tolerance(0.001)); } - -BOOST_AUTO_TEST_CASE(weekly_BC_restricts_link_direct_capacity_to_50) +BOOST_FIXTURE_TEST_CASE(weekly_BC_restricts_link_direct_capacity_to_50, StudyWithBConLink) { setNumberMCyears(1); @@ -118,10 +128,7 @@ BOOST_AUTO_TEST_CASE(weekly_BC_restricts_link_direct_capacity_to_50) BC->operatorType(BindingConstraint::opEquality); double rhsValue = 50.; - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, rhsValue); - + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, rhsValue); simulation->create(); simulation->run(); @@ -131,8 +138,7 @@ BOOST_AUTO_TEST_CASE(weekly_BC_restricts_link_direct_capacity_to_50) BOOST_TEST(output.flow(link).week(0) == rhsValue * nbDaysInWeek, tt::tolerance(0.001)); } - -BOOST_AUTO_TEST_CASE(daily_BC_restricts_link_direct_capacity_to_60) +BOOST_FIXTURE_TEST_CASE(daily_BC_restricts_link_direct_capacity_to_60, StudyWithBConLink) { setNumberMCyears(1); @@ -140,9 +146,7 @@ BOOST_AUTO_TEST_CASE(daily_BC_restricts_link_direct_capacity_to_60) BC->operatorType(BindingConstraint::opEquality); double rhsValue = 60.; - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, rhsValue); + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, rhsValue); simulation->create(); simulation->run(); @@ -151,8 +155,7 @@ BOOST_AUTO_TEST_CASE(daily_BC_restricts_link_direct_capacity_to_60) BOOST_TEST(output.flow(link).day(0) == rhsValue, tt::tolerance(0.001)); } - -BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_less_than_90) +BOOST_FIXTURE_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_less_than_90, StudyWithBConLink) { setNumberMCyears(1); @@ -160,9 +163,7 @@ BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_less_than_90) BC->operatorType(BindingConstraint::opLess); double rhsValue = 90.; - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, rhsValue); + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, rhsValue); simulation->create(); simulation->run(); @@ -171,7 +172,8 @@ BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_link_direct_capacity_to_less_than_90) BOOST_TEST(output.flow(link).hour(100) <= rhsValue, tt::tolerance(0.001)); } -BOOST_AUTO_TEST_CASE(Daily_BC_restricts_link_direct_capacity_to_greater_than_80) +BOOST_FIXTURE_TEST_CASE(Daily_BC_restricts_link_direct_capacity_to_greater_than_80, + StudyWithBConLink) { setNumberMCyears(1); @@ -179,9 +181,7 @@ BOOST_AUTO_TEST_CASE(Daily_BC_restricts_link_direct_capacity_to_greater_than_80) BC->operatorType(BindingConstraint::opGreater); double rhsValue = 80.; - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, rhsValue); + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, rhsValue); simulation->create(); simulation->run(); @@ -192,10 +192,9 @@ BOOST_AUTO_TEST_CASE(Daily_BC_restricts_link_direct_capacity_to_greater_than_80) BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE(TESTS_BINDING_CONSTRAINTS_ON_A_CLUSTER) -BOOST_FIXTURE_TEST_SUITE(TESTS_BINDING_CONSTRAINTS_ON_A_CLUSTER, StudyWithBConCluster) - -BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_cluster_generation_to_90) +BOOST_FIXTURE_TEST_CASE(Hourly_BC_restricts_cluster_generation_to_90, StudyWithBConLink) { setNumberMCyears(1); @@ -203,9 +202,7 @@ BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_cluster_generation_to_90) BC->operatorType(BindingConstraint::opEquality); double rhsValue = 90.; - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, rhsValue); + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, rhsValue); simulation->create(); simulation->run(); @@ -216,11 +213,9 @@ BOOST_AUTO_TEST_CASE(Hourly_BC_restricts_cluster_generation_to_90) BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE(TESTING_BC_RHS_SCENARIZATION_WHEN_BC_ON_A_LINK) -BOOST_FIXTURE_TEST_SUITE(TESTING_BC_RHS_SCENARIZATION_WHEN_BC_ON_A_LINK, StudyWithBConLink) - - -BOOST_AUTO_TEST_CASE(On_year_2__RHS_TS_number_2_is_taken_into_account) +BOOST_FIXTURE_TEST_CASE(On_year_2__RHS_TS_number_2_is_taken_into_account, StudyWithBConLink) { setNumberMCyears(2); @@ -230,9 +225,9 @@ BOOST_AUTO_TEST_CASE(On_year_2__RHS_TS_number_2_is_taken_into_account) double bcGroupRHS1 = 90.; double bcGroupRHS2 = 70.; TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(2) - .fillColumnWith(0, bcGroupRHS1) - .fillColumnWith(1, bcGroupRHS2); + .setColumnCount(2) + .fillColumnWith(0, bcGroupRHS1) + .fillColumnWith(1, bcGroupRHS2); ScenarioBuilderRule scenarioBuilderRule(*study); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 0, 1); @@ -246,7 +241,7 @@ BOOST_AUTO_TEST_CASE(On_year_2__RHS_TS_number_2_is_taken_into_account) BOOST_TEST(output.flow(link).hour(0) == bcGroupRHS2, tt::tolerance(0.001)); } -BOOST_AUTO_TEST_CASE(On_year_9__RHS_TS_number_4_is_taken_into_account) +BOOST_FIXTURE_TEST_CASE(On_year_9__RHS_TS_number_4_is_taken_into_account, StudyWithBConLink) { setNumberMCyears(10); @@ -254,14 +249,14 @@ BOOST_AUTO_TEST_CASE(On_year_9__RHS_TS_number_4_is_taken_into_account) BC->operatorType(BindingConstraint::opEquality); TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(7) - .fillColumnWith(0, 10.) - .fillColumnWith(1, 20.) - .fillColumnWith(2, 30.) - .fillColumnWith(3, 40.) - .fillColumnWith(4, 50.) - .fillColumnWith(5, 60.) - .fillColumnWith(6, 70.); + .setColumnCount(7) + .fillColumnWith(0, 10.) + .fillColumnWith(1, 20.) + .fillColumnWith(2, 30.) + .fillColumnWith(3, 40.) + .fillColumnWith(4, 50.) + .fillColumnWith(5, 60.) + .fillColumnWith(6, 70.); ScenarioBuilderRule scenarioBuilderRule(*study); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 0, 1); @@ -272,7 +267,7 @@ BOOST_AUTO_TEST_CASE(On_year_9__RHS_TS_number_4_is_taken_into_account) scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 5, 1); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 6, 1); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 7, 1); - scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 8, 4); // Here year 9 + scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 8, 4); // Here year 9 scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 9, 1); simulation->create(); @@ -283,16 +278,15 @@ BOOST_AUTO_TEST_CASE(On_year_9__RHS_TS_number_4_is_taken_into_account) BOOST_TEST(output.flow(link).hour(0) == 40., tt::tolerance(0.001)); } -BOOST_AUTO_TEST_CASE(On_year_9__RHS_TS_number_4_out_of_bound_use_random_fallback_to_Oth_column) +BOOST_FIXTURE_TEST_CASE(On_year_9__RHS_TS_number_4_out_of_bound_use_random_fallback_to_Oth_column, + StudyWithBConLink) { setNumberMCyears(10); BC->setTimeGranularity(BindingConstraint::typeHourly); BC->operatorType(BindingConstraint::opEquality); - TimeSeriesConfigurer(BC->RHSTimeSeries()) - .setColumnCount(1) - .fillColumnWith(0, 0.); + TimeSeriesConfigurer(BC->RHSTimeSeries()).setColumnCount(1).fillColumnWith(0, 0.); ScenarioBuilderRule scenarioBuilderRule(*study); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 0, 1); @@ -303,7 +297,7 @@ BOOST_AUTO_TEST_CASE(On_year_9__RHS_TS_number_4_out_of_bound_use_random_fallback scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 5, 1); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 6, 1); scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 7, 1); - scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 8, 42); // Here year 9 + scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 8, 42); // Here year 9 scenarioBuilderRule.bcGroup().setTSnumber(BC->group(), 9, 1); simulation->create(); diff --git a/src/tests/end-to-end/simple_study/CMakeLists.txt b/src/tests/end-to-end/simple_study/CMakeLists.txt index ac29766275..cc5c93b410 100644 --- a/src/tests/end-to-end/simple_study/CMakeLists.txt +++ b/src/tests/end-to-end/simple_study/CMakeLists.txt @@ -3,40 +3,33 @@ enable_testing() #bigobj support needed for windows compilation if(MSVC) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") endif(MSVC) add_executable(tests-simple-study - simple-study.cpp - ) + simple-study.cpp +) target_link_libraries(tests-simple-study - PRIVATE - test_utils - antares-solver-main-economy - antares-solver-main-adequacy - antares-solver-hydro - antares-solver-aleatoire - antares-solver-variable - antares-solver-simulation - antares-solver-ts-generator - model_antares - ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} - ) - + PRIVATE + antares-solver-hydro + antares-solver-variable + antares-solver-simulation + antares-solver-ts-generator + model_antares + ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} + Antares::tests::in-memory-study +) + target_include_directories(tests-simple-study - PRIVATE - ${CMAKE_SOURCE_DIR}/solver - ${CMAKE_CURRENT_SOURCE_DIR}/../utils - ) + PRIVATE + ${CMAKE_SOURCE_DIR}/solver +) add_test(NAME end-to-end-simple-study COMMAND tests-simple-study) set_property(TEST end-to-end-simple-study PROPERTY LABELS end-to-end) set_target_properties(tests-simple-study PROPERTIES FOLDER Unit-tests/end_to_end) - -copy_dependency(sirius_solver tests-simple-study) - # Storing tests-simple-study under the folder Unit-tests in the IDE #---------------------------------------------------------- diff --git a/src/tests/end-to-end/simple_study/simple-study.cpp b/src/tests/end-to-end/simple_study/simple-study.cpp index d200c32bc8..7005057209 100644 --- a/src/tests/end-to-end/simple_study/simple-study.cpp +++ b/src/tests/end-to-end/simple_study/simple-study.cpp @@ -1,9 +1,28 @@ -#define BOOST_TEST_MODULE test-end-to-end tests -#define BOOST_TEST_DYN_LINK -#include +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test - end - to - end tests #include +#include -#include "utils.h" +#include "in-memory-study.h" namespace utf = boost::unit_test; namespace tt = boost::test_tools; @@ -11,154 +30,368 @@ namespace tt = boost::test_tools; using namespace Antares::Data; // ================================= -// Basic fixture +// Basic fixture // ================================= -struct StudyFixture : public StudyBuilder -{ - using StudyBuilder::StudyBuilder; - StudyFixture(); - - // Data members - std::shared_ptr cluster; - Area* area = nullptr; - double loadInArea = 0.; - double clusterCost = 0.; - ThermalClusterConfig clusterConfig; - TimeSeriesConfigurer> loadTSconfig; +struct StudyFixture: public StudyBuilder +{ + using StudyBuilder::StudyBuilder; + StudyFixture(); + + // Data members + std::shared_ptr cluster; + Area* area = nullptr; + double loadInArea = 0.; + double clusterCost = 0.; + ThermalClusterConfig clusterConfig; + TimeSeriesConfigurer loadTSconfig; }; StudyFixture::StudyFixture() { - simulationBetweenDays(0, 7); - area = addAreaToStudy("Some area"); - cluster = addClusterToArea(area, "some cluster"); - - loadInArea = 7.0; - loadTSconfig = std::move(TimeSeriesConfigurer(area->load.series->timeSeries)); - loadTSconfig.setColumnCount(1) - .fillColumnWith(0, loadInArea); - - clusterCost = 2.; - clusterConfig = std::move(ThermalClusterConfig(cluster.get())); - clusterConfig.setNominalCapacity(100.) - .setAvailablePower(0, 50.) - .setCosts(clusterCost) - .setUnitCount(1); + simulationBetweenDays(0, 7); + area = addAreaToStudy("Some area"); + cluster = addClusterToArea(area, "some cluster"); + + loadInArea = 7.0; + loadTSconfig = TimeSeriesConfigurer(area->load.series.timeSeries); + loadTSconfig.setColumnCount(1).fillColumnWith(0, loadInArea); + + clusterCost = 2.; + clusterConfig = ThermalClusterConfig(cluster.get()); + clusterConfig.setNominalCapacity(100.) + .setAvailablePower(0, 50.) + .setCosts(clusterCost) + .setUnitCount(1); +} + +struct HydroMaxPowerStudy: public StudyBuilder +{ + using StudyBuilder::StudyBuilder; + HydroMaxPowerStudy(); + + // Data members + Area* area = nullptr; + PartHydro* hydro = nullptr; + double loadInArea = 24000.; }; +HydroMaxPowerStudy::HydroMaxPowerStudy() +{ + simulationBetweenDays(0, 14); + + area = addAreaToStudy("Area"); + area->thermal.unsuppliedEnergyCost = 1; + + setNumberMCyears(1); + + TimeSeriesConfigurer loadTSconfig(area->load.series.timeSeries); + loadTSconfig.setColumnCount(1).fillColumnWith(0, loadInArea); + + hydro = &area->hydro; -BOOST_FIXTURE_TEST_SUITE(ONE_AREA__ONE_THERMAL_CLUSTER, StudyFixture) + TimeSeriesConfigurer genP(hydro->series->maxHourlyGenPower.timeSeries); + genP.setColumnCount(1).fillColumnWith(0, 100.); -BOOST_AUTO_TEST_CASE(thermal_cluster_fullfills_area_demand) -{ - setNumberMCyears(1); + TimeSeriesConfigurer hydroStorage(hydro->series->storage.timeSeries); + hydroStorage.setColumnCount(1, DAYS_PER_YEAR).fillColumnWith(0, 2400.); - simulation->create(); - simulation->run(); + TimeSeriesConfigurer genE(hydro->dailyNbHoursAtGenPmax); + genE.setColumnCount(1, DAYS_PER_YEAR).fillColumnWith(0, 24); - OutputRetriever output(simulation->rawSimu()); - BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); - BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); + hydro->reservoirCapacity = 1e6; + hydro->reservoirManagement = true; } -BOOST_AUTO_TEST_CASE(two_MC_years__thermal_cluster_fullfills_area_demand_on_2nd_year_as_well) +BOOST_AUTO_TEST_SUITE(ONE_AREA__ONE_THERMAL_CLUSTER) + +BOOST_FIXTURE_TEST_CASE(thermal_cluster_fullfills_area_demand, StudyFixture) { - setNumberMCyears(2); + setNumberMCyears(1); + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); + BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); +} - simulation->create(); - playOnlyYear(1); - simulation->run(); +BOOST_FIXTURE_TEST_CASE(two_MC_years__thermal_cluster_fullfills_area_demand_on_2nd_year_as_well, + StudyFixture) +{ + setNumberMCyears(2); - OutputRetriever output(simulation->rawSimu()); - BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); - BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); + simulation->create(); + playOnlyYear(1); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); + BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); } -BOOST_AUTO_TEST_CASE(two_mc_years__two_ts_identical) +BOOST_FIXTURE_TEST_CASE(two_mc_years__two_ts_identical, StudyFixture) { - setNumberMCyears(2); + setNumberMCyears(2); - loadTSconfig.setColumnCount(2) - .fillColumnWith(0, 7.0) - .fillColumnWith(1, 7.0); + loadTSconfig.setColumnCount(2).fillColumnWith(0, 7.0).fillColumnWith(1, 7.0); - clusterConfig.setAvailablePowerNumberOfTS(2) - .setAvailablePower(0, 50.) - .setAvailablePower(1, 50.); + clusterConfig.setAvailablePowerNumberOfTS(2).setAvailablePower(0, 50.).setAvailablePower(1, + 50.); - simulation->create(); - simulation->run(); + simulation->create(); + simulation->run(); - OutputRetriever output(simulation->rawSimu()); - BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); - BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); + OutputRetriever output(simulation->rawSimu()); + BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); + BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); } -BOOST_AUTO_TEST_CASE(two_mc_years__two_ts_for_load) +BOOST_FIXTURE_TEST_CASE(two_mc_years__two_ts_for_load, StudyFixture) { - setNumberMCyears(2); + setNumberMCyears(2); - loadTSconfig.setColumnCount(2) - .fillColumnWith(0, 7.0) - .fillColumnWith(1, 14.0); + loadTSconfig.setColumnCount(2).fillColumnWith(0, 7.0).fillColumnWith(1, 14.0); - ScenarioBuilderRule scenarioBuilderRule(*study); - scenarioBuilderRule.load().setTSnumber(area->index, 0, 1); - scenarioBuilderRule.load().setTSnumber(area->index, 1, 2); + ScenarioBuilderRule scenarioBuilderRule(*study); + scenarioBuilderRule.load().setTSnumber(area->index, 0, 1); + scenarioBuilderRule.load().setTSnumber(area->index, 1, 2); - simulation->create(); - simulation->run(); + simulation->create(); + simulation->run(); - OutputRetriever output(simulation->rawSimu()); - double averageLoad = (7. + 14.) / 2.; - BOOST_TEST(output.thermalGeneration(cluster.get()).hour(10) == averageLoad, tt::tolerance(0.001)); - BOOST_TEST(output.overallCost(area).hour(0) == averageLoad * clusterCost, tt::tolerance(0.001)); + OutputRetriever output(simulation->rawSimu()); + double averageLoad = (7. + 14.) / 2.; + BOOST_TEST(output.thermalGeneration(cluster.get()).hour(10) == averageLoad, + tt::tolerance(0.001)); + BOOST_TEST(output.overallCost(area).hour(0) == averageLoad * clusterCost, tt::tolerance(0.001)); } -BOOST_AUTO_TEST_CASE(two_mc_years_with_different_weight__two_ts) -{ - setNumberMCyears(2); - - giveWeightToYear(4.f, 0); - giveWeightToYear(10.f, 1); - float weightSum = study->parameters.getYearsWeightSum(); - - loadTSconfig.setColumnCount(2) - .fillColumnWith(0, 7.0) - .fillColumnWith(1, 14.0); - - ScenarioBuilderRule scenarioBuilderRule(*study); - scenarioBuilderRule.load().setTSnumber(area->index, 0, 1); - scenarioBuilderRule.load().setTSnumber(area->index, 1, 2); - - simulation->create(); - simulation->run(); - - OutputRetriever output(simulation->rawSimu()); - double averageLoad = (4 * 7. + 10. * 14.) / weightSum; - BOOST_TEST(output.thermalGeneration(cluster.get()).hour(10) == averageLoad, tt::tolerance(0.001)); - BOOST_TEST(output.overallCost(area).hour(0) == averageLoad * clusterCost, tt::tolerance(0.001)); +BOOST_FIXTURE_TEST_CASE(two_mc_years_with_different_weight__two_ts, StudyFixture) +{ + setNumberMCyears(2); + + giveWeightToYear(4.f, 0); + giveWeightToYear(10.f, 1); + float weightSum = study->parameters.getYearsWeightSum(); + + loadTSconfig.setColumnCount(2).fillColumnWith(0, 7.0).fillColumnWith(1, 14.0); + + ScenarioBuilderRule scenarioBuilderRule(*study); + scenarioBuilderRule.load().setTSnumber(area->index, 0, 1); + scenarioBuilderRule.load().setTSnumber(area->index, 1, 2); + + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + double averageLoad = (4 * 7. + 10. * 14.) / weightSum; + BOOST_TEST(output.thermalGeneration(cluster.get()).hour(10) == averageLoad, + tt::tolerance(0.001)); + BOOST_TEST(output.overallCost(area).hour(0) == averageLoad * clusterCost, tt::tolerance(0.001)); +} + +BOOST_FIXTURE_TEST_CASE(milp_two_mc_single_unit_single_scenario, StudyFixture) +{ + setNumberMCyears(1); + + // Arbitrary large number, only characteristic is : larger than all + // other marginal costs + area->thermal.unsuppliedEnergyCost = 1000; + + // Use OR-Tools / COIN for MILP + auto& p = study->parameters; + p.unitCommitment.ucMode = ucMILP; + p.optOptions.ortoolsUsed = true; + p.optOptions.ortoolsSolver = "coin"; + + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + + BOOST_TEST(output.thermalGeneration(cluster.get()).hour(10) == loadInArea, + tt::tolerance(0.001)); + BOOST_TEST(output.thermalNbUnitsON(cluster.get()).hour(10) == 1, tt::tolerance(0.001)); + BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); } +BOOST_FIXTURE_TEST_CASE(milp_two_mc_two_unit_single_scenario, StudyFixture) +{ + setNumberMCyears(1); + + clusterConfig.setAvailablePower(0, 150.).setUnitCount(2); + + loadInArea = 150; + loadTSconfig.setColumnCount(1).fillColumnWith(0, loadInArea); + // Arbitrary large number, only characteristic is : larger than all + // other marginal costs + area->thermal.unsuppliedEnergyCost = 1000; + + // Use OR-Tools / COIN for MILP + auto& p = study->parameters; + p.unitCommitment.ucMode = ucMILP; + p.optOptions.ortoolsUsed = true; + p.optOptions.ortoolsSolver = "coin"; + + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + + BOOST_TEST(output.thermalGeneration(cluster.get()).hour(10) == loadInArea, + tt::tolerance(0.001)); + BOOST_TEST(output.thermalNbUnitsON(cluster.get()).hour(10) == 2, tt::tolerance(0.001)); +} + +BOOST_FIXTURE_TEST_CASE(parallel, StudyFixture) +{ + setNumberMCyears(10); + study->maxNbYearsInParallel = 2; + + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); + BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); +} + +BOOST_FIXTURE_TEST_CASE(parallel2, StudyFixture) +{ + setNumberMCyears(2); + study->maxNbYearsInParallel = 2; + + loadTSconfig.setColumnCount(2).fillColumnWith(0, 7.0).fillColumnWith(1, 7.0); + + clusterConfig.setAvailablePowerNumberOfTS(2).setAvailablePower(0, 50.).setAvailablePower(1, + 50.); + + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + BOOST_TEST(output.overallCost(area).hour(0) == loadInArea * clusterCost, tt::tolerance(0.001)); + BOOST_TEST(output.load(area).hour(0) == loadInArea, tt::tolerance(0.001)); +} BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(error_cases) -BOOST_AUTO_TEST_CASE(error_on_wrong_hydro_data) +BOOST_FIXTURE_TEST_CASE(error_on_wrong_hydro_data, StudyFixture) { StudyBuilder builder; builder.simulationBetweenDays(0, 7); - builder.setNumberMCyears(1); Area& area = *builder.addAreaToStudy("A"); PartHydro& hydro = area.hydro; - TimeSeriesConfigurer(hydro.series->storage) - .setColumnCount(1) - .fillColumnWith(0, -1.0); //Negative inflow will cause a consistency error with mingen + TimeSeriesConfigurer(hydro.series->storage.timeSeries) + .setColumnCount(1) + .fillColumnWith(0, -1.0); // Negative inflow will cause a consistency error with mingen + builder.setNumberMCyears(1); auto simulation = builder.simulation; simulation->create(); BOOST_CHECK_THROW(simulation->run(), Antares::FatalError); } +BOOST_AUTO_TEST_SUITE_END() + +BOOST_AUTO_TEST_SUITE(ONE_AREA__ONE_STS_THERMAL_CLUSTER) + +BOOST_FIXTURE_TEST_CASE(STS_initial_level_is_also_weekly_final_level, StudyFixture) +{ + using namespace Antares::Data::ShortTermStorage; + setNumberMCyears(1); + auto& storages = area->shortTermStorage.storagesByIndex; + STStorageCluster sts; + auto& props = sts.properties; + props.name = "my-sts"; + props.injectionNominalCapacity = 10; + props.withdrawalNominalCapacity = 10; + props.reservoirCapacity = 100; + props.efficiencyFactor = .9; + props.initialLevel = .443; + props.groupName = std::string("Some STS group"); + // Default values for series + sts.series->fillDefaultSeriesIfEmpty(); + + storages.push_back(sts); + + // Fatal gen at h=1 + { + auto& windTS = area->wind.series.timeSeries; + TimeSeriesConfigurer(windTS).setColumnCount(1).fillColumnWith(0, 0.); + windTS[0][1] = 100; + } + + // Fatal load at h=2 + { + auto& loadTS = area->load.series.timeSeries; + TimeSeriesConfigurer(loadTS).setColumnCount(1).fillColumnWith(0, 0.); + loadTS[0][2] = 100; + } + + // Usual values, avoid spillage & unsupplied energy + area->thermal.unsuppliedEnergyCost = 1.e3; + area->thermal.spilledEnergyCost = 1.; + + simulation->create(); + simulation->run(); + + unsigned int groupNb = 0; // Used to reach the first group of STS results + OutputRetriever output(simulation->rawSimu()); + BOOST_TEST(output.levelForSTSgroup(area, groupNb).hour(167) + == props.initialLevel * props.reservoirCapacity.value(), + tt::tolerance(0.001)); +} +BOOST_AUTO_TEST_SUITE_END() + +BOOST_AUTO_TEST_SUITE(HYDRO_MAX_POWER) + +BOOST_FIXTURE_TEST_CASE(basic, HydroMaxPowerStudy) +{ + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + + BOOST_TEST(output.hydroStorage(area).hour(0) + == hydro->series->maxHourlyGenPower.timeSeries[0][0], + tt::tolerance(0.001)); + BOOST_TEST(output.overallCost(area).hour(0) + == (loadInArea - output.hydroStorage(area).hour(0)) + * area->thermal.unsuppliedEnergyCost, + tt::tolerance(0.001)); +} + +BOOST_FIXTURE_TEST_CASE(scenario_builder, HydroMaxPowerStudy) +{ + setNumberMCyears(3); + + giveWeightToYear(4.f, 0); + giveWeightToYear(3.f, 1); + giveWeightToYear(2.f, 2); + float weightSum = study->parameters.getYearsWeightSum(); + + TimeSeriesConfigurer genP(hydro->series->maxHourlyGenPower.timeSeries); + TimeSeriesConfigurer genE(hydro->series->maxHourlyPumpPower.timeSeries); + genP.setColumnCount(3).fillColumnWith(0, 100.).fillColumnWith(1, 200.).fillColumnWith(2, 300.); + genE.setColumnCount(3).fillColumnWith(0, 0.).fillColumnWith(1, 0.).fillColumnWith(2, 0.); + + ScenarioBuilderRule scenarioBuilderRule(*study); + scenarioBuilderRule.hydro().setTSnumber(area->index, 0, 3); + scenarioBuilderRule.hydro().setTSnumber(area->index, 1, 2); + scenarioBuilderRule.hydro().setTSnumber(area->index, 2, 1); + + simulation->create(); + simulation->run(); + + OutputRetriever output(simulation->rawSimu()); + + double averageLoad = (4 * 300. + 3. * 200. + 2. * 100.) / weightSum; + + BOOST_TEST(output.overallCost(area).hour(0) + == loadInArea - averageLoad * area->thermal.unsuppliedEnergyCost, + tt::tolerance(0.1)); +} BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/end-to-end/utils/CMakeLists.txt b/src/tests/end-to-end/utils/CMakeLists.txt deleted file mode 100644 index 3923b070d2..0000000000 --- a/src/tests/end-to-end/utils/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -add_library(test_utils - utils.cpp - utils.h - ) - -target_link_libraries(test_utils - PRIVATE - antares-solver-simulation - PUBLIC - ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} - Antares::infoCollection - ) - -target_include_directories(test_utils - PRIVATE - ${CMAKE_SOURCE_DIR}/solver - ) - -set_target_properties(test_utils PROPERTIES FOLDER Unit-tests/end_to_end) - -target_include_directories(test_utils PUBLIC ${Boost_INCLUDE_DIRS}) diff --git a/src/tests/end-to-end/utils/utils.cpp b/src/tests/end-to-end/utils/utils.cpp deleted file mode 100644 index d4dc34ac54..0000000000 --- a/src/tests/end-to-end/utils/utils.cpp +++ /dev/null @@ -1,209 +0,0 @@ -#define WIN32_LEAN_AND_MEAN -#include "utils.h" - - -void initializeStudy(Study::Ptr study) -{ - study->parameters.reset(); -} - -void configureLinkCapacities(AreaLink* link) -{ - const double linkCapacityInfinite = +std::numeric_limits::infinity(); - link->directCapacities.resize(1, 8760); - link->directCapacities.fill(linkCapacityInfinite); - - link->indirectCapacities.resize(1, 8760); - link->indirectCapacities.fill(linkCapacityInfinite); -} - -std::shared_ptr addClusterToArea(Area* area, const std::string& clusterName) -{ - auto cluster = std::make_shared(area); - cluster->setName(clusterName); - cluster->reset(); - - auto added = area->thermal.list.add(cluster); - - area->thermal.list.mapping[cluster->id()] = added; - area->thermal.prepareAreaWideIndexes(); - - return cluster; -} - -void addScratchpadToEachArea(Study& study) -{ - for (auto [_, area] : study.areas) { - for (unsigned int i = 0; i < study.maxNbYearsInParallel; ++i) { - area->scratchpad.emplace_back(*study.runtime, *area); - } - } -} - - -ThermalClusterConfig::ThermalClusterConfig(ThermalCluster* cluster) : cluster_(cluster) -{ - tsAvailablePowerConfig_ = std::move(TimeSeriesConfigurer(cluster_->series->timeSeries)); -} -ThermalClusterConfig& ThermalClusterConfig::setNominalCapacity(double nominalCapacity) -{ - cluster_->nominalCapacity = nominalCapacity; - return *this; -} -ThermalClusterConfig& ThermalClusterConfig::setUnitCount(unsigned int unitCount) -{ - cluster_->unitCount = unitCount; - return *this; -} -ThermalClusterConfig& ThermalClusterConfig::setCosts(double cost) -{ - cluster_->marginalCost = cost; - cluster_->marketBidCost = cost; // Must define market bid cost otherwise all production is used - return *this; -} -ThermalClusterConfig& ThermalClusterConfig::setAvailablePowerNumberOfTS(unsigned int columnCount) -{ - tsAvailablePowerConfig_.setColumnCount(columnCount); - return *this; -}; -ThermalClusterConfig& ThermalClusterConfig::setAvailablePower(unsigned int column, double value) -{ - tsAvailablePowerConfig_.fillColumnWith(column, value); - return *this; -} - -// ------------------------------- -// Simulation results retrieval -// ------------------------------- -averageResults OutputRetriever::overallCost(Area* area) -{ - auto result = retrieveAreaResults(area); - return averageResults(result->avgdata); -} - -averageResults OutputRetriever::load(Area* area) -{ - auto result = retrieveAreaResults(area); - return averageResults(result->avgdata); -} - -averageResults OutputRetriever::flow(AreaLink* link) -{ - // There is a problem here : - // we cannot easly retrieve the hourly flow for a link and a year : - // - Functions retrieveHourlyResultsForCurrentYear are not coded everywhere it should. - // - Even if those functions were correctly implemented, there is another problem : - // Each year results erase results of previous year, how can we retrieve results of year 1 - // if 2 year were run ? - // We should be able to run each year independently, which is not possible now. - // A workaround is to retrieve syntheses, and that's what we do here. - - auto result = retrieveLinkResults(link); - return averageResults(result->avgdata); -} - -averageResults OutputRetriever::thermalGeneration(ThermalCluster* cluster) -{ - auto result = retrieveResultsForThermalCluster(cluster); - return averageResults((*result)[cluster->areaWideIndex].avgdata); -} - -ScenarioBuilderRule::ScenarioBuilderRule(Study& study) -{ - study.scenarioRulesCreate(); - ScenarioBuilder::Sets* sets = study.scenarioRules; - if (sets && !sets->empty()) - { - rules_ = sets->createNew("Custom"); - - study.parameters.useCustomScenario = true; - study.parameters.activeRulesScenario = "Custom"; - } - } - - -// ===================== -// Simulation handler -// ===================== - -void SimulationHandler::create() -{ - study_.initializeRuntimeInfos(); - addScratchpadToEachArea(study_); - - simulation_ = std::make_shared>(study_, - settings_, - nullDurationCollector_, - resultWriter_); - SIM_AllocationTableaux(study_); -} - - -// ========================= -// Basic study builder -// ========================= -StudyBuilder::StudyBuilder() -{ - // Make logs shrink to errors (and higher) only - logs.verbosityLevel = Logs::Verbosity::Error::level; - - study = std::make_shared(); - simulation = std::make_shared(*study); - - initializeStudy(study); -} - -void StudyBuilder::simulationBetweenDays(const unsigned int firstDay, const unsigned int lastDay) -{ - study->parameters.simulationDays.first = firstDay; - study->parameters.simulationDays.end = lastDay; -} - -void StudyBuilder::setNumberMCyears(unsigned int nbYears) -{ - study->parameters.resetPlaylist(nbYears); - study->areas.resizeAllTimeseriesNumbers(nbYears); -} - -void StudyBuilder::playOnlyYear(unsigned int year) -{ - auto& params = study->parameters; - - params.userPlaylist = true; - std::fill(params.yearsFilter.begin(), params.yearsFilter.end(), false); - params.yearsFilter[year] = true; -} - -void StudyBuilder::giveWeightToYear(float weight, unsigned int year) -{ - study->parameters.setYearWeight(year, weight); - - // Activate playlist, otherwise previous sets won't have any effect - study->parameters.userPlaylist = true; -} - -Area* StudyBuilder::addAreaToStudy(const std::string& areaName) -{ - Area* area = addAreaToListOfAreas(study->areas, areaName); - - // Default values for the area - area->createMissingData(); - area->resetToDefaultValues(); - - // Temporary : we want to give a high unsupplied or spilled energy costs. - // Which cost should we give ? - area->thermal.unsuppliedEnergyCost = 1000.0; - area->thermal.spilledEnergyCost = 1000.0; - - study->areas.rebuildIndexes(); - - return area; -} - -std::shared_ptr addBindingConstraints(Study& study, std::string name, std::string group) { - auto bc = study.bindingConstraints.add(name); - bc->group(group); - auto g = study.bindingConstraintsGroups.add(group); - g->add(bc); - return bc; -} diff --git a/src/tests/end-to-end/utils/utils.h b/src/tests/end-to-end/utils/utils.h deleted file mode 100644 index 1781b2f54c..0000000000 --- a/src/tests/end-to-end/utils/utils.h +++ /dev/null @@ -1,186 +0,0 @@ -#pragma once -#define WIN32_LEAN_AND_MEAN -#include "antares/study/study.h" -#include "simulation/economy.h" -#include "antares/study/scenario-builder/rules.h" -#include "antares/study/scenario-builder/sets.h" -#include "simulation.h" - -using namespace Antares::Solver; -using namespace Antares::Solver::Simulation; -using namespace Antares::Data::ScenarioBuilder; - - -void initializeStudy(Study::Ptr study); -void configureLinkCapacities(AreaLink* link); - - -template -class TimeSeriesConfigurer -{ -public: - TimeSeriesConfigurer() = default; - TimeSeriesConfigurer(MatrixType& matrix) : ts_(&matrix) {} - TimeSeriesConfigurer& setColumnCount(unsigned int columnCount); - TimeSeriesConfigurer& fillColumnWith(unsigned int column, double value); -private: - MatrixType* ts_ = nullptr; -}; - -template -TimeSeriesConfigurer& TimeSeriesConfigurer::setColumnCount(unsigned int columnCount) -{ - ts_->resize(columnCount, HOURS_PER_YEAR); - return *this; -} - -template -TimeSeriesConfigurer& TimeSeriesConfigurer::fillColumnWith(unsigned int column, double value) -{ - ts_->fillColumn(column, value); - return *this; -} - - -class ThermalClusterConfig -{ -public: - ThermalClusterConfig() = default; - ThermalClusterConfig(ThermalCluster* cluster); - ThermalClusterConfig& setNominalCapacity(double nominalCapacity); - ThermalClusterConfig& setUnitCount(unsigned int unitCount); - ThermalClusterConfig& setCosts(double cost); - ThermalClusterConfig& setAvailablePowerNumberOfTS(unsigned int columnCount); - ThermalClusterConfig& setAvailablePower(unsigned int column, double value); - -private: - ThermalCluster* cluster_ = nullptr; - TimeSeriesConfigurer> tsAvailablePowerConfig_; -}; - -std::shared_ptr addClusterToArea(Area* area, const std::string& clusterName); -void addScratchpadToEachArea(Study& study); - -// ------------------------------- -// Simulation results retrieval -// ------------------------------- -class averageResults -{ -public: - averageResults(Variable::R::AllYears::AverageData& averageResults) : averageResults_(averageResults) - {} - - double hour(unsigned int hour) { return averageResults_.hourly[hour]; } - double day(unsigned int day) { return averageResults_.daily[day]; } - double week(unsigned int week) { return averageResults_.weekly[week]; } - -private: - Variable::R::AllYears::AverageData& averageResults_; -}; - - -class OutputRetriever -{ -public: - OutputRetriever(ISimulation& simulation) : simulation_(simulation) {} - averageResults overallCost(Area* area); - averageResults load(Area* area); - averageResults flow(AreaLink* link); - averageResults thermalGeneration(ThermalCluster* cluster); - -private: - template - typename Variable::Storage::ResultsType* retrieveAreaResults(Area* area); - - template - typename Variable::Storage::ResultsType* retrieveLinkResults(AreaLink* link); - - template - typename Variable::Storage::ResultsType* retrieveResultsForThermalCluster(ThermalCluster* cluster); - - ISimulation& simulation_; -}; - -template -typename Variable::Storage::ResultsType* -OutputRetriever::retrieveAreaResults(Area* area) -{ - typename Variable::Storage::ResultsType* result = nullptr; - simulation_.variables.retrieveResultsForArea(&result, area); - return result; -} - -template -typename Variable::Storage::ResultsType* -OutputRetriever::retrieveLinkResults(AreaLink* link) -{ - typename Variable::Storage::ResultsType* result = nullptr; - simulation_.variables.retrieveResultsForLink(&result, link); - return result; -} - -template -typename Variable::Storage::ResultsType* -OutputRetriever::retrieveResultsForThermalCluster(ThermalCluster* cluster) -{ - typename Variable::Storage::ResultsType* result = nullptr; - simulation_.variables.retrieveResultsForThermalCluster(&result, cluster); - return result; -} - -class ScenarioBuilderRule -{ -public: - ScenarioBuilderRule(Study& study); - loadTSNumberData& load() { return rules_->load; } - BindingConstraintsTSNumberData& bcGroup() { return rules_->binding_constraints; } - -private: - Rules::Ptr rules_; -}; - -// ===================== -// Simulation handler -// ===================== -using namespace Benchmarking; - -class SimulationHandler -{ -public: - SimulationHandler(Study& study) - : study_(study) - {} - ~SimulationHandler() = default; - void create(); - void run() { simulation_->run(); } - ISimulation& rawSimu() { return *simulation_; } - -private: - std::shared_ptr> simulation_; - NullDurationCollector nullDurationCollector_; - Settings settings_; - Study& study_; - NullResultWriter resultWriter_; -}; - - -// ========================= -// Basic study builder -// ========================= - -struct StudyBuilder -{ - StudyBuilder(); - - void simulationBetweenDays(const unsigned int firstDay, const unsigned int lastDay); - Area* addAreaToStudy(const std::string& areaName); - void setNumberMCyears(unsigned int nbYears); - void playOnlyYear(unsigned int year); - void giveWeightToYear(float weight, unsigned int year); - - // Data members - std::shared_ptr study; - std::shared_ptr simulation; -}; - -std::shared_ptr addBindingConstraints(Antares::Data::Study& study, std::string name, std::string group); diff --git a/src/tests/inmemory-study/CMakeLists.txt b/src/tests/inmemory-study/CMakeLists.txt new file mode 100644 index 0000000000..bb7cd26e13 --- /dev/null +++ b/src/tests/inmemory-study/CMakeLists.txt @@ -0,0 +1,26 @@ +add_library(in-memory-study) +add_library(Antares::tests::in-memory-study ALIAS in-memory-study) + +target_sources(in-memory-study + PRIVATE + in-memory-study.cpp + include/in-memory-study.h +) + +target_link_libraries(in-memory-study + PUBLIC + ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} + antares-solver-simulation + Antares::application + PRIVATE + Antares::infoCollection +) + +target_include_directories(in-memory-study + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/include +) + +set_target_properties(in-memory-study PROPERTIES FOLDER Unit-tests) + +target_include_directories(in-memory-study PUBLIC ${Boost_INCLUDE_DIRS}) diff --git a/src/tests/inmemory-study/in-memory-study.cpp b/src/tests/inmemory-study/in-memory-study.cpp new file mode 100644 index 0000000000..30efd246bf --- /dev/null +++ b/src/tests/inmemory-study/in-memory-study.cpp @@ -0,0 +1,275 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define WIN32_LEAN_AND_MEAN + +#include "in-memory-study.h" + +#include "antares/application/ScenarioBuilderOwner.h" + +void initializeStudy(Study* study) +{ + study->parameters.reset(); +} + +void configureLinkCapacities(AreaLink* link) +{ + const double linkCapacityInfinite = +std::numeric_limits::infinity(); + link->directCapacities.resize(1, 8760); + link->directCapacities.fill(linkCapacityInfinite); + + link->indirectCapacities.resize(1, 8760); + link->indirectCapacities.fill(linkCapacityInfinite); +} + +std::shared_ptr addClusterToArea(Area* area, const std::string& clusterName) +{ + auto cluster = std::make_shared(area); + cluster->setName(clusterName); + cluster->reset(); + + area->thermal.list.addToCompleteList(cluster); + + return cluster; +} + +void addScratchpadToEachArea(Study& study) +{ + for (auto& [_, area]: study.areas) + { + for (unsigned int i = 0; i < study.maxNbYearsInParallel; ++i) + { + area->scratchpad.emplace_back(*study.runtime, *area); + } + } +} + +// Name should be changed to setTSSize +TimeSeriesConfigurer& TimeSeriesConfigurer::setColumnCount(unsigned int columnCount, + unsigned rowCount) +{ + ts_->resize(columnCount, rowCount); + return *this; +} + +TimeSeriesConfigurer& TimeSeriesConfigurer::fillColumnWith(unsigned int column, double value) +{ + ts_->fillColumn(column, value); + return *this; +} + +ThermalClusterConfig::ThermalClusterConfig(ThermalCluster* cluster): + cluster_(cluster), + tsAvailablePowerConfig_(cluster_->series.timeSeries) +{ +} + +ThermalClusterConfig& ThermalClusterConfig::setNominalCapacity(double nominalCapacity) +{ + cluster_->nominalCapacity = nominalCapacity; + return *this; +} + +ThermalClusterConfig& ThermalClusterConfig::setUnitCount(unsigned int unitCount) +{ + cluster_->unitCount = unitCount; + return *this; +} + +ThermalClusterConfig& ThermalClusterConfig::setCosts(double cost) +{ + cluster_->marginalCost = cost; + cluster_->marketBidCost = cost; // Must define market bid cost otherwise all production is used + return *this; +} + +ThermalClusterConfig& ThermalClusterConfig::setAvailablePowerNumberOfTS(unsigned int columnCount) +{ + tsAvailablePowerConfig_.setColumnCount(columnCount); + return *this; +} + +ThermalClusterConfig& ThermalClusterConfig::setAvailablePower(unsigned int column, double value) +{ + tsAvailablePowerConfig_.fillColumnWith(column, value); + return *this; +} + +// ------------------------------- +// Simulation results retrieval +// ------------------------------- +averageResults OutputRetriever::overallCost(Area* area) +{ + auto result = retrieveAreaResults(area); + return averageResults(result->avgdata); +} + +averageResults OutputRetriever::levelForSTSgroup(Area* area, unsigned int groupNb) +{ + auto result = retrieveAreaResults(area); + unsigned int levelIndex = groupNb * 3 + 2; + return result[area->index][levelIndex].avgdata; +} + +averageResults OutputRetriever::load(Area* area) +{ + auto result = retrieveAreaResults(area); + return averageResults(result->avgdata); +} + +averageResults OutputRetriever::hydroStorage(Area* area) +{ + auto result = retrieveAreaResults(area); + return averageResults(result->avgdata); +} + +averageResults OutputRetriever::flow(AreaLink* link) +{ + // There is a problem here : + // we cannot easly retrieve the hourly flow for a link and a year : + // - Functions retrieveHourlyResultsForCurrentYear are not coded everywhere it should. + // - Even if those functions were correctly implemented, there is another problem : + // Each year results erase results of previous year, how can we retrieve results of year 1 + // if 2 year were run ? + // We should be able to run each year independently, which is not possible now. + // A workaround is to retrieve syntheses, and that's what we do here. + + auto result = retrieveLinkResults(link); + return averageResults(result->avgdata); +} + +averageResults OutputRetriever::thermalGeneration(ThermalCluster* cluster) +{ + auto result = retrieveResultsForThermalCluster< + Variable::Economy::VCardProductionByDispatchablePlant>(cluster); + return averageResults((*result)[cluster->areaWideIndex].avgdata); +} + +averageResults OutputRetriever::thermalNbUnitsON(ThermalCluster* cluster) +{ + auto result = retrieveResultsForThermalCluster< + Variable::Economy::VCardNbOfDispatchedUnitsByPlant>(cluster); + return averageResults((*result)[cluster->areaWideIndex].avgdata); +} + +ScenarioBuilderRule::ScenarioBuilderRule(Study& study) +{ + study.scenarioRulesCreate(); + ScenarioBuilder::Sets* sets = study.scenarioRules; + if (sets && !sets->empty()) + { + rules_ = sets->createNew("Custom"); + + study.parameters.useCustomScenario = true; + study.parameters.activeRulesScenario = "Custom"; + } +} + +// ===================== +// Simulation handler +// ===================== + +void SimulationHandler::create() +{ + study_.initializeRuntimeInfos(); + addScratchpadToEachArea(study_); + simulation_ = std::make_shared>(study_, + settings_, + durationCollector_, + resultWriter_, + observer_); + Antares::Solver::ScenarioBuilderOwner(study_).callScenarioBuilder(); + + SIM_AllocationTableaux(study_); +} + +// ========================= +// Basic study builder +// ========================= +StudyBuilder::StudyBuilder() +{ + // Make logs shrink to errors (and higher) only + logs.verbosityLevel = Logs::Verbosity::Error::level; + + study = std::make_unique(true); + simulation = std::make_shared(*study); + + initializeStudy(study.get()); +} + +void StudyBuilder::simulationBetweenDays(const unsigned int firstDay, const unsigned int lastDay) +{ + study->parameters.simulationDays.first = firstDay; + study->parameters.simulationDays.end = lastDay; +} + +void StudyBuilder::setNumberMCyears(unsigned int nbYears) +{ + study->parameters.resetPlaylist(nbYears); + study->areas.resizeAllTimeseriesNumbers(nbYears); + study->areas.each([&](Data::Area& area) + { area.hydro.deltaBetweenFinalAndInitialLevels.resize(nbYears); }); +} + +void StudyBuilder::playOnlyYear(unsigned int year) +{ + auto& params = study->parameters; + + params.userPlaylist = true; + std::fill(params.yearsFilter.begin(), params.yearsFilter.end(), false); + params.yearsFilter[year] = true; +} + +void StudyBuilder::giveWeightToYear(float weight, unsigned int year) +{ + study->parameters.setYearWeight(year, weight); + + // Activate playlist, otherwise previous sets won't have any effect + study->parameters.userPlaylist = true; +} + +Area* StudyBuilder::addAreaToStudy(const std::string& areaName) +{ + Area* area = addAreaToListOfAreas(study->areas, areaName); + + // Default values for the area + area->createMissingData(); + area->resetToDefaultValues(); + + // Temporary : we want to give a high unsupplied or spilled energy costs. + // Which cost should we give ? + area->thermal.unsuppliedEnergyCost = 1000.0; + area->thermal.spilledEnergyCost = 1000.0; + + study->areas.rebuildIndexes(); + + return area; +} + +std::shared_ptr addBindingConstraints(Study& study, + std::string name, + std::string group) +{ + auto bc = study.bindingConstraints.add(name); + bc->group(group); + auto g = study.bindingConstraintsGroups.add(group); + g->add(bc); + return bc; +} diff --git a/src/tests/inmemory-study/include/in-memory-study.h b/src/tests/inmemory-study/include/in-memory-study.h new file mode 100644 index 0000000000..920d28f261 --- /dev/null +++ b/src/tests/inmemory-study/include/in-memory-study.h @@ -0,0 +1,237 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#pragma once +#define WIN32_LEAN_AND_MEAN +#include "antares/solver/simulation/economy.h" +#include "antares/solver/simulation/simulation.h" +#include "antares/study/scenario-builder/rules.h" +#include "antares/study/scenario-builder/sets.h" +#include "antares/study/study.h" + +using namespace Antares::Solver; +using namespace Antares::Solver::Simulation; +using namespace Antares::Data::ScenarioBuilder; + +void initializeStudy(Study* study); +void configureLinkCapacities(AreaLink* link); + +class TimeSeriesConfigurer +{ +public: + TimeSeriesConfigurer() = default; + + TimeSeriesConfigurer(Matrix<>& matrix): + ts_(&matrix) + { + } + + TimeSeriesConfigurer& setColumnCount(unsigned int columnCount, + unsigned rowCount = HOURS_PER_YEAR); + TimeSeriesConfigurer& fillColumnWith(unsigned int column, double value); + +private: + Matrix<>* ts_ = nullptr; +}; + +class ThermalClusterConfig +{ +public: + ThermalClusterConfig() = default; + ThermalClusterConfig(ThermalCluster* cluster); + ThermalClusterConfig& setNominalCapacity(double nominalCapacity); + ThermalClusterConfig& setUnitCount(unsigned int unitCount); + ThermalClusterConfig& setCosts(double cost); + ThermalClusterConfig& setAvailablePowerNumberOfTS(unsigned int columnCount); + ThermalClusterConfig& setAvailablePower(unsigned int column, double value); + +private: + ThermalCluster* cluster_ = nullptr; + TimeSeriesConfigurer tsAvailablePowerConfig_; +}; + +std::shared_ptr addClusterToArea(Area* area, const std::string& clusterName); +void addScratchpadToEachArea(Study& study); + +// ------------------------------- +// Simulation results retrieval +// ------------------------------- +class averageResults +{ +public: + averageResults(Variable::R::AllYears::AverageData& averageResults): + averageResults_(averageResults) + { + } + + double hour(unsigned int hour) + { + return averageResults_.hourly[hour]; + } + + double day(unsigned int day) + { + return averageResults_.daily[day]; + } + + double week(unsigned int week) + { + return averageResults_.weekly[week]; + } + +private: + Variable::R::AllYears::AverageData& averageResults_; +}; + +class OutputRetriever +{ +public: + OutputRetriever(ISimulation& simulation): + simulation_(simulation) + { + } + + averageResults overallCost(Area* area); + averageResults levelForSTSgroup(Area* area, unsigned int groupNb); + averageResults load(Area* area); + averageResults hydroStorage(Area* area); + averageResults flow(AreaLink* link); + averageResults thermalGeneration(ThermalCluster* cluster); + averageResults thermalNbUnitsON(ThermalCluster* cluster); + +private: + template + typename Variable::Storage::ResultsType* retrieveAreaResults(Area* area); + + template + typename Variable::Storage::ResultsType* retrieveLinkResults(AreaLink* link); + + template + typename Variable::Storage::ResultsType* retrieveResultsForThermalCluster( + ThermalCluster* cluster); + + ISimulation& simulation_; +}; + +template +typename Variable::Storage::ResultsType* OutputRetriever::retrieveAreaResults(Area* area) +{ + typename Variable::Storage::ResultsType* result = nullptr; + simulation_.variables.retrieveResultsForArea(&result, area); + return result; +} + +template +typename Variable::Storage::ResultsType* OutputRetriever::retrieveLinkResults(AreaLink* link) +{ + typename Variable::Storage::ResultsType* result = nullptr; + simulation_.variables.retrieveResultsForLink(&result, link); + return result; +} + +template +typename Variable::Storage::ResultsType* OutputRetriever::retrieveResultsForThermalCluster( + ThermalCluster* cluster) +{ + typename Variable::Storage::ResultsType* result = nullptr; + simulation_.variables.retrieveResultsForThermalCluster(&result, cluster); + return result; +} + +class ScenarioBuilderRule +{ +public: + ScenarioBuilderRule(Study& study); + + loadTSNumberData& load() + { + return rules_->load; + } + + BindingConstraintsTSNumberData& bcGroup() + { + return rules_->binding_constraints; + } + + hydroTSNumberData& hydro() + { + return rules_->hydro; + } + +private: + Rules::Ptr rules_; +}; + +// ===================== +// Simulation handler +// ===================== + +class SimulationHandler +{ +public: + SimulationHandler(Study& study): + study_(study) + { + } + + ~SimulationHandler() = default; + void create(); + + void run() + { + simulation_->run(); + } + + ISimulation& rawSimu() + { + return *simulation_; + } + +private: + std::shared_ptr> simulation_; + Benchmarking::DurationCollector durationCollector_; + Settings settings_; + Study& study_; + NullResultWriter resultWriter_; + NullSimulationObserver observer_; +}; + +// ========================= +// Basic study builder +// ========================= + +struct StudyBuilder +{ + StudyBuilder(); + + void simulationBetweenDays(const unsigned int firstDay, const unsigned int lastDay); + Area* addAreaToStudy(const std::string& areaName); + void setNumberMCyears(unsigned int nbYears); + void playOnlyYear(unsigned int year); + void giveWeightToYear(float weight, unsigned int year); + + // Data members + std::unique_ptr study; + std::shared_ptr simulation; +}; + +std::shared_ptr addBindingConstraints(Antares::Data::Study& study, + std::string name, + std::string group); diff --git a/src/tests/run-study-tests/actions_on_study/study_run.py b/src/tests/run-study-tests/actions_on_study/study_run.py index 2eec19336b..9abafdb066 100644 --- a/src/tests/run-study-tests/actions_on_study/study_run.py +++ b/src/tests/run-study-tests/actions_on_study/study_run.py @@ -1,14 +1,16 @@ import subprocess +import os from pathlib import Path from utils.assertions import check class study_run: - def __init__(self, study_path, solver_path, use_ortools, ortools_solver, named_mps_problems): + def __init__(self, study_path, solver_path, use_ortools, ortools_solver, named_mps_problems, parallel): self.study_path = study_path self.solver_path = solver_path self.use_ortools = use_ortools self.ortools_solver = ortools_solver self.named_mps_problems = named_mps_problems + self.parallel = parallel self.raise_exception_on_failure = True self.return_code = 0 @@ -26,6 +28,9 @@ def run(self): command.append('--ortools-solver=' + self.ortools_solver) if self.named_mps_problems: command.append('--named-mps-problems') + if self.parallel: + command.append('--force-parallel=4') + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) process.communicate() diff --git a/src/tests/run-study-tests/antares_tools/ts-generator/CMakeLists.txt b/src/tests/run-study-tests/antares_tools/ts-generator/CMakeLists.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/tests/run-study-tests/antares_tools/ts-generator/conftest.py b/src/tests/run-study-tests/antares_tools/ts-generator/conftest.py new file mode 100644 index 0000000000..3eb8e98ff7 --- /dev/null +++ b/src/tests/run-study-tests/antares_tools/ts-generator/conftest.py @@ -0,0 +1,8 @@ +import pytest + +def pytest_addoption(parser): + parser.addoption("--tsgenerator_path", action="store", default="") + +@pytest.fixture +def tsgenerator_path(request): + return request.config.getoption("--tsgenerator_path") diff --git a/src/tests/run-study-tests/antares_tools/ts-generator/pytest.ini b/src/tests/run-study-tests/antares_tools/ts-generator/pytest.ini new file mode 100644 index 0000000000..aee08ad8a7 --- /dev/null +++ b/src/tests/run-study-tests/antares_tools/ts-generator/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +markers = + tsgenerator: Run the timeseries generator, checks results diff --git a/src/tests/run-study-tests/antares_tools/ts-generator/ts-generator.py b/src/tests/run-study-tests/antares_tools/ts-generator/ts-generator.py new file mode 100755 index 0000000000..6a11c551db --- /dev/null +++ b/src/tests/run-study-tests/antares_tools/ts-generator/ts-generator.py @@ -0,0 +1,52 @@ +import pytest +import subprocess +import sys + +from pathlib import Path +from utils.find_output import find_dated_output_folder +from utils.find_reference import find_reference_folder +from parse_studies.look_for_studies import look_for_studies + +def get_ts_files(path): + ts_files = list(path.glob('**/*.txt')) + assert ts_files + return ts_files + +def get_clusters_to_gen(path): + cluster_to_gen_file = open(path / "clustersToGen.txt", 'r') + line = cluster_to_gen_file.readline().rstrip() # remove new line char + cluster_to_gen_file.close() + return line + +def run_and_compare(exe, path): + clusters_to_gen_arg = get_clusters_to_gen(path) + + res = subprocess.run([exe, clusters_to_gen_arg, path]) + assert (res.returncode == 0), "The exec failed for study: " + str(path) + + ref_path = Path(find_reference_folder(path)) / "ts-generator" + out_path = Path(find_dated_output_folder(path)) / "ts-generator" + + ref_ts_files = get_ts_files(ref_path) + ts_files = get_ts_files(out_path) + + # get pairs of same file to compare + # we need to have the correct cluster and area pair, that's why we check ts.parent + list_of_pairs = [(ts_ref, ts) for ts_ref in ref_ts_files for ts in ts_files if ts_ref.name == ts.name and ts_ref.parent.name == ts.parent.name] + assert list_of_pairs + + for pair in list_of_pairs: + ref_content = open(pair[0]).read() + output_content = open(pair[1]).read() + assert ref_content == output_content, "Difference between files {pair[0]} and {pair[1]}" + + + +# main: get studies and iterate on them +ROOT_FOLDER = Path('../resources/batches').resolve() +study_paths = look_for_studies(ROOT_FOLDER) + +@pytest.mark.tsgenerator +def test_ts_generator(tsgenerator_path): + for study in study_paths: + run_and_compare(tsgenerator_path, study) diff --git a/src/tests/run-study-tests/conftest.py b/src/tests/run-study-tests/conftest.py index cf88f051d2..f38b048ca0 100644 --- a/src/tests/run-study-tests/conftest.py +++ b/src/tests/run-study-tests/conftest.py @@ -5,6 +5,8 @@ def pytest_addoption(parser): parser.addoption("--ortools-solver", action="store", default="sirius") parser.addoption("--solver-path", action="store") parser.addoption("--named-mps-problems", action="store_true", default=False) + parser.addoption("--force-parallel", action="store_true", default=False) + parser.addoption("--ts-generator", action="store_true", default=False) @pytest.fixture() def ortools_solver(request): @@ -13,11 +15,15 @@ def ortools_solver(request): @pytest.fixture() def use_ortools(request): return request.config.getoption("--use-ortools") - + @pytest.fixture() def solver_path(request): return request.config.getoption("--solver-path") - + @pytest.fixture() def named_mps_problems(request): return request.config.getoption("--named-mps-problems") + +@pytest.fixture() +def parallel(request): + return request.config.getoption("--force-parallel") diff --git a/src/tests/run-study-tests/fixtures.py b/src/tests/run-study-tests/fixtures.py index b37cfda2c4..5f4945f379 100644 --- a/src/tests/run-study-tests/fixtures.py +++ b/src/tests/run-study-tests/fixtures.py @@ -40,8 +40,8 @@ def resultsRemover(study_path): return results_remover(study_path) @pytest.fixture -def simulation(study_path, solver_path, use_ortools, ortools_solver, named_mps_problems): - return study_run(study_path, solver_path, use_ortools, ortools_solver, named_mps_problems) +def simulation(study_path, solver_path, use_ortools, ortools_solver, named_mps_problems, parallel): + return study_run(study_path, solver_path, use_ortools, ortools_solver, named_mps_problems, parallel) @pytest.fixture(autouse=True) def check_runner(simulation, resultsRemover): diff --git a/src/tests/run-study-tests/parse_studies/json_schema.json b/src/tests/run-study-tests/parse_studies/json_schema.json index 6bf3e8a74b..0504760208 100644 --- a/src/tests/run-study-tests/parse_studies/json_schema.json +++ b/src/tests/run-study-tests/parse_studies/json_schema.json @@ -82,4 +82,4 @@ } } } -} \ No newline at end of file +} diff --git a/src/tests/run-study-tests/pytest.ini b/src/tests/run-study-tests/pytest.ini index 48d37f5875..e30ec39c1a 100644 --- a/src/tests/run-study-tests/pytest.ini +++ b/src/tests/run-study-tests/pytest.ini @@ -4,4 +4,4 @@ addopts = --tb=line -v -s markers = unfeasible: Unfeasible problems json: Collect JSON config files and run tests accordingly - mps: Compare mps files to a reference \ No newline at end of file + mps: Compare mps files to a reference diff --git a/src/tests/run-study-tests/utils/find_output.py b/src/tests/run-study-tests/utils/find_output.py index 604835ff80..3357076157 100644 --- a/src/tests/run-study-tests/utils/find_output.py +++ b/src/tests/run-study-tests/utils/find_output.py @@ -1,7 +1,5 @@ from re import match -from os.path import isdir, basename -from os import walk -from pathlib import Path +import pathlib, os from utils.assertions import check @@ -11,11 +9,9 @@ def __init__(self, study_path): self.found_dir_path = None def find(self): - for element in self.output_folder.iterdir(): - if isdir(element) and match('[0-9]{8}-[0-9]{4}', basename(element)): - self.found_dir_path = element - return True - return False + dirs = pathlib.Path(self.output_folder).glob('*/') + self.found_dir_path = max(dirs, key=os.path.getmtime) + return True def get(self): return self.found_dir_path @@ -29,7 +25,7 @@ def find_dated_output_folder(study_path): def find_simulation_folder(output_dir): # Return full path of the ouptut simulation path (can be "adequacy", "economy") - for root, dirs, files in walk(output_dir): - if basename(root) in ["adequacy", "economy"]: - return Path(root) + for root, dirs, files in os.walk(output_dir): + if os.path.basename(root) in ["adequacy", "economy"]: + return pathlib.Path(root) diff --git a/src/tests/src/CMakeLists.txt b/src/tests/src/CMakeLists.txt index f6275f8386..14c9929f56 100644 --- a/src/tests/src/CMakeLists.txt +++ b/src/tests/src/CMakeLists.txt @@ -1,3 +1,5 @@ +add_subdirectory(api_internal) +add_subdirectory(api_lib) add_subdirectory(utils) add_subdirectory(libs) diff --git a/src/tests/src/api_internal/CMakeLists.txt b/src/tests/src/api_internal/CMakeLists.txt new file mode 100644 index 0000000000..2186dc6f4b --- /dev/null +++ b/src/tests/src/api_internal/CMakeLists.txt @@ -0,0 +1,27 @@ +set(EXECUTABLE_NAME test-api) +add_executable(${EXECUTABLE_NAME}) + +target_sources(${EXECUTABLE_NAME} + PRIVATE + test_api.cpp +) + +target_link_libraries(${EXECUTABLE_NAME} + PRIVATE + Boost::unit_test_framework + Antares::solver_api + Antares::tests::in-memory-study +) + +target_include_directories(${EXECUTABLE_NAME} + PRIVATE + #Allow to use the private headers + $ +) + +# Storing tests-ts-numbers under the folder Unit-tests in the IDE +set_target_properties(${EXECUTABLE_NAME} PROPERTIES FOLDER Unit-tests) + +add_test(NAME test-api COMMAND ${EXECUTABLE_NAME}) + +set_property(TEST test-api PROPERTY LABELS unit) diff --git a/src/tests/src/api_internal/test_api.cpp b/src/tests/src/api_internal/test_api.cpp new file mode 100644 index 0000000000..d60f6315d5 --- /dev/null +++ b/src/tests/src/api_internal/test_api.cpp @@ -0,0 +1,96 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test_api +#define WIN32_LEAN_AND_MEAN + +#include + +#include + +#include "API.h" +#include "in-memory-study.h" + +class InMemoryStudyLoader: public Antares::IStudyLoader +{ +public: + explicit InMemoryStudyLoader(bool success = true): + success_(success){}; + + [[nodiscard]] std::unique_ptr load() const override + { + if (!success_) + { + return nullptr; + } + StudyBuilder builder; + builder.addAreaToStudy("area1"); + builder.addAreaToStudy("area2"); + builder.setNumberMCyears(1); + builder.study->initializeRuntimeInfos(); + builder.study->parameters.resultFormat = ResultFormat::inMemory; + builder.study->prepareOutput(); + return std::move(builder.study); + } + + bool success_ = true; +}; + +BOOST_AUTO_TEST_CASE(simulation_path_points_to_results) +{ + Antares::API::APIInternal api; + auto study_loader = std::make_unique(); + auto results = api.run(*study_loader.get()); + BOOST_CHECK_EQUAL(results.simulationPath, std::filesystem::path{"no_output"}); + // Testing for "no_output" is a bit weird, but it's the only way to test this without actually + // running the simulation +} + +BOOST_AUTO_TEST_CASE(api_run_contains_antares_problem) +{ + Antares::API::APIInternal api; + auto study_loader = std::make_unique(); + auto results = api.run(*study_loader.get()); + + BOOST_CHECK(!results.antares_problems.empty()); + BOOST_CHECK(!results.error); +} + +BOOST_AUTO_TEST_CASE(result_failure_when_study_is_null) +{ + Antares::API::APIInternal api; + auto study_loader = std::make_unique(false); + auto results = api.run(*study_loader.get()); + + BOOST_CHECK(results.error); +} + +// Test where data in problems are consistant with data in study +BOOST_AUTO_TEST_CASE(result_contains_problems) +{ + Antares::API::APIInternal api; + auto study_loader = std::make_unique(); + auto results = api.run(*study_loader.get()); + + BOOST_CHECK(!results.antares_problems.empty()); + BOOST_CHECK(!results.error); + BOOST_CHECK_EQUAL(results.antares_problems.weeklyProblems.size(), 52); +} diff --git a/src/tests/src/api_lib/CMakeLists.txt b/src/tests/src/api_lib/CMakeLists.txt new file mode 100644 index 0000000000..b5ce633955 --- /dev/null +++ b/src/tests/src/api_lib/CMakeLists.txt @@ -0,0 +1,20 @@ +set(EXECUTABLE_NAME test-client-api) +add_executable(${EXECUTABLE_NAME}) + +target_sources(${EXECUTABLE_NAME} + PRIVATE + test_api.cpp +) + +target_link_libraries(${EXECUTABLE_NAME} + PRIVATE + Boost::unit_test_framework + Antares::solver_api +) + +# Storing tests-ts-numbers under the folder Unit-tests in the IDE +set_target_properties(${EXECUTABLE_NAME} PROPERTIES FOLDER Unit-tests) + +add_test(NAME test-client-api COMMAND ${EXECUTABLE_NAME}) + +set_property(TEST test-client-api PROPERTY LABELS unit) diff --git a/src/tests/src/api_lib/test_api.cpp b/src/tests/src/api_lib/test_api.cpp new file mode 100644 index 0000000000..0dbddfae7f --- /dev/null +++ b/src/tests/src/api_lib/test_api.cpp @@ -0,0 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test_api +#define WIN32_LEAN_AND_MEAN + +#include + +#include "antares/api/solver.h" + +BOOST_AUTO_TEST_CASE(result_failure_when_study_path_invalid) +{ + using namespace std::string_literals; + auto results = Antares::API::PerformSimulation("dummy"s); + BOOST_CHECK(results.error); + BOOST_CHECK(!results.error->reason.empty()); +} diff --git a/src/tests/src/libs/CMakeLists.txt b/src/tests/src/libs/CMakeLists.txt index b97a7df1bc..81b6173280 100644 --- a/src/tests/src/libs/CMakeLists.txt +++ b/src/tests/src/libs/CMakeLists.txt @@ -1,2 +1,2 @@ -add_subdirectory(antares) \ No newline at end of file +add_subdirectory(antares) diff --git a/src/tests/src/libs/antares/CMakeLists.txt b/src/tests/src/libs/antares/CMakeLists.txt index a6771db392..875ff5e374 100644 --- a/src/tests/src/libs/antares/CMakeLists.txt +++ b/src/tests/src/libs/antares/CMakeLists.txt @@ -1,16 +1,25 @@ add_subdirectory(concurrency) add_subdirectory(writer) add_subdirectory(study) +add_subdirectory(benchmarking) +add_subdirectory(inifile) -set(src_libs_antares "${CMAKE_SOURCE_DIR}/libs/antares") +if(WITH_YAMLCPP) + add_subdirectory(yaml-parser) +endif() + +if(WITH_ANTLR4) + add_subdirectory(antlr4-interface) +endif() +set(src_libs_antares "${CMAKE_SOURCE_DIR}/libs/antares") # Adding a library embedding all Antares sources useful to test class Matrix set(SRC_MATRIX_LIB # For confort in IDE, but not necessary - ${src_libs_antares}/array/antares/array/matrix.h - ${src_libs_antares}/array/antares/array/matrix.hxx + ${src_libs_antares}/array/include/antares/array/matrix.h + ${src_libs_antares}/array/include/antares/array/matrix.hxx # Necessary cpp files ${src_libs_antares}/jit/jit.cpp @@ -27,6 +36,7 @@ target_link_libraries(matrix target_include_directories(matrix PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/logs" + "${src_libs_antares}/jit/include" ) # Storing lib-matrix under the folder Unit-tests in the IDE @@ -45,9 +55,9 @@ add_executable(tests-matrix-save ${SRC_TEST_MATRIX_SAVE}) target_include_directories(tests-matrix-save PRIVATE - "${src_libs_antares}/array" - "${src_libs_antares}/io" - "${src_libs_antares}/jit" + "${src_libs_antares}/array/include" + "${src_libs_antares}/io/include" + "${src_libs_antares}/jit/include" "${src_libs_antares}/memory/include" "${CMAKE_CURRENT_SOURCE_DIR}/logs" "${CMAKE_CURRENT_SOURCE_DIR}/jit" @@ -60,6 +70,7 @@ target_link_libraries(tests-matrix-save matrix yuni-static-core Boost::unit_test_framework + antares-core ) # Storing tests-matrix-save under the folder Unit-tests in the IDE @@ -80,9 +91,9 @@ set(SRC_TEST_MATRIX_LOAD add_executable(tests-matrix-load ${SRC_TEST_MATRIX_LOAD}) target_include_directories(tests-matrix-load PRIVATE - "${src_libs_antares}/array" - "${src_libs_antares}/io" - "${src_libs_antares}/jit" + "${src_libs_antares}/array/include" + "${src_libs_antares}/io/include" + "${src_libs_antares}/jit/include" "${src_libs_antares}/memory/include" "${CMAKE_CURRENT_SOURCE_DIR}/logs" "${CMAKE_CURRENT_SOURCE_DIR}/jit" @@ -95,6 +106,7 @@ target_link_libraries(tests-matrix-load matrix yuni-static-core Boost::unit_test_framework + antares-core ) # Storing tests-matrix-load under the folder Unit-tests in the IDE @@ -112,5 +124,7 @@ target_link_libraries(test-utils Antares::utils yuni-static-core ) -add_test(NAME test-utils COMMAND test-utils) +set_target_properties(test-utils PROPERTIES FOLDER Unit-tests/test-utils) +add_test(NAME test-utils COMMAND test-utils) +set_property(TEST test-utils PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/antlr4-interface/CMakeLists.txt b/src/tests/src/libs/antares/antlr4-interface/CMakeLists.txt new file mode 100644 index 0000000000..f74e12981c --- /dev/null +++ b/src/tests/src/libs/antares/antlr4-interface/CMakeLists.txt @@ -0,0 +1,20 @@ + +find_package(antlr4-runtime CONFIG REQUIRED) +Set(SRCS test_antlr_interface.cpp +) + +set(execname "antlr-interface-test") +add_executable(${execname} ${SRCS}) +target_link_libraries(${execname} + PRIVATE + antlr-interface + Boost::unit_test_framework + ) + + +target_include_directories(${execname} + PRIVATE + ${ANTLR4_INCLUDE_DIR}) +add_test(NAME antlr-interface COMMAND ${execname}) + +set_tests_properties(antlr-interface PROPERTIES LABELS unit) diff --git a/src/tests/src/libs/antares/antlr4-interface/test_antlr_interface.cpp b/src/tests/src/libs/antares/antlr4-interface/test_antlr_interface.cpp new file mode 100644 index 0000000000..04d1c7be9f --- /dev/null +++ b/src/tests/src/libs/antares/antlr4-interface/test_antlr_interface.cpp @@ -0,0 +1,41 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#define BOOST_TEST_MODULE antlr_interface tests +#include + +#include +#include + +#include "ExprLexer.h" +#include "ExprParser.h" +#include "antlr4-runtime.h" + +using namespace antlr4; + +BOOST_AUTO_TEST_CASE(test_antlr_interface) +{ + const std::string my_input = "y = b + a*x"; + ANTLRInputStream input(my_input); + ExprLexer lexer(&input); + CommonTokenStream tokens(&lexer); + tokens.fill(); + BOOST_CHECK(tokens.getTokens().size() == 8); +} diff --git a/src/tests/src/libs/antares/array/fill-matrix.h b/src/tests/src/libs/antares/array/fill-matrix.h index 79a69b4929..29681740e3 100644 --- a/src/tests/src/libs/antares/array/fill-matrix.h +++ b/src/tests/src/libs/antares/array/fill-matrix.h @@ -1,52 +1,72 @@ - +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_LIBS_ARRAY_MATRIX_FILL_MTX_H__ #define __ANTARES_LIBS_ARRAY_MATRIX_FILL_MTX_H__ -#include #include +#include + +#include + using namespace std; using namespace Antares; -namespace Antares -{ -namespace Statistics -{ -void HasWrittenToDisk(uint64_t /* size */) -{ -} -} // namespace Statistics -} // namespace Antares - template -class Matrix_easy_to_fill : public Matrix +class Matrix_easy_to_fill: public Matrix { public: - Matrix_easy_to_fill() : Matrix() + Matrix_easy_to_fill(): + Matrix() { } - Matrix_easy_to_fill(uint height, uint width) : Matrix(height, width) + + Matrix_easy_to_fill(uint height, uint width): + Matrix(height, width) { } - Matrix_easy_to_fill(uint height, uint width, const vector& vec) : Matrix() + Matrix_easy_to_fill(uint height, uint width, const vector& vec): + Matrix() { BOOST_REQUIRE_EQUAL(height * width, vec.size()); this->reset(width, height, true); uint count = 0; for (uint j = 0; j < height; j++) + { for (uint i = 0; i < width; i++) { this->entry[i][j] = vec[count]; count++; } + } } - bool openFile(Yuni::IO::File::Stream& /* file */, const AnyString& /* filename */) const override + bool openFile(Yuni::IO::File::Stream& /* file */, + const AnyString& /* filename */) const override { return true; } + void saveBufferToFile(std::string& buffer, Yuni::IO::File::Stream& /* f */) const override { data = buffer; diff --git a/src/tests/src/libs/antares/array/matrix-bypass-load.h b/src/tests/src/libs/antares/array/matrix-bypass-load.h index 521b3cb83a..c981a8d199 100644 --- a/src/tests/src/libs/antares/array/matrix-bypass-load.h +++ b/src/tests/src/libs/antares/array/matrix-bypass-load.h @@ -1,4 +1,23 @@ - +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_LIBS_ARRAY_MATRIX_BYPASS_LOAD_H__ #define __ANTARES_LIBS_ARRAY_MATRIX_BYPASS_LOAD_H__ @@ -22,29 +41,23 @@ struct PredicateIdentity } // namespace UnitTests } // namespace Antares -namespace Antares -{ -namespace Statistics -{ -void HasReadFromDisk(uint64_t /* size */) -{ -} -} // namespace Statistics -} // namespace Antares - template -class Matrix_load_bypass : public Matrix_easy_to_fill +class Matrix_load_bypass: public Matrix_easy_to_fill { using BufferType = typename Matrix::BufferType; public: - Matrix_load_bypass() : Matrix_easy_to_fill(), loadFromCSVFile_called(false){}; + Matrix_load_bypass(): + Matrix_easy_to_fill(), + loadFromCSVFile_called(false){}; - Matrix_load_bypass(uint height, uint width) : - Matrix_easy_to_fill(height, width), loadFromCSVFile_called(false){}; + Matrix_load_bypass(uint height, uint width): + Matrix_easy_to_fill(height, width), + loadFromCSVFile_called(false){}; - Matrix_load_bypass(uint height, uint width, const vector& vec) : - Matrix_easy_to_fill(height, width, vec), loadFromCSVFile_called(false){}; + Matrix_load_bypass(uint height, uint width, const vector& vec): + Matrix_easy_to_fill(height, width, vec), + loadFromCSVFile_called(false){}; bool loadFromCSVFile(const AnyString& /* filename */, uint /* minWidth */, @@ -64,7 +77,9 @@ template class fake_buffer_factory { public: - fake_buffer_factory() : buffer_precision_(0), buffer_print_dimensions_(false) + fake_buffer_factory(): + buffer_precision_(0), + buffer_print_dimensions_(false) { } @@ -74,22 +89,27 @@ class fake_buffer_factory { mtx_to_build_buffer_with_ = mtx; } + void set_precision(uint precision) { buffer_precision_ = precision; } + void print_dimensions(bool print_dims) { buffer_print_dimensions_ = print_dims; } + Clob* build_buffer() { Clob* buffer_to_return = new Clob; std::string buffer; Antares::UnitTests::PredicateIdentity predicate; - mtx_to_build_buffer_with_->saveToFileDescriptor( - buffer, buffer_precision_, buffer_print_dimensions_, predicate); + mtx_to_build_buffer_with_->saveToFileDescriptor(buffer, + buffer_precision_, + buffer_print_dimensions_, + predicate); buffer_to_return->append(buffer); @@ -103,17 +123,20 @@ class fake_buffer_factory }; template -class Matrix_mock_load_to_buffer : public Matrix +class Matrix_mock_load_to_buffer: public Matrix { public: - Matrix_mock_load_to_buffer() : - Matrix(), fake_mtx_error_when_loading_(IO::errNone){}; + Matrix_mock_load_to_buffer(): + Matrix(), + fake_mtx_error_when_loading_(IO::errNone){}; - Matrix_mock_load_to_buffer(uint height, uint width) : - Matrix(height, width), fake_mtx_error_when_loading_(IO::errNone){}; + Matrix_mock_load_to_buffer(uint height, uint width): + Matrix(height, width), + fake_mtx_error_when_loading_(IO::errNone){}; - Matrix_mock_load_to_buffer(uint height, uint width, const vector& vec) : - Matrix(height, width, vec), fake_mtx_error_when_loading_(IO::errNone){}; + Matrix_mock_load_to_buffer(uint height, uint width, const vector& vec): + Matrix(height, width, vec), + fake_mtx_error_when_loading_(IO::errNone){}; IO::Error loadFromFileToBuffer(typename Matrix::BufferType& /* buffer */, const AnyString& /* filename */) const override diff --git a/src/tests/src/libs/antares/array/tests-matrix-load.cpp b/src/tests/src/libs/antares/array/tests-matrix-load.cpp index 31a209c67b..2c427890eb 100644 --- a/src/tests/src/libs/antares/array/tests-matrix-load.cpp +++ b/src/tests/src/libs/antares/array/tests-matrix-load.cpp @@ -1,48 +1,68 @@ -#define BOOST_TEST_MODULE test-lib-antares-matrix tests -#define BOOST_TEST_DYN_LINK +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test - lib - antares - matrix tests #define WIN32_LEAN_AND_MEAN -#include - #include "tests-matrix-load.h" -#include #include +#include #include +#include + namespace utf = boost::unit_test; using namespace Yuni; /* All loadFromCSVFile(...) entries (some directions to test this big method): - 0. Global JIT::enabled state : on or off - 1. file to be loaded (= buffer) : - a. empty - b. contains the head banner 'size:nxm' or not - c. contains digits (which precision) or integers. - d. full of zeros, - e. full of numbers (> 0 or < 0) - f. strange cases - 2. Initial matrix state (matrix state when loadFromCSVFile(...) is called) : - a. empty - b. sized n x m - c. state of the jit - 3. loadFromBuffer(...) method arguments : - a. desired final matrix size (minWidth & maxHeight) - b. options : - + optNone = 0, //! None - + optFixedSize = 1, //! The matrix can not see its size modified - + optQuiet = 2, //! Do not produce warnings/errors - + optImmediate = 4, //! Do not postpone the loading - + optMarkAsModified = 8, //! mark the matrix as modified after loading - + optNoWarnIfEmpty = 16, //! Do not warn if the file is empty - + optNeverFails = 32, //! The loading never fails - 4. Error type returned by loadFromFileToBuffer(...) + 0. Global JIT::enabled state : on or off + 1. file to be loaded (= buffer) : + a. empty + b. contains the head banner 'size:nxm' or not + c. contains digits (which precision) or integers. + d. full of zeros, + e. full of numbers (> 0 or < 0) + f. strange cases + 2. Initial matrix state (matrix state when loadFromCSVFile(...) is called) : + a. empty + b. sized n x m + c. state of the jit + 3. loadFromBuffer(...) method arguments : + a. desired final matrix size (minWidth & maxHeight) + b. options : + + optNone = 0, //! None + + optFixedSize = 1, //! The matrix can not see its size +modified + + optQuiet = 2, //! Do not produce warnings/errors + + optImmediate = 4, //! Do not postpone the loading + + optMarkAsModified = 8, //! mark the matrix as modified after +loading + + optNoWarnIfEmpty = 16, //! Do not warn if the file is empty + + optNeverFails = 32, //! The loading never fails + 4. Error type returned by loadFromFileToBuffer(...) */ - // ================================ // === Matrix === // ================================ @@ -51,365 +71,374 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_double__load_from_double) // 1.a. BOOST_AUTO_TEST_CASE(fake_file_is_empty___target_matrix_has_only_0s) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Clob* fake_buffer = new Clob; // Empty buffer + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Clob* fake_buffer = new Clob; // Empty buffer - // Testing load - Matrix_mock_load_to_buffer mtx(2, 2); - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx(2, 2); + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_CHECK(mtx.containsOnlyZero()); } // 1.b. BOOST_AUTO_TEST_CASE(fake_file_with_banner__target_mtx_empty___mtx_gets_file_dimensions) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 3, { 1.5, -2.4444, 3.66666, 0, 8.559, -5.5555 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(1); - buffer_factory_dd.print_dimensions(true); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 3, {1.5, -2.4444, 3.66666, 0, 8.559, -5.5555}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(1); + buffer_factory_dd.print_dimensions(true); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.5); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.4); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.7); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.6); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5.6); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.5); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.4); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.7); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.6); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5.6); } // 1.c. BOOST_AUTO_TEST_CASE(fake_file_precision_is_4___matrix_precision_gets_4) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(3, 1, { 1.5554, -2.4444, 3.66666 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(4); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(3, 1, {1.5554, -2.4444, 3.66666}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(4); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 3, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 3, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 3); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.5554); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -2.4444); - BOOST_REQUIRE_EQUAL(mtx.entry[0][2], 3.6667); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 3); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.5554); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -2.4444); + BOOST_REQUIRE_EQUAL(mtx.entry[0][2], 3.6667); } // 1.c. BOOST_AUTO_TEST_CASE(fake_file_contains_int___matrix_precision_is_0) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(1, 4, { 1, -2, 3, -4 }); - fake_buffer_factory buffer_factory_ii; - buffer_factory_ii.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_ii.print_dimensions(true); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(1, 4, {1, -2, 3, -4}); + fake_buffer_factory buffer_factory_ii; + buffer_factory_ii.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_ii.print_dimensions(true); - Clob* fake_buffer = buffer_factory_ii.build_buffer(); + Clob* fake_buffer = buffer_factory_ii.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 4, 1, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 4, 1, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.height, 1); - BOOST_REQUIRE_EQUAL(mtx.width, 4); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.); - BOOST_REQUIRE_EQUAL(mtx.entry[3][0], -4.); + BOOST_REQUIRE_EQUAL(mtx.height, 1); + BOOST_REQUIRE_EQUAL(mtx.width, 4); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.); + BOOST_REQUIRE_EQUAL(mtx.entry[3][0], -4.); } // 1.d. BOOST_AUTO_TEST_CASE(fake_file_full_0s__load_mtx___mtx_contains_only_0s) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 3, {0,0,0,0,0,0}); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 3, {0, 0, 0, 0, 0, 0}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_CHECK(mtx.containsOnlyZero()); } // 1.e. BOOST_AUTO_TEST_CASE(fake_file_not_empty__target_mtx_empty___mtx_gets_file_dimensions) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 3, { 1.5, -2.44444, 3.66666, 0, 8.559, -5.5555 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(2); - buffer_factory_dd.print_dimensions(false); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 3, {1.5, -2.44444, 3.66666, 0, 8.559, -5.5555}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(2); + buffer_factory_dd.print_dimensions(false); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.5); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.44); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.67); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.56); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5.56); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.5); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.44); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.67); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.56); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5.56); } // Specific tests for renewable TS // Expected behavior : read 4 digits BOOST_AUTO_TEST_CASE(fake_file_double_renewable) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 3, { 100.5111, -2.44444, 3.66666, 0, 8.559, -5.5555 }); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, + 3, + {100.5111, -2.44444, 3.66666, 0, 8.559, -5.5555}); fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(4); - buffer_factory_dd.print_dimensions(false); + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(4); + buffer_factory_dd.print_dimensions(false); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 100.5111); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.4444); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.6667); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.559); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5.5555); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 100.5111); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.4444); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.6667); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.559); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5.5555); } // Specific tests for thermal TS // Expected behavior : read 0 digits, i.e round input to closest integer value BOOST_AUTO_TEST_CASE(fake_file_double_thermal) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 3, { 1.50001, -2.44444, 3.66666, 0, 8.559, -5.55555 }); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, + 3, + {1.50001, -2.44444, 3.66666, 0, 8.559, -5.55555}); fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(0); // default precision is 0 - buffer_factory_dd.print_dimensions(false); + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(0); // default precision is 0 + buffer_factory_dd.print_dimensions(false); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 2); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 4); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 9); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -6); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 2); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 4); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 9); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -6); } - // 1.f. BOOST_AUTO_TEST_CASE(file_with_alphabetic_char___load_fails_with_warning) { - Clob* fake_buffer = new Clob; - fake_buffer->append("1.3\tHello\n"); + Clob* fake_buffer = new Clob; + fake_buffer->append("1.3\tHello\n"); - Matrix_mock_load_to_buffer mtx; - logs.warning().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 1, Matrix<>::optNone, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + logs.warning().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 1, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(logs.warning().contains("Invalid numeric value")); + BOOST_CHECK(logs.warning().contains("Invalid numeric value")); } // 1.f. -BOOST_AUTO_TEST_CASE(binary_file___detect_encoding_when_loading_buffer_is_KO_and_is_probably_dead_code) +BOOST_AUTO_TEST_CASE( + binary_file___detect_encoding_when_loading_buffer_is_KO_and_is_probably_dead_code) { - // CAUTION : - // In load from buffer function, the code in charge to detect encoding (ex : little endian utf-16, ...) - // is dead code. It is be used, but does not seem to detect anything. - // Anyway, binary file are not used in Antares. + // CAUTION : + // In load from buffer function, the code in charge to detect encoding (ex : little endian + // utf-16, ...) is dead code. It is be used, but does not seem to detect anything. + // Anyway, binary file are not used in Antares. - // Creating an utf-16 binary file ----------------------------------------------------------- - // ... UTF-16le data (if host system is little-endian) - char16_t utf16le[4] = { 0x007a, // latin small letter 'z' U+007a - 0x6c34, // CJK ideograph "water" U+6c34 - 0xd834, 0xdd0b }; // musical sign segno U+1d10b - // ... store in a file - std::ofstream fout("text.txt"); - fout.write(reinterpret_cast(utf16le), sizeof utf16le); - fout.close(); - // ------------------------------------------------------------------------------------------ + // Creating an utf-16 binary file ----------------------------------------------------------- + // ... UTF-16le data (if host system is little-endian) + char16_t utf16le[4] = {0x007a, // latin small letter 'z' U+007a + 0x6c34, // CJK ideograph "water" U+6c34 + 0xd834, + 0xdd0b}; // musical sign segno U+1d10b + // ... store in a file + std::ofstream fout("text.txt"); + fout.write(reinterpret_cast(utf16le), sizeof utf16le); + fout.close(); + // ------------------------------------------------------------------------------------------ - Clob* fake_buffer = new Clob; + Clob* fake_buffer = new Clob; - Matrix mtx; - BOOST_CHECK(not mtx.loadFromCSVFile("text.txt", 2, 2, Matrix<>::optNone, fake_buffer)); - BOOST_CHECK(not fake_buffer->empty()); + Matrix mtx; + BOOST_CHECK(not mtx.loadFromCSVFile("text.txt", 2, 2, Matrix<>::optNone, fake_buffer)); + BOOST_CHECK(not fake_buffer->empty()); - delete fake_buffer; + delete fake_buffer; - remove("text.txt"); + remove("text.txt"); } // 1.f. BOOST_AUTO_TEST_CASE(file_with_only_charriot_return__load_fails_with_warning) { - Clob* fake_buffer = new Clob; - fake_buffer->append("\n\n"); + Clob* fake_buffer = new Clob; + fake_buffer->append("\n\n"); - Matrix_mock_load_to_buffer mtx; - logs.warning().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 1, Matrix<>::optNone, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + logs.warning().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 1, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(logs.warning().contains("Invalid format: The file seems empty")); + BOOST_CHECK(logs.warning().contains("Invalid format: The file seems empty")); } // 1.f. BOOST_AUTO_TEST_CASE(file_with_only_tabs__option_no_failure___load_fails_with_warning) { - Clob* fake_buffer = new Clob; - fake_buffer->append("\t\t\t\t"); + Clob* fake_buffer = new Clob; + fake_buffer->append("\t\t\t\t"); - Matrix_mock_load_to_buffer mtx; - logs.warning().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 1, Matrix<>::optNeverFails, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + logs.warning().clear(); + BOOST_CHECK( + not mtx.loadFromCSVFile("path/to/a/file", 2, 1, Matrix<>::optNeverFails, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(logs.warning().contains("Invalid format: The file seems empty")); + BOOST_CHECK(logs.warning().contains("Invalid format: The file seems empty")); } // 1.f. -BOOST_AUTO_TEST_CASE(file_with_no_charriot_return__option_no_failure___load_succeeds_with_warning__column_resized) +BOOST_AUTO_TEST_CASE( + file_with_no_charriot_return__option_no_failure___load_succeeds_with_warning__column_resized) { - Clob* fake_buffer = new Clob; - fake_buffer->append("1.1\t2.2\t3.3\t4.4\t"); + Clob* fake_buffer = new Clob; + fake_buffer->append("1.1\t2.2\t3.3\t4.4\t"); - Matrix_mock_load_to_buffer mtx; - logs.warning().clear(); - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNeverFails, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + logs.warning().clear(); + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNeverFails, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(logs.warning().content() == "path/to/a/file: not enough rows (expected 2, got 1)"); + BOOST_CHECK(logs.warning().content() == "path/to/a/file: not enough rows (expected 2, got 1)"); - BOOST_REQUIRE_EQUAL(mtx.width, 4); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.1); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], 2.2); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.3); - BOOST_REQUIRE_EQUAL(mtx.entry[3][0], 4.4); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0.); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 0.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], 0.); - BOOST_REQUIRE_EQUAL(mtx.entry[3][1], 0.); + BOOST_REQUIRE_EQUAL(mtx.width, 4); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.1); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], 2.2); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.3); + BOOST_REQUIRE_EQUAL(mtx.entry[3][0], 4.4); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0.); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 0.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], 0.); + BOOST_REQUIRE_EQUAL(mtx.entry[3][1], 0.); } // 1.f. -BOOST_AUTO_TEST_CASE(file_with_rows_of_different_size___load_succeeds__column_resized__0_on_missing_coef) +BOOST_AUTO_TEST_CASE( + file_with_rows_of_different_size___load_succeeds__column_resized__0_on_missing_coef) { - Clob* fake_buffer = new Clob; - // 5.2 6.1 - - // 1.3 4.5 9.7 - fake_buffer->append("5.2\t6.1\n1.3\t4.5\t9.7\n"); + Clob* fake_buffer = new Clob; + // 5.2 6.1 - + // 1.3 4.5 9.7 + fake_buffer->append("5.2\t6.1\n1.3\t4.5\t9.7\n"); - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNeverFails, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNeverFails, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 5.2); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], 6.1); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 0.); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 1.3); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 4.5); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], 9.7); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 5.2); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], 6.1); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 0.); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 1.3); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 4.5); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], 9.7); } // 1.f. BOOST_AUTO_TEST_CASE(file_with_columns_of_different_size___load_succeeds__row_not_resized) { - Clob* fake_buffer = new Clob; - // 5.2 6.1 - // 1.3 4.5 - // 9.7 - - fake_buffer->append("5.2\t6.1\n1.3\t4.5\n9.7\n"); + Clob* fake_buffer = new Clob; + // 5.2 6.1 + // 1.3 4.5 + // 9.7 - + fake_buffer->append("5.2\t6.1\n1.3\t4.5\n9.7\n"); - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNeverFails, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optNeverFails, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 2); - BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.width, 2); + BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 5.2); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], 6.1); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 5.2); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], 6.1); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 1.3); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 4.5); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 1.3); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 4.5); } // 1.f. -BOOST_AUTO_TEST_CASE(file_has_invalid_header__option_do_not_fail____load_succeeds__column_resized_to_1__0s_everywhere) +BOOST_AUTO_TEST_CASE( + file_has_invalid_header__option_do_not_fail____load_succeeds__column_resized_to_1__0s_everywhere) { - Clob* fake_buffer = new Clob; - fake_buffer->append("size:0x0"); + Clob* fake_buffer = new Clob; + fake_buffer->append("size:0x0"); - Matrix_mock_load_to_buffer mtx; - logs.warning().clear(); - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 5, Matrix<>::optNeverFails, fake_buffer)); + Matrix_mock_load_to_buffer mtx; + logs.warning().clear(); + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 5, Matrix<>::optNeverFails, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(logs.warning().contains("Invalid header")); + BOOST_CHECK(logs.warning().contains("Invalid header")); - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 5); - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 5); + BOOST_CHECK(mtx.containsOnlyZero()); } // 2. @@ -417,269 +446,281 @@ BOOST_AUTO_TEST_CASE(file_has_invalid_header__option_do_not_fail____load_succeed // 3.a. BOOST_AUTO_TEST_CASE(fake_file_empty__mtx_resized_to_0x2___mtx_cleared) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Clob* fake_buffer = new Clob; // Empty buffer + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Clob* fake_buffer = new Clob; // Empty buffer - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(mtx.empty()); + BOOST_CHECK(mtx.empty()); } // 3.a. -BOOST_AUTO_TEST_CASE(file_size_3x2__mtx_resized_to_5x7___mtx_still_5x7_but_contains_only_0s__load_fails) +BOOST_AUTO_TEST_CASE( + file_size_3x2__mtx_resized_to_5x7___mtx_still_5x7_but_contains_only_0s__load_fails) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 3, { 1.5, -2.44444, 3.66666, 0.9, 8.559, -5.5555 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 3, {1.5, -2.44444, 3.66666, 0.9, 8.559, -5.5555}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 5, 7, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 5, 7, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 5); - BOOST_REQUIRE_EQUAL(mtx.height, 7); - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_REQUIRE_EQUAL(mtx.width, 5); + BOOST_REQUIRE_EQUAL(mtx.height, 7); + BOOST_CHECK(mtx.containsOnlyZero()); } // 3.a. BOOST_AUTO_TEST_CASE(file_size_3x3__mtx_resized_to_1x2___mtx_column_resized_to_3__coefs_preserved) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(3, 3, { 1., -2., 3., 0., 8., -5., 6., -7., 12. }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(3, 3, {1., -2., 3., 0., 8., -5., 6., -7., 12.}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0.); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 0.); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], 8.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], -5); } // 3.a. // 3.b. -BOOST_AUTO_TEST_CASE(file_bigger_than_mtx__mtx_has_a_fixed_size___mtx_keeps_size_but_is_filled_with_0s__load_fails) -{ - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(4, 4, { 1., -2., 3., -15., - 8., -5., 6., -7., - 12., 10., -20., 30., - -150., 80., -50., 60.}); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); +BOOST_AUTO_TEST_CASE( + file_bigger_than_mtx__mtx_has_a_fixed_size___mtx_keeps_size_but_is_filled_with_0s__load_fails) +{ + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0( + 4, + 4, + {1., -2., 3., -15., 8., -5., 6., -7., 12., 10., -20., 30., -150., 80., -50., 60.}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - logs.warning().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 3, Matrix<>::optFixedSize, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + logs.warning().clear(); + BOOST_CHECK( + not mtx.loadFromCSVFile("path/to/a/file", 3, 3, Matrix<>::optFixedSize, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_CHECK(logs.warning().contains("Invalid format: Too many entry for the row")); + BOOST_CHECK(logs.warning().contains("Invalid format: Too many entry for the row")); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 3); - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 3); + BOOST_CHECK(mtx.containsOnlyZero()); } // 3.a. // 3.b. -BOOST_AUTO_TEST_CASE(file_bigger_than_mtx__mtx_fixed_size__load_should_never_fail___load_succeeds__column_resized) +BOOST_AUTO_TEST_CASE( + file_bigger_than_mtx__mtx_fixed_size__load_should_never_fail___load_succeeds__column_resized) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(3, 3, { 1., -2., 3., 8., -5., 6., 12., 10., -20.}); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(3, 3, {1., -2., 3., 8., -5., 6., 12., 10., -20.}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 2, 2, Matrix<>::optFixedSize | Matrix<>::optNeverFails, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", + 2, + 2, + Matrix<>::optFixedSize | Matrix<>::optNeverFails, + fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 8.); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); - BOOST_REQUIRE_EQUAL(mtx.entry[1][1], -5.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][1], 6.); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], 8.); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); + BOOST_REQUIRE_EQUAL(mtx.entry[1][1], -5.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][1], 6.); } // 3.b. BOOST_AUTO_TEST_CASE(loading_option_to_none___target_mtx_not_loaded_but_pointed_to_by_jit) { - global_JIT_manager global_JIT_to(true); + global_JIT_manager global_JIT_to(true); - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(1, 3, { 1., -2., 3. }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(1, 3, {1., -2., 3.}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 0); - BOOST_REQUIRE_EQUAL(mtx.height, 0); - BOOST_CHECK((bool)(mtx.jit)); - BOOST_REQUIRE_EQUAL(mtx.jit->sourceFilename, "path/to/a/file"); + BOOST_REQUIRE_EQUAL(mtx.width, 0); + BOOST_REQUIRE_EQUAL(mtx.height, 0); + BOOST_CHECK((bool)(mtx.jit)); + BOOST_REQUIRE_EQUAL(mtx.jit->sourceFilename, "path/to/a/file"); } - // 3.b. BOOST_AUTO_TEST_CASE(loading_option_to_immediate___target_mtx_loaded_but_not_pointed_to_by_jit) { - global_JIT_manager global_JIT_to(true); + global_JIT_manager global_JIT_to(true); - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(1, 3, { 1.55, -2., 3.11 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(2); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(1, 3, {1.55, -2., 3.11}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(2); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optImmediate, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optImmediate, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 1); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.55); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.11); - BOOST_CHECK(not mtx.jit); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 1); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.55); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.11); + BOOST_CHECK(not mtx.jit); } // 3.b. -BOOST_AUTO_TEST_CASE(loading_option_to_immediate_and_fixed_size___target_mtx_loaded_and_pointed_to_by_jit) +BOOST_AUTO_TEST_CASE( + loading_option_to_immediate_and_fixed_size___target_mtx_loaded_and_pointed_to_by_jit) { - global_JIT_manager global_JIT_to(true); + global_JIT_manager global_JIT_to(true); - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(1, 3, { 1.55, -2., 3.11 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(2); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(1, 3, {1.55, -2., 3.11}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(2); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optImmediate | Matrix<>::optFixedSize, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", + 3, + 1, + Matrix<>::optImmediate | Matrix<>::optFixedSize, + fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 1); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.55); - BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); - BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.11); - BOOST_CHECK(mtx.jit); - BOOST_REQUIRE_EQUAL(mtx.jit->sourceFilename, "path/to/a/file"); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 1); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1.55); + BOOST_REQUIRE_EQUAL(mtx.entry[1][0], -2.); + BOOST_REQUIRE_EQUAL(mtx.entry[2][0], 3.11); + BOOST_CHECK(mtx.jit); + BOOST_REQUIRE_EQUAL(mtx.jit->sourceFilename, "path/to/a/file"); } // 4. BOOST_AUTO_TEST_CASE(err_not_found_when_loading___log_is_ok) { - Clob* fake_buffer = new Clob; + Clob* fake_buffer = new Clob; - // Testing load - Matrix_mock_load_to_buffer mtx; - mtx.error_when_loading_from_file(IO::errNotFound); + // Testing load + Matrix_mock_load_to_buffer mtx; + mtx.error_when_loading_from_file(IO::errNotFound); - // option : none - logs.error().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); - BOOST_REQUIRE_EQUAL(logs.error().content(), "I/O Error: not found: 'path/to/a/file'"); + // option : none + logs.error().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optNone, fake_buffer)); + BOOST_REQUIRE_EQUAL(logs.error().content(), "I/O Error: not found: 'path/to/a/file'"); - // option : quiet - logs.error().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 5, Matrix<>::optQuiet, fake_buffer)); - BOOST_REQUIRE_EQUAL(logs.error().content(), ""); + // option : quiet + logs.error().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 2, 5, Matrix<>::optQuiet, fake_buffer)); + BOOST_REQUIRE_EQUAL(logs.error().content(), ""); - delete fake_buffer; + delete fake_buffer; } // 4. BOOST_AUTO_TEST_CASE(err_memory_limit_when_loading___log_is_ok) { - Clob* fake_buffer = new Clob; + Clob* fake_buffer = new Clob; - // Testing load - Matrix_mock_load_to_buffer mtx; - mtx.error_when_loading_from_file(IO::errMemoryLimit); + // Testing load + Matrix_mock_load_to_buffer mtx; + mtx.error_when_loading_from_file(IO::errMemoryLimit); - // option : none - logs.error().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 7, Matrix<>::optNone, fake_buffer)); - string logs_to_get = "path/to/a/file: The file is too large (>" + to_string(filesizeHardLimit / 1024 / 1024) + "Mo)"; - BOOST_REQUIRE_EQUAL(logs.error().content(), logs_to_get); + // option : none + logs.error().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 7, Matrix<>::optNone, fake_buffer)); + string logs_to_get = "path/to/a/file: The file is too large (>" + + to_string(filesizeHardLimit / 1024 / 1024) + "Mo)"; + BOOST_REQUIRE_EQUAL(logs.error().content(), logs_to_get); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 7); - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 7); + BOOST_CHECK(mtx.containsOnlyZero()); - // option : quiet - logs.error().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optQuiet, fake_buffer)); - BOOST_REQUIRE_EQUAL(logs.error().content(), ""); + // option : quiet + logs.error().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optQuiet, fake_buffer)); + BOOST_REQUIRE_EQUAL(logs.error().content(), ""); - BOOST_REQUIRE_EQUAL(mtx.width, 3); - BOOST_REQUIRE_EQUAL(mtx.height, 1); - BOOST_CHECK(mtx.containsOnlyZero()); + BOOST_REQUIRE_EQUAL(mtx.width, 3); + BOOST_REQUIRE_EQUAL(mtx.height, 1); + BOOST_CHECK(mtx.containsOnlyZero()); - delete fake_buffer; + delete fake_buffer; } // 4. BOOST_AUTO_TEST_CASE(err_unknown_when_loading___log_is_ok) { - Clob* fake_buffer = new Clob; + Clob* fake_buffer = new Clob; - // Testing load - Matrix_mock_load_to_buffer mtx; - mtx.error_when_loading_from_file(IO::errUnknown); + // Testing load + Matrix_mock_load_to_buffer mtx; + mtx.error_when_loading_from_file(IO::errUnknown); - // option : none - logs.error().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 7, Matrix<>::optNone, fake_buffer)); - BOOST_REQUIRE_EQUAL(logs.error().content(), "I/O Error: failed to load 'path/to/a/file'"); + // option : none + logs.error().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 7, Matrix<>::optNone, fake_buffer)); + BOOST_REQUIRE_EQUAL(logs.error().content(), "I/O Error: failed to load 'path/to/a/file'"); - // option : quiet - logs.error().clear(); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optQuiet, fake_buffer)); - BOOST_REQUIRE_EQUAL(logs.error().content(), ""); + // option : quiet + logs.error().clear(); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 3, 1, Matrix<>::optQuiet, fake_buffer)); + BOOST_REQUIRE_EQUAL(logs.error().content(), ""); - delete fake_buffer; + delete fake_buffer; } BOOST_AUTO_TEST_SUITE_END() - // ============================ // ==== Matrix ==== // ============================ @@ -688,53 +729,52 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_int__load_from_int) // 1.c. BOOST_AUTO_TEST_CASE(file_contains_digits___loading_to_target_matrix_rounds_each_coef_to_floor) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 1, { 1.5252, -2.1111 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(4); - buffer_factory_dd.print_dimensions(true); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 1, {1.5252, -2.1111}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(4); + buffer_factory_dd.print_dimensions(true); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -2); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -2); } BOOST_AUTO_TEST_CASE(file_contains_int___loaded_coefs_are_int) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 1, { 102, -54 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(4); - buffer_factory_dd.print_dimensions(true); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 1, {102, -54}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(4); + buffer_factory_dd.print_dimensions(true); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 102); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -54); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 102); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -54); } BOOST_AUTO_TEST_SUITE_END() - // =============================== // ==== Matrix ==== // =============================== @@ -743,25 +783,25 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_int__load_from_digits) // 1.c. BOOST_AUTO_TEST_CASE(file_contains_digits___loading_to_target_matrix_rounds_each_coef_to_floor) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 1, { 1.5252, -2.1111 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(4); - buffer_factory_dd.print_dimensions(true); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 1, {1.5252, -2.1111}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(4); + buffer_factory_dd.print_dimensions(true); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -2); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 1); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -2); } BOOST_AUTO_TEST_SUITE_END() @@ -774,73 +814,80 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_digits__load_from_int) // 1.c. BOOST_AUTO_TEST_CASE(file_contains_digits___loaded_coefs_are_rounded_to_floor_but_stored_as_digits) { - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 1, { 12.9, -23.2 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - buffer_factory_dd.set_precision(4); - buffer_factory_dd.print_dimensions(true); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 1, {12.9, -23.2}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + buffer_factory_dd.set_precision(4); + buffer_factory_dd.print_dimensions(true); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optNone, fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 12.); - BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -23.); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_REQUIRE_EQUAL(mtx.entry[0][0], 12.); + BOOST_REQUIRE_EQUAL(mtx.entry[0][1], -23.); } BOOST_AUTO_TEST_SUITE_END() - BOOST_AUTO_TEST_SUITE(JIT_management) BOOST_AUTO_TEST_CASE(mtx_is_marked_modified__load_is_done___mtx_no_more_modified) { - global_JIT_manager global_JIT_to(true); + global_JIT_manager global_JIT_to(true); - // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) - Matrix_easy_to_fill mtx_0(2, 1, { 12, -23 }); - fake_buffer_factory buffer_factory_dd; - buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); + // Creating a buffer mocking the result of : IO::File::LoadFromFile(...) + Matrix_easy_to_fill mtx_0(2, 1, {12, -23}); + fake_buffer_factory buffer_factory_dd; + buffer_factory_dd.matrix_to_build_buffer_with(&mtx_0); - Clob* fake_buffer = buffer_factory_dd.build_buffer(); + Clob* fake_buffer = buffer_factory_dd.build_buffer(); - // Testing load - Matrix_mock_load_to_buffer mtx; - mtx.jit = new JIT::Informations(); // Giving matrix a defaut jit information - mtx.markAsModified(); - BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", 0, 0, Matrix<>::optImmediate | Matrix<>::optMarkAsModified, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + mtx.jit = new JIT::Informations(); // Giving matrix a defaut jit information + mtx.markAsModified(); + BOOST_CHECK(mtx.loadFromCSVFile("path/to/a/file", + 0, + 0, + Matrix<>::optImmediate | Matrix<>::optMarkAsModified, + fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_CHECK(not mtx.jit->modified); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_CHECK(not mtx.jit->modified); } -BOOST_AUTO_TEST_CASE(load_fails_so_jit_not_created_by_effective_loading___jit_created_after_load_because_size_fixed) +BOOST_AUTO_TEST_CASE( + load_fails_so_jit_not_created_by_effective_loading___jit_created_after_load_because_size_fixed) { - global_JIT_manager global_JIT_to(true); + global_JIT_manager global_JIT_to(true); - Clob* fake_buffer = nullptr; + Clob* fake_buffer = nullptr; - // Testing load - Matrix_mock_load_to_buffer mtx; - mtx.error_when_loading_from_file(IO::errNotFound); - BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", 1, 2, Matrix<>::optImmediate | Matrix<>::optFixedSize, fake_buffer)); + // Testing load + Matrix_mock_load_to_buffer mtx; + mtx.error_when_loading_from_file(IO::errNotFound); + BOOST_CHECK(not mtx.loadFromCSVFile("path/to/a/file", + 1, + 2, + Matrix<>::optImmediate | Matrix<>::optFixedSize, + fake_buffer)); - delete fake_buffer; + delete fake_buffer; - BOOST_REQUIRE_EQUAL(mtx.width, 1); - BOOST_REQUIRE_EQUAL(mtx.height, 2); - BOOST_CHECK(mtx.jit); + BOOST_REQUIRE_EQUAL(mtx.width, 1); + BOOST_REQUIRE_EQUAL(mtx.height, 2); + BOOST_CHECK(mtx.jit); } - -BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/array/tests-matrix-load.h b/src/tests/src/libs/antares/array/tests-matrix-load.h index 6e88a2c460..8ec9188e0b 100644 --- a/src/tests/src/libs/antares/array/tests-matrix-load.h +++ b/src/tests/src/libs/antares/array/tests-matrix-load.h @@ -1,10 +1,31 @@ -# include "matrix-bypass-load.h" -# include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include +#include + +#include "matrix-bypass-load.h" enum { - //! A Hard-coded maximum filesize - filesizeHardLimit = 1536 * 1024 * 1024, // 1.5Go -}; \ No newline at end of file + //! A Hard-coded maximum filesize + filesizeHardLimit = 1536 * 1024 * 1024, // 1.5Go +}; diff --git a/src/tests/src/libs/antares/array/tests-matrix-save.cpp b/src/tests/src/libs/antares/array/tests-matrix-save.cpp index b01ac3ef17..d1af11d387 100644 --- a/src/tests/src/libs/antares/array/tests-matrix-save.cpp +++ b/src/tests/src/libs/antares/array/tests-matrix-save.cpp @@ -1,14 +1,32 @@ -#define BOOST_TEST_MODULE test-lib-antares-matrix tests -#define BOOST_TEST_DYN_LINK +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test - lib - antares - matrix tests #define WIN32_LEAN_AND_MEAN -#include - #include "tests-matrix-save.h" -namespace utf = boost::unit_test; +#include +namespace utf = boost::unit_test; // ================================ // === Matrix === @@ -17,75 +35,73 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_double__save_into_double) BOOST_AUTO_TEST_CASE(matrix_only_0s_and__no_print_dim___result_is_empty) { - Matrix_easy_to_fill mtx; - mtx.reset(2, 2, true); - mtx.saveToCSVFile("path/to/an/output/file"); - BOOST_REQUIRE_EQUAL(mtx.data, ""); + Matrix_easy_to_fill mtx; + mtx.reset(2, 2, true); + mtx.saveToCSVFile("path/to/an/output/file"); + BOOST_REQUIRE_EQUAL(mtx.data, ""); } BOOST_AUTO_TEST_CASE(matrix_only_0s__print_dim___get_only_a_title_and_the_0s) { - Matrix_easy_to_fill mtx; - mtx.reset(2, 2, true); - mtx.saveToCSVFile("path/to/an/output/file", 0, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:2x2\n0\t0\n0\t0\n"); + Matrix_easy_to_fill mtx; + mtx.reset(2, 2, true); + mtx.saveToCSVFile("path/to/an/output/file", 0, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:2x2\n0\t0\n0\t0\n"); } BOOST_AUTO_TEST_CASE(coeffs_have_int_values___no_zeros_after_decimal_point) { - Matrix_easy_to_fill mtx(2, 2, {1, 0, 0, -2}); - mtx.saveToCSVFile("path/to/an/output/file"); - BOOST_REQUIRE_EQUAL(mtx.data, "1\t0\n0\t-2\n"); + Matrix_easy_to_fill mtx(2, 2, {1, 0, 0, -2}); + mtx.saveToCSVFile("path/to/an/output/file"); + BOOST_REQUIRE_EQUAL(mtx.data, "1\t0\n0\t-2\n"); } BOOST_AUTO_TEST_CASE(precision_is_3___get_3_nbs_after_decimal_point) { - Matrix_easy_to_fill mtx(2, 2, {1.5, -2.44444, 3.66666, 0}); - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_REQUIRE_EQUAL(mtx.data, "1.500\t-2.444\n3.667\t0\n"); + Matrix_easy_to_fill mtx(2, 2, {1.5, -2.44444, 3.66666, 0}); + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_REQUIRE_EQUAL(mtx.data, "1.500\t-2.444\n3.667\t0\n"); } BOOST_AUTO_TEST_CASE(precision_has_no_effect_on_integer_values) { - // Any whole number is printed without decimal point - Matrix_easy_to_fill mtx(2, 2, {1, 5, 0, 3}); - mtx.saveToCSVFile("path/to/an/output/file", 4, false); - BOOST_REQUIRE_EQUAL(mtx.data, "1\t5\n0\t3\n"); + // Any whole number is printed without decimal point + Matrix_easy_to_fill mtx(2, 2, {1, 5, 0, 3}); + mtx.saveToCSVFile("path/to/an/output/file", 4, false); + BOOST_REQUIRE_EQUAL(mtx.data, "1\t5\n0\t3\n"); } BOOST_AUTO_TEST_CASE(add_identity_predicate___each_coeff_is_unchanged) { - Matrix_easy_to_fill mtx(2, 2, {1, 0, 0, 2}); - PredicateIdentity predicate; - mtx.saveToCSVFile("path/to/an/output/file", 2, false, predicate); - BOOST_REQUIRE_EQUAL(mtx.data, "1\t0\n0\t2\n"); + Matrix_easy_to_fill mtx(2, 2, {1, 0, 0, 2}); + PredicateIdentity predicate; + mtx.saveToCSVFile("path/to/an/output/file", 2, false, predicate); + BOOST_REQUIRE_EQUAL(mtx.data, "1\t0\n0\t2\n"); } BOOST_AUTO_TEST_CASE(one_column__3_rows) { - Matrix_easy_to_fill mtx(3, 1, { 1.5, -3.552, 0.66 }); - mtx.saveToCSVFile("path/to/an/output/file", 2, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n1.50\n-3.55\n0.66\n"); + Matrix_easy_to_fill mtx(3, 1, {1.5, -3.552, 0.66}); + mtx.saveToCSVFile("path/to/an/output/file", 2, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n1.50\n-3.55\n0.66\n"); } BOOST_AUTO_TEST_CASE(one_column__3_rows_thermal) { - Matrix_easy_to_fill mtx(3, 1, { 1., -3., 2. }); - mtx.saveToCSVFile("path/to/an/output/file", 2, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n1\n-3\n2\n"); + Matrix_easy_to_fill mtx(3, 1, {1., -3., 2.}); + mtx.saveToCSVFile("path/to/an/output/file", 2, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n1\n-3\n2\n"); } BOOST_AUTO_TEST_CASE(one_column__3_rows_renw) { - Matrix_easy_to_fill mtx(3, 1, { 1.3333, -3.66666, 2. }); - mtx.saveToCSVFile("path/to/an/output/file", 4, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n1.3333\n-3.6667\n2\n"); + Matrix_easy_to_fill mtx(3, 1, {1.3333, -3.66666, 2.}); + mtx.saveToCSVFile("path/to/an/output/file", 4, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n1.3333\n-3.6667\n2\n"); } BOOST_AUTO_TEST_SUITE_END() - - // ============================= // === Matrix === // ============================= @@ -93,53 +109,51 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_int__save_into_double) BOOST_AUTO_TEST_CASE(matrix_only_0s_and__no_print_dim___result_is_empty) { - Matrix_easy_to_fill mtx(2, 2); - mtx.reset(2, 2, true); - mtx.saveToCSVFile("path/to/an/output/file"); - BOOST_REQUIRE_EQUAL(mtx.data, ""); + Matrix_easy_to_fill mtx(2, 2); + mtx.reset(2, 2, true); + mtx.saveToCSVFile("path/to/an/output/file"); + BOOST_REQUIRE_EQUAL(mtx.data, ""); } BOOST_AUTO_TEST_CASE(matrix_only_0s__print_dim___get_only_a_title_and_the_0s) { - Matrix_easy_to_fill mtx; - mtx.reset(2, 2, true); - mtx.saveToCSVFile("path/to/an/output/file", 0, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:2x2\n0\t0\n0\t0\n"); + Matrix_easy_to_fill mtx; + mtx.reset(2, 2, true); + mtx.saveToCSVFile("path/to/an/output/file", 0, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:2x2\n0\t0\n0\t0\n"); } BOOST_AUTO_TEST_CASE(any_whole_number_is_printed_without_decimal_point) { - Matrix_easy_to_fill mtx(2, 2, {10, 500, 0, 3}); - mtx.saveToCSVFile("path/to/an/output/file"); - BOOST_REQUIRE_EQUAL(mtx.data, "10\t500\n0\t3\n"); + Matrix_easy_to_fill mtx(2, 2, {10, 500, 0, 3}); + mtx.saveToCSVFile("path/to/an/output/file"); + BOOST_REQUIRE_EQUAL(mtx.data, "10\t500\n0\t3\n"); } BOOST_AUTO_TEST_CASE(add_predicate__print_dim___each_coeff_is_one_incremented) { - Matrix_easy_to_fill mtx(2, 3, { 1, 2, 3, 4, 5, 6 }); - TSNumbersPredicate predicate; - mtx.saveToCSVFile("path/to/an/output/file", 2, true, predicate); - BOOST_REQUIRE_EQUAL(mtx.data, "size:3x2\n2\t3\t4\n5\t6\t7\n"); + Matrix_easy_to_fill mtx(2, 3, {1, 2, 3, 4, 5, 6}); + TSNumbersPredicate predicate; + mtx.saveToCSVFile("path/to/an/output/file", 2, true, predicate); + BOOST_REQUIRE_EQUAL(mtx.data, "size:3x2\n2\t3\t4\n5\t6\t7\n"); } BOOST_AUTO_TEST_CASE(negative_int___printed_correctly) { - Matrix_easy_to_fill mtx(2, 3, { 1, -2, 3, -4, -5, 6 }); - mtx.saveToCSVFile("path/to/an/output/file", 2, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:3x2\n1\t-2\t3\n-4\t-5\t6\n"); + Matrix_easy_to_fill mtx(2, 3, {1, -2, 3, -4, -5, 6}); + mtx.saveToCSVFile("path/to/an/output/file", 2, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:3x2\n1\t-2\t3\n-4\t-5\t6\n"); } BOOST_AUTO_TEST_CASE(precision_has_no_effect_on_int_coeffs) { - Matrix_easy_to_fill mtx(3, 2, { 1, -2, 3, -4, -5, 6 }); - mtx.saveToCSVFile("path/to/an/output/file", 5, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:2x3\n1\t-2\n3\t-4\n-5\t6\n"); + Matrix_easy_to_fill mtx(3, 2, {1, -2, 3, -4, -5, 6}); + mtx.saveToCSVFile("path/to/an/output/file", 5, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:2x3\n1\t-2\n3\t-4\n-5\t6\n"); } BOOST_AUTO_TEST_SUITE_END() - - // ========================== // === Matrix === // ========================== @@ -147,45 +161,44 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_int__save_into_int) BOOST_AUTO_TEST_CASE(matrix_only_0s_and_no_print_dim___result_is_empty) { - Matrix_easy_to_fill mtx(2, 2); - mtx.reset(2, 2, true); - mtx.saveToCSVFile("path/to/an/output/file"); - BOOST_REQUIRE_EQUAL(mtx.data, ""); + Matrix_easy_to_fill mtx(2, 2); + mtx.reset(2, 2, true); + mtx.saveToCSVFile("path/to/an/output/file"); + BOOST_REQUIRE_EQUAL(mtx.data, ""); } BOOST_AUTO_TEST_CASE(matrix_only_0s__print_dim___dim_and_0s_are_printed) { - Matrix_easy_to_fill mtx(3, 1); // Normal Matrix constuctor : 3 columns x 1 row - mtx.zero(); - mtx.saveToCSVFile("path/to/an/output/file", 0, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:3x1\n0\t0\t0\n"); + Matrix_easy_to_fill mtx(3, 1); // Normal Matrix constuctor : 3 columns x 1 row + mtx.zero(); + mtx.saveToCSVFile("path/to/an/output/file", 0, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:3x1\n0\t0\t0\n"); } BOOST_AUTO_TEST_CASE(first_matrix___int_to_int) { - Matrix_easy_to_fill mtx(2, 2, {1000, -5000, 0, 3000}); - mtx.saveToCSVFile("path/to/an/output/file"); - BOOST_REQUIRE_EQUAL(mtx.data, "1000\t-5000\n0\t3000\n"); + Matrix_easy_to_fill mtx(2, 2, {1000, -5000, 0, 3000}); + mtx.saveToCSVFile("path/to/an/output/file"); + BOOST_REQUIRE_EQUAL(mtx.data, "1000\t-5000\n0\t3000\n"); } BOOST_AUTO_TEST_CASE(add_predicate__print_dim__negative_int___each_coeff_is_one_incremented) { - Matrix_easy_to_fill mtx(2, 3, { -1, 2, -3, 4, -5, 6 }); - TSNumbersPredicate predicate; - mtx.saveToCSVFile("path/to/an/output/file", 2, true, predicate); - BOOST_REQUIRE_EQUAL(mtx.data, "size:3x2\n0\t3\t-2\n5\t-4\t7\n"); + Matrix_easy_to_fill mtx(2, 3, {-1, 2, -3, 4, -5, 6}); + TSNumbersPredicate predicate; + mtx.saveToCSVFile("path/to/an/output/file", 2, true, predicate); + BOOST_REQUIRE_EQUAL(mtx.data, "size:3x2\n0\t3\t-2\n5\t-4\t7\n"); } BOOST_AUTO_TEST_CASE(precision_has_no_effect_on_int_coeffs) { - Matrix_easy_to_fill mtx(3, 2, { 1, -2, 3, -4, -5, 6 }); - mtx.saveToCSVFile("path/to/an/output/file", 5, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:2x3\n1\t-2\n3\t-4\n-5\t6\n"); + Matrix_easy_to_fill mtx(3, 2, {1, -2, 3, -4, -5, 6}); + mtx.saveToCSVFile("path/to/an/output/file", 5, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:2x3\n1\t-2\n3\t-4\n-5\t6\n"); } BOOST_AUTO_TEST_SUITE_END() - // ============================= // === Matrix === // ============================= @@ -193,38 +206,36 @@ BOOST_AUTO_TEST_SUITE(coeffs_are_double__save_into_int) BOOST_AUTO_TEST_CASE(coeffs_only_0s__no_print_dim___result_empty) { - Matrix_easy_to_fill mtx(2, 2); - mtx.zero(); - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_REQUIRE_EQUAL(mtx.data, ""); + Matrix_easy_to_fill mtx(2, 2); + mtx.zero(); + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_REQUIRE_EQUAL(mtx.data, ""); } BOOST_AUTO_TEST_CASE(coeffs_only_0s__print_dim___get_dim_and_0s_in_output) { - Matrix_easy_to_fill mtx(1, 3); - mtx.zero(); - mtx.saveToCSVFile("path/to/an/output/file", 3, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n0\n0\n0\n"); + Matrix_easy_to_fill mtx(1, 3); + mtx.zero(); + mtx.saveToCSVFile("path/to/an/output/file", 3, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:1x3\n0\n0\n0\n"); } BOOST_AUTO_TEST_CASE(precision_is_3__get_coeffs_floor_integers) { - Matrix_easy_to_fill mtx(2, 2, {1.99, 2.44, -3.999, -1.51}); - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_REQUIRE_EQUAL(mtx.data, "1\t2\n-3\t-1\n"); + Matrix_easy_to_fill mtx(2, 2, {1.99, 2.44, -3.999, -1.51}); + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_REQUIRE_EQUAL(mtx.data, "1\t2\n-3\t-1\n"); } - BOOST_AUTO_TEST_CASE(precision_has_no_effect_on_int_coeffs) { - Matrix_easy_to_fill mtx(3, 2, { 1.99, -2.49, 3, -4.99, -5, 6.99 }); - mtx.saveToCSVFile("path/to/an/output/file", 5, true); - BOOST_REQUIRE_EQUAL(mtx.data, "size:2x3\n1\t-2\n3\t-4\n-5\t6\n"); + Matrix_easy_to_fill mtx(3, 2, {1.99, -2.49, 3, -4.99, -5, 6.99}); + mtx.saveToCSVFile("path/to/an/output/file", 5, true); + BOOST_REQUIRE_EQUAL(mtx.data, "size:2x3\n1\t-2\n3\t-4\n-5\t6\n"); } BOOST_AUTO_TEST_SUITE_END() - // =================== // === About JIT === // =================== @@ -233,110 +244,111 @@ BOOST_AUTO_TEST_SUITE(jit) BOOST_AUTO_TEST_CASE(JIT_enabler_built__jit_also_built) { - { - global_JIT_manager global_JIT_to(true); - BOOST_CHECK(JIT::enabled); - } - BOOST_CHECK(not JIT::enabled); + { + global_JIT_manager global_JIT_to(true); + BOOST_CHECK(JIT::enabled); + } + BOOST_CHECK(not JIT::enabled); } BOOST_AUTO_TEST_CASE(global_JIT_off___matrix_built_with_any_constructor_or_reset____jit_not_built) { - Matrix_load_bypass mtx_1, mtx_2(2, 2); - BOOST_CHECK(not mtx_1.jit); - BOOST_CHECK(not mtx_2.jit); - mtx_1.reset(2, 2, true); - BOOST_CHECK(not mtx_1.jit); + Matrix_load_bypass mtx_1, mtx_2(2, 2); + BOOST_CHECK(not mtx_1.jit); + BOOST_CHECK(not mtx_2.jit); + mtx_1.reset(2, 2, true); + BOOST_CHECK(not mtx_1.jit); } BOOST_AUTO_TEST_CASE(global_JIT_on___matrix_built_with_any_constructor____jit_not_built) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx_1, mtx_2(2, 2); - BOOST_CHECK(not mtx_1.jit); - BOOST_CHECK(not mtx_2.jit); - mtx_1.reset(2, 2, true); - BOOST_CHECK(mtx_1.jit); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx_1, mtx_2(2, 2); + BOOST_CHECK(not mtx_1.jit); + BOOST_CHECK(not mtx_2.jit); + mtx_1.reset(2, 2, true); + BOOST_CHECK(mtx_1.jit); } BOOST_AUTO_TEST_CASE(global_JIT_on___matrix_built_with_reset____jit_built) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx; - mtx.reset(2, 2, true); - BOOST_CHECK(mtx.jit); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx; + mtx.reset(2, 2, true); + BOOST_CHECK(mtx.jit); } BOOST_AUTO_TEST_CASE(global_JIT_ON__reset__save____no_load_done) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx; - mtx.reset(2, 2, true); - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(not mtx.loadFromCSVFile_called); - BOOST_CHECK(not mtx.jit->loadDataIfNotAlreadyDone); - BOOST_CHECK(not mtx.jit->alreadyLoaded); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx; + mtx.reset(2, 2, true); + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(not mtx.loadFromCSVFile_called); + BOOST_CHECK(not mtx.jit->loadDataIfNotAlreadyDone); + BOOST_CHECK(not mtx.jit->alreadyLoaded); } BOOST_AUTO_TEST_CASE(global_JIT_ON__reset__save__force_loadData_to_ON____no_load_done) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx; - mtx.reset(2, 2, true); - mtx.jit->loadDataIfNotAlreadyDone = true; - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(not mtx.loadFromCSVFile_called); - BOOST_CHECK(not mtx.jit->loadDataIfNotAlreadyDone); - BOOST_CHECK(not mtx.jit->alreadyLoaded); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx; + mtx.reset(2, 2, true); + mtx.jit->loadDataIfNotAlreadyDone = true; + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(not mtx.loadFromCSVFile_called); + BOOST_CHECK(not mtx.jit->loadDataIfNotAlreadyDone); + BOOST_CHECK(not mtx.jit->alreadyLoaded); } -BOOST_AUTO_TEST_CASE(global_JIT_ON__reset__save__force_loadData_to_ON__alreadyLoaded_to_OFF____load_done) +BOOST_AUTO_TEST_CASE( + global_JIT_ON__reset__save__force_loadData_to_ON__alreadyLoaded_to_OFF____load_done) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx; - mtx.reset(2, 2, true); - mtx.jit->loadDataIfNotAlreadyDone = true; - mtx.jit->alreadyLoaded = false; - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(mtx.loadFromCSVFile_called); - BOOST_CHECK(not mtx.jit->loadDataIfNotAlreadyDone); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx; + mtx.reset(2, 2, true); + mtx.jit->loadDataIfNotAlreadyDone = true; + mtx.jit->alreadyLoaded = false; + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(mtx.loadFromCSVFile_called); + BOOST_CHECK(not mtx.jit->loadDataIfNotAlreadyDone); } BOOST_AUTO_TEST_CASE(matrix_not_empty_cleared_BEFORE_it_can_be_saved) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx(2, 2, { 1.99, 2.44, -3.999, -1.51 }); - mtx.jit = JIT::Reset(mtx.jit); - mtx.jit->modified = false; - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(not mtx.loadFromCSVFile_called); - BOOST_CHECK(mtx.empty()); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx(2, 2, {1.99, 2.44, -3.999, -1.51}); + mtx.jit = JIT::Reset(mtx.jit); + mtx.jit->modified = false; + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(not mtx.loadFromCSVFile_called); + BOOST_CHECK(mtx.empty()); } BOOST_AUTO_TEST_CASE(global_JIT_ON___matrix_saved_and_cleared) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx(2, 2, { 1.99, 2.44, -3.999, -1.51 }); - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(mtx.empty()); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx(2, 2, {1.99, 2.44, -3.999, -1.51}); + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(mtx.empty()); } BOOST_AUTO_TEST_CASE(global_JIT_OFF_jit_off___matrix_never_cleared) { - global_JIT_manager global_JIT_to(false); - Matrix_load_bypass mtx(2, 2, { 1.99, 2.44, -3.999, -1.51 }); - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(not mtx.empty()); + global_JIT_manager global_JIT_to(false); + Matrix_load_bypass mtx(2, 2, {1.99, 2.44, -3.999, -1.51}); + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(not mtx.empty()); } BOOST_AUTO_TEST_CASE(global_JIT_ON_jit_off___matrix_cleared) { - global_JIT_manager global_JIT_to(true); - Matrix_load_bypass mtx(2, 2, { 1.99, 2.44, -3.999, -1.51 }); - delete mtx.jit; // Turning jit off - mtx.jit = nullptr; - mtx.saveToCSVFile("path/to/an/output/file", 3, false); - BOOST_CHECK(mtx.empty()); + global_JIT_manager global_JIT_to(true); + Matrix_load_bypass mtx(2, 2, {1.99, 2.44, -3.999, -1.51}); + delete mtx.jit; // Turning jit off + mtx.jit = nullptr; + mtx.saveToCSVFile("path/to/an/output/file", 3, false); + BOOST_CHECK(mtx.empty()); } -BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/array/tests-matrix-save.h b/src/tests/src/libs/antares/array/tests-matrix-save.h index e8ea710661..7e003eb779 100644 --- a/src/tests/src/libs/antares/array/tests-matrix-save.h +++ b/src/tests/src/libs/antares/array/tests-matrix-save.h @@ -1,21 +1,41 @@ -#include "fill-matrix.h" -#include "matrix-bypass-load.h" -#include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include +#include +#include -#include -#include +#include + +#include "fill-matrix.h" +#include "matrix-bypass-load.h" using namespace std; using namespace Yuni; using namespace Antares; - struct TSNumbersPredicate { - uint32_t operator () (uint32_t value) const - { - return value + 1; - } + uint32_t operator()(uint32_t value) const + { + return value + 1; + } }; struct PredicateIdentity @@ -26,4 +46,3 @@ struct PredicateIdentity return value; } }; - diff --git a/src/tests/src/libs/antares/benchmarking/CMakeLists.txt b/src/tests/src/libs/antares/benchmarking/CMakeLists.txt new file mode 100644 index 0000000000..911f6e12e4 --- /dev/null +++ b/src/tests/src/libs/antares/benchmarking/CMakeLists.txt @@ -0,0 +1,15 @@ +set(PROJ test-duration-collector) + +add_executable(${PROJ}) +target_sources(${PROJ} PRIVATE test_duration_collector.cpp) +target_link_libraries(${PROJ} + PRIVATE + Antares::benchmarking + Boost::unit_test_framework +) + +set_target_properties(${PROJ} PROPERTIES FOLDER Unit-tests/${PROJ}) + +add_test(NAME ${PROJ} COMMAND ${PROJ}) + +set_property(TEST ${PROJ} PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/benchmarking/test_duration_collector.cpp b/src/tests/src/libs/antares/benchmarking/test_duration_collector.cpp new file mode 100644 index 0000000000..4fc74bcda9 --- /dev/null +++ b/src/tests/src/libs/antares/benchmarking/test_duration_collector.cpp @@ -0,0 +1,78 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test - benchmarking +#define WIN32_LEAN_AND_MEAN +#include + +#include + +#include +#include + +BOOST_AUTO_TEST_SUITE(durationCollector) + +using namespace std::literals::chrono_literals; + +constexpr double threshold = 30; + +BOOST_AUTO_TEST_CASE(lambda) +{ + Benchmarking::DurationCollector d; + + d("test1") << [] { [[maybe_unused]] int a; }; + BOOST_CHECK_CLOSE((double)d.getTime("test1"), 0., threshold); + + d("test2") << [] { std::this_thread::sleep_for(200ms); }; + BOOST_CHECK_CLOSE((double)d.getTime("test2"), 200., threshold); + + d("test3") << [&d] + { + d("test4") << [] { std::this_thread::sleep_for(100ms); }; + std::this_thread::sleep_for(100ms); + }; + + BOOST_CHECK_CLOSE((double)d.getTime("test3"), 200., threshold); + BOOST_CHECK_CLOSE((double)d.getTime("test4"), 100., threshold); +} + +BOOST_AUTO_TEST_CASE(exceptionHandling) +{ + Benchmarking::DurationCollector d; + + auto IShouldThrowAnInt = [&d]() { d("test1") << [] { throw int(2); }; }; + + BOOST_CHECK_THROW(IShouldThrowAnInt(), int); +} + +BOOST_AUTO_TEST_CASE(addDuration) +{ + Benchmarking::DurationCollector d; + Benchmarking::Timer t; + + std::this_thread::sleep_for(100ms); + t.stop(); + d.addDuration("test1", t.get_duration()); + + BOOST_CHECK_CLOSE((double)d.getTime("test1"), 100., threshold); +} + +BOOST_AUTO_TEST_SUITE_END() // DurationCollector diff --git a/src/tests/src/libs/antares/concurrency/CMakeLists.txt b/src/tests/src/libs/antares/concurrency/CMakeLists.txt index 71cc0484c4..563d89524f 100644 --- a/src/tests/src/libs/antares/concurrency/CMakeLists.txt +++ b/src/tests/src/libs/antares/concurrency/CMakeLists.txt @@ -8,4 +8,7 @@ target_link_libraries(test-concurrency Antares::concurrency ) +set_target_properties(test-concurrency PROPERTIES FOLDER Unit-tests/test-concurrency) + add_test(NAME concurrency COMMAND test-concurrency) +set_property(TEST concurrency PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/concurrency/test_concurrency.cpp b/src/tests/src/libs/antares/concurrency/test_concurrency.cpp index 2e9cffbd1a..c1188c7a9d 100644 --- a/src/tests/src/libs/antares/concurrency/test_concurrency.cpp +++ b/src/tests/src/libs/antares/concurrency/test_concurrency.cpp @@ -1,33 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#define BOOST_TEST_MODULE test-concurrency tests -#define BOOST_TEST_DYN_LINK -#include + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test - concurrency tests #include +#include #include "antares/concurrency/concurrency.h" @@ -46,23 +39,23 @@ BOOST_AUTO_TEST_CASE(test_no_error) { auto threadPool = createThreadPool(1); int counter = 0; - Task incrementCounter = [&counter]() { - counter++; - }; + Task incrementCounter = [&counter]() { counter++; }; TaskFuture future = AddTask(*threadPool, incrementCounter); future.get(); BOOST_CHECK(counter == 1); } - -template -Task failingTask() { - return []() { - throw Exc(); - }; +template +Task failingTask() +{ + return []() { throw Exc(); }; } -class TestException {}; +class TestException +{ +}; + +BOOST_AUTO_TEST_SUITE(test_concurrency) BOOST_AUTO_TEST_CASE(test_throw) { @@ -74,20 +67,21 @@ BOOST_AUTO_TEST_CASE(test_throw) BOOST_AUTO_TEST_CASE(test_future_set) { auto threadPool = createThreadPool(4); - int counter = 0; - Task incrementCounter = [&counter]() { - counter++; - }; + std::atomic counter = 0; + Task incrementCounter = [&counter]() { counter++; }; FutureSet futures; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { futures.add(AddTask(*threadPool, incrementCounter)); } futures.join(); BOOST_CHECK(counter == 10); } -template -class TestExceptionN {}; +template +class TestExceptionN +{ +}; BOOST_AUTO_TEST_CASE(test_future_set_rethrows_first_submitted) { @@ -97,3 +91,29 @@ BOOST_AUTO_TEST_CASE(test_future_set_rethrows_first_submitted) futures.add(AddTask(*threadPool, failingTask>())); BOOST_CHECK_THROW(futures.join(), TestExceptionN<1>); } + +struct NonCopyableFunctionObject +{ + NonCopyableFunctionObject() = default; + NonCopyableFunctionObject(const NonCopyableFunctionObject&) = delete; + NonCopyableFunctionObject& operator=(const NonCopyableFunctionObject&) = delete; + + bool called = false; + + void operator()() + { + called = true; + } +}; + +BOOST_AUTO_TEST_CASE(allow_to_use_function_object_pointer) +{ + auto threadPool = createThreadPool(1); + auto functionObjectPtr = std::make_shared(); + BOOST_CHECK(!functionObjectPtr->called); + TaskFuture future = AddTask(*threadPool, functionObjectPtr); + future.get(); + BOOST_CHECK(functionObjectPtr->called); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/inifile/CMakeLists.txt b/src/tests/src/libs/antares/inifile/CMakeLists.txt new file mode 100644 index 0000000000..1670c13084 --- /dev/null +++ b/src/tests/src/libs/antares/inifile/CMakeLists.txt @@ -0,0 +1,15 @@ + +add_executable(test_inifile_io test_inifile_io.cpp) + +target_link_libraries(test_inifile_io + PRIVATE + inifile + Boost::unit_test_framework +) + +# Storing executable under the folder Unit-tests in the IDE +set_target_properties(test_inifile_io PROPERTIES FOLDER Unit-tests/test_inifile_io) + +add_test(NAME test_inifile_io COMMAND test_inifile_io) + +set_property(TEST test_inifile_io PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/inifile/test_inifile_io.cpp b/src/tests/src/libs/antares/inifile/test_inifile_io.cpp new file mode 100644 index 0000000000..8e3c80e73f --- /dev/null +++ b/src/tests/src/libs/antares/inifile/test_inifile_io.cpp @@ -0,0 +1,252 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#define BOOST_TEST_MODULE "test inifile IO" + +#include + +#include "antares/inifile/inifile.h" + +struct ReadFromStreamFixture +{ + std::string ini_content; + Antares::IniFile my_inifile; + Antares::IniFile::Section* section = nullptr; + Antares::IniFile::Property* property = nullptr; +}; + +BOOST_AUTO_TEST_SUITE(populating_inicontent_from_stream) + +BOOST_FIXTURE_TEST_CASE(one_section_with_one_property, ReadFromStreamFixture) +{ + ini_content += "[some section]\n"; + ini_content += "some key = some value"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); // Reading the stream causes no trouble + + section = my_inifile.find("some section"); + BOOST_CHECK(section); // The IniFile obj contains the section we supplied + BOOST_CHECK(section->find("some key")); +} + +BOOST_FIXTURE_TEST_CASE(nothing_in_the_stream___no_section_created, ReadFromStreamFixture) +{ + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + BOOST_CHECK(my_inifile.empty()); +} + +BOOST_FIXTURE_TEST_CASE(properties_without_parent_section___ini_content_remains_empty, + ReadFromStreamFixture) +{ + ini_content += "key-1 = value-1\n"; + ini_content += "key-2 = value-2"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + BOOST_CHECK(my_inifile.empty()); +} + +BOOST_FIXTURE_TEST_CASE(a_section_has_no_property___the_section_is_created_and_remains_empty, + ReadFromStreamFixture) +{ + ini_content += "[some section]"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + section = my_inifile.find("some section"); + BOOST_CHECK(section->empty()); +} + +BOOST_FIXTURE_TEST_CASE(a_property_has_2_equal_signs___reading_stream_fails, ReadFromStreamFixture) +{ + ini_content += "[some section]\n"; + ini_content += "key-1 = value-1 key-2 = value-2"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(!my_inifile.readStream(input_stream)); +} + +BOOST_FIXTURE_TEST_CASE(two_properties_commented___they_are_not_created, ReadFromStreamFixture) +{ + ini_content += "[my section]\n"; + ini_content += "key-1 = value-1\n"; + ini_content += "# key-2 = value-2"; + ini_content += "; key-3 = value-3"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + section = my_inifile.find("my section"); + BOOST_CHECK(section->find("key-1")); + BOOST_CHECK(section->size() == 1); +} + +BOOST_FIXTURE_TEST_CASE(blank_line_does_not_matter, ReadFromStreamFixture) +{ + ini_content += "[my section]\n"; + ini_content += " \n"; + ini_content += "key-1 = value-1\n"; + ini_content += "key-2 = value-2"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + section = my_inifile.find("my section"); + BOOST_CHECK(section->size() == 2); + BOOST_CHECK(section->find("key-1") && section->find("key-2")); +} + +BOOST_FIXTURE_TEST_CASE(we_have_a_line_with_unknown_format___reading_stream_fails, + ReadFromStreamFixture) +{ + ini_content += "[my section]\n"; + ini_content += "Some strange line\n"; + ini_content += "key-1 = value-1\n"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(!my_inifile.readStream(input_stream)); +} + +BOOST_FIXTURE_TEST_CASE(ill_formed_section_because_brace_missing___reading_stream_fails, + ReadFromStreamFixture) +{ + ini_content += "[my section\n"; + ini_content += "some key = some value\n"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(!my_inifile.readStream(input_stream)); +} + +BOOST_FIXTURE_TEST_CASE(many_sections, ReadFromStreamFixture) +{ + ini_content += "[section 1]\n"; + ini_content += "key 1 = value 1\n"; + ini_content += "[section 2]\n"; + ini_content += "key 2 = value 2\n"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + + section = my_inifile.find("section 1"); + BOOST_CHECK(section); + BOOST_CHECK(section->find("key 1")); + section = my_inifile.find("section 2"); + BOOST_CHECK(section); + BOOST_CHECK(section->find("key 2")); +} + +BOOST_FIXTURE_TEST_CASE(two_sections_wearing_same_name__both_are_created, ReadFromStreamFixture) +{ + ini_content += "[section 1]\n"; + ini_content += "key 1 = value 1\n"; + ini_content += "[section 1]\n"; + ini_content += "key 2 = value 2\n"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + + section = my_inifile.find("section 1"); + BOOST_CHECK(section); + BOOST_CHECK(section->find("key 1")); + + Antares::IniFile::Section* nextSection = section->next; + BOOST_CHECK(nextSection); + BOOST_CHECK(nextSection->name = "section 1"); + BOOST_CHECK(nextSection->find("key 2")); +} + +BOOST_FIXTURE_TEST_CASE(checking_created_properties_content, ReadFromStreamFixture) +{ + ini_content += "[section 1]\n"; + ini_content += "key 1 = value 1\n"; + ini_content += "key 2 = value 2\n"; + std::istringstream input_stream(ini_content); + + BOOST_CHECK(my_inifile.readStream(input_stream)); + + section = my_inifile.find("section 1"); + BOOST_CHECK(section); + + property = section->find("key 1"); + BOOST_CHECK(property); + BOOST_CHECK_EQUAL(property->value, "value 1"); + + property = section->find("key 2"); + BOOST_CHECK(property); + BOOST_CHECK_EQUAL(property->value, "value 2"); +} + +BOOST_AUTO_TEST_SUITE_END() + +struct SavingToStreamFixture +{ + Antares::IniFile my_inifile; + Antares::IniFile::Section* section = nullptr; + std::ostringstream output_stream; + uint64_t written = 0; + std::string expected_stream_content; +}; + +BOOST_AUTO_TEST_SUITE(saving_inicontent_to_stream) + +BOOST_FIXTURE_TEST_CASE(ini_content_is_empty___out_stream_is_empty, SavingToStreamFixture) +{ + my_inifile.saveToStream(output_stream, written); + BOOST_CHECK_EQUAL(output_stream.str(), ""); +} + +BOOST_FIXTURE_TEST_CASE(one_empty_section___out_stream_is_empty, SavingToStreamFixture) +{ + section = my_inifile.addSection("my section"); + my_inifile.saveToStream(output_stream, written); + BOOST_CHECK_EQUAL(output_stream.str(), ""); +} + +BOOST_FIXTURE_TEST_CASE(one_section_one_property, SavingToStreamFixture) +{ + section = my_inifile.addSection("my section"); + section->add("some key", "some value"); + + my_inifile.saveToStream(output_stream, written); + + expected_stream_content += "[my section]\n"; + expected_stream_content += "some key = some value\n\n"; + BOOST_CHECK_EQUAL(output_stream.str(), expected_stream_content); +} + +BOOST_FIXTURE_TEST_CASE(may_sections, SavingToStreamFixture) +{ + section = my_inifile.addSection("section 1"); + section->add("key 1", "value 1"); + section = my_inifile.addSection("section 2"); + section->add("key 2", "value 2"); + + my_inifile.saveToStream(output_stream, written); + + expected_stream_content += "[section 1]\n"; + expected_stream_content += "key 1 = value 1\n"; + expected_stream_content += "\n"; + expected_stream_content += "[section 2]\n"; + expected_stream_content += "key 2 = value 2\n\n"; + BOOST_CHECK_EQUAL(output_stream.str(), expected_stream_content); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/jit/global_JIT_manager.h b/src/tests/src/libs/antares/jit/global_JIT_manager.h index c27c8b4d5e..829c4271bc 100644 --- a/src/tests/src/libs/antares/jit/global_JIT_manager.h +++ b/src/tests/src/libs/antares/jit/global_JIT_manager.h @@ -1,17 +1,44 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_TEST_LIBS_JIT_H__ -# define __ANTARES_TEST_LIBS_JIT_H__ +#define __ANTARES_TEST_LIBS_JIT_H__ + +#include "antares/jit/jit.h" class global_JIT_manager { public: - global_JIT_manager(bool turn_to) : JIT_initial(JIT::enabled) - { - JIT::enabled = turn_to; - } - ~global_JIT_manager() { JIT::enabled = JIT_initial; } + global_JIT_manager(bool turn_to): + JIT_initial(JIT::enabled) + { + JIT::enabled = turn_to; + } + + ~global_JIT_manager() + { + JIT::enabled = JIT_initial; + } + private: - bool JIT_initial; + bool JIT_initial; }; - #endif diff --git a/src/tests/src/libs/antares/logs/antares/logs/logs.h b/src/tests/src/libs/antares/logs/antares/logs/logs.h index e64730cccf..afea1f5bd1 100644 --- a/src/tests/src/libs/antares/logs/antares/logs/logs.h +++ b/src/tests/src/libs/antares/logs/antares/logs/logs.h @@ -1,62 +1,111 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __TESTS_ANTARES_LIBS_LOGS_FAKE_H__ -# define __TESTS_ANTARES_LIBS_LOGS_FAKE_H__ +#define __TESTS_ANTARES_LIBS_LOGS_FAKE_H__ #include + #include namespace Antares { - namespace UnitTests - { - - class fakeLogger; - - class Buffer - { - public: - Buffer() = default; - - template - Buffer& operator << (const U& u) - { - // Appending the piece of message to the buffer - buffer_.append(u); - return *this; - } +namespace UnitTests +{ - void clear() { buffer_.clear(); } - std::string content() const { return buffer_.to(); } - bool contains(const std::string sub_string) const { return buffer_.contains(sub_string); } - bool empty() { return buffer_.empty(); } - private: - Yuni::CString<1024> buffer_; - }; +class fakeLogger; +class Buffer +{ +public: + Buffer() = default; + + template + Buffer& operator<<(const U& u) + { + // Appending the piece of message to the buffer + buffer_.append(u); + return *this; + } + + void clear() + { + buffer_.clear(); + } + + std::string content() const + { + return buffer_.to(); + } + + bool contains(const std::string sub_string) const + { + return buffer_.contains(sub_string); + } + + bool empty() + { + return buffer_.empty(); + } + +private: + Yuni::CString<1024> buffer_; +}; + +class fakeLogger +{ +public: + fakeLogger() = default; - class fakeLogger - { - public: - fakeLogger() = default; + Buffer& error() + { + return error_buffer_; + } - Buffer& error() { return error_buffer_; } - Buffer& info() { return info_buffer_; } - Buffer& debug() { return debug_buffer_; } - Buffer& warning() { return warning_buffer_; } + Buffer& info() + { + return info_buffer_; + } - private: - Buffer error_buffer_; - Buffer info_buffer_; - Buffer debug_buffer_; - Buffer warning_buffer_; - }; + Buffer& debug() + { + return debug_buffer_; + } + Buffer& warning() + { + return warning_buffer_; + } - } // UnitTests +private: + Buffer error_buffer_; + Buffer info_buffer_; + Buffer debug_buffer_; + Buffer warning_buffer_; +}; - extern UnitTests::fakeLogger logs; +} // namespace UnitTests -} // Antares +extern UnitTests::fakeLogger logs; -#endif // __TESTS_ANTARES_LIBS_LOGS_FAKE_H__ +} // namespace Antares +#endif // __TESTS_ANTARES_LIBS_LOGS_FAKE_H__ diff --git a/src/tests/src/libs/antares/logs/logs.cpp b/src/tests/src/libs/antares/logs/logs.cpp index 0576c8e778..1bf7096759 100644 --- a/src/tests/src/libs/antares/logs/logs.cpp +++ b/src/tests/src/libs/antares/logs/logs.cpp @@ -1,12 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "antares/logs/logs.h" - - namespace Antares { - //! Our log facility - UnitTests::fakeLogger logs; +//! Our log facility +UnitTests::fakeLogger logs; -} // namespace Antares \ No newline at end of file +} // namespace Antares diff --git a/src/tests/src/libs/antares/study/CMakeLists.txt b/src/tests/src/libs/antares/study/CMakeLists.txt index dcff0a42fd..c4edfc9dfa 100644 --- a/src/tests/src/libs/antares/study/CMakeLists.txt +++ b/src/tests/src/libs/antares/study/CMakeLists.txt @@ -6,3 +6,18 @@ add_subdirectory(output-folder) add_subdirectory(short-term-storage-input) add_subdirectory(thermal-price-definition) add_subdirectory(constraint) +add_subdirectory(parts) +add_subdirectory(series) +add_subdirectory(parameters) + +add_executable(test-study) +target_sources(test-study PRIVATE test_study.cpp) +target_link_libraries(test-study + PRIVATE + Antares::study + Boost::unit_test_framework +) + +add_test(NAME test-study COMMAND test-study) + +set_property(TEST test-study PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/study/area/CMakeLists.txt b/src/tests/src/libs/antares/study/area/CMakeLists.txt index 4743817225..fc726aa02c 100644 --- a/src/tests/src/libs/antares/study/area/CMakeLists.txt +++ b/src/tests/src/libs/antares/study/area/CMakeLists.txt @@ -13,7 +13,7 @@ add_executable(test-save-link-properties ${SRC_LINK_PROPERTIES}) target_include_directories(test-save-link-properties PRIVATE - "${src_libs_antares_study}" + "${src_libs_antares_study}/include" ) target_link_libraries(test-save-link-properties PRIVATE @@ -45,7 +45,7 @@ add_executable(test-save-area-optimization-ini ${SRC_AREA_OPTIMIZATION}) target_include_directories(test-save-area-optimization-ini PRIVATE - "${src_libs_antares_study}" + "${src_libs_antares_study}/include" ) target_link_libraries(test-save-area-optimization-ini PRIVATE diff --git a/src/tests/src/libs/antares/study/area/files-helper.cpp b/src/tests/src/libs/antares/study/area/files-helper.cpp index a6e22bca92..aa050502fb 100644 --- a/src/tests/src/libs/antares/study/area/files-helper.cpp +++ b/src/tests/src/libs/antares/study/area/files-helper.cpp @@ -1,7 +1,28 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include "files-helper.h" + +#include #include #include -#include -#include "files-helper.h" using namespace std; namespace fs = std::filesystem; @@ -12,28 +33,31 @@ namespace fs = std::filesystem; void remove_files(const vector& filesToRemove) { - for (const auto& fileToRemove : filesToRemove) - { - if (fs::exists(fileToRemove)) - fs::remove(fileToRemove); - } + for (const auto& fileToRemove: filesToRemove) + { + if (fs::exists(fileToRemove)) + { + fs::remove(fileToRemove); + } + } } // ================ // Compare files // ================ -string readFileIntoString(const string& path) { - ifstream input_file; - input_file.open(path); - return string(istreambuf_iterator(input_file), istreambuf_iterator()); +string readFileIntoString(const string& path) +{ + ifstream input_file; + input_file.open(path); + return string(istreambuf_iterator(input_file), istreambuf_iterator()); } bool files_identical(const string& fileName_1, const string& fileName_2) { - string content_1 = readFileIntoString(fileName_1); - string content_2 = readFileIntoString(fileName_2); - return content_1 == content_2; + string content_1 = readFileIntoString(fileName_1); + string content_2 = readFileIntoString(fileName_2); + return content_1 == content_2; } // ============================ @@ -42,7 +66,10 @@ bool files_identical(const string& fileName_1, const string& fileName_2) bool fileContainsLine(const string& fileName, string_view line_to_find) { - if (string fileContent = readFileIntoString(fileName); fileContent.find(line_to_find) == string::npos) - return false; - return true; + if (string fileContent = readFileIntoString(fileName); + fileContent.find(line_to_find) == string::npos) + { + return false; + } + return true; } diff --git a/src/tests/src/libs/antares/study/area/files-helper.h b/src/tests/src/libs/antares/study/area/files-helper.h index d8b53f1118..8938860186 100644 --- a/src/tests/src/libs/antares/study/area/files-helper.h +++ b/src/tests/src/libs/antares/study/area/files-helper.h @@ -1,10 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include -#include #include +#include void remove_files(const std::vector& filesToRemove); std::string readFileIntoString(const std::string& path); bool files_identical(const std::string& fileName_1, const std::string& fileName_2); -bool fileContainsLine(const std::string& fileName, std::string_view line_to_find); \ No newline at end of file +bool fileContainsLine(const std::string& fileName, std::string_view line_to_find); diff --git a/src/tests/src/libs/antares/study/area/test-save-area-optimization-ini.cpp b/src/tests/src/libs/antares/study/area/test-save-area-optimization-ini.cpp index 0e3f4163d4..77672b88c2 100644 --- a/src/tests/src/libs/antares/study/area/test-save-area-optimization-ini.cpp +++ b/src/tests/src/libs/antares/study/area/test-save-area-optimization-ini.cpp @@ -1,16 +1,36 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE test save area optimization.ini -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN -#include -#include #include #include +#include + +#include -#include -#include -#include +#include +#include +#include #include "files-helper.h" @@ -22,205 +42,234 @@ const std::string referenceIniFileName = "optimization-reference.ini"; struct Fixture { - Fixture(const Fixture& f) = delete; - Fixture(const Fixture&& f) = delete; - Fixture& operator= (const Fixture& f) = delete; - Fixture& operator= (const Fixture&& f) = delete; - Fixture() : area(study->areaAdd("Area")) - { - path_to_generated_file << fs::current_path().append(generatedIniFileName).string(); - } - - ~Fixture() - { - std::vector filesToRemove = { generatedIniFileName, referenceIniFileName }; - remove_files(filesToRemove); - } - - Study::Ptr study = std::make_shared(); - Area* area; - Yuni::Clob path_to_generated_file; + Fixture(const Fixture& f) = delete; + Fixture(const Fixture&& f) = delete; + Fixture& operator=(const Fixture& f) = delete; + Fixture& operator=(const Fixture&& f) = delete; + + Fixture(): + area(study->areaAdd("Area")) + { + path_to_generated_file << fs::current_path().append(generatedIniFileName); + } + + ~Fixture() + { + std::vector filesToRemove = {generatedIniFileName, referenceIniFileName}; + remove_files(filesToRemove); + } + + Study::Ptr study = std::make_shared(); + Area* area; + Yuni::Clob path_to_generated_file; }; class referenceIniFile { public: - referenceIniFile(); - ~referenceIniFile() = default; - std::string name() const { return name_; } - void save(); + referenceIniFile(); + ~referenceIniFile() = default; + + std::string name() const + { + return name_; + } + + void save(); + + void set_property(const std::string& key, const std::string& value) + { + properties_[key] = value; + } - void set_property(const std::string& key, const std::string& value) { properties_[key] = value; } private: - void save_section(std::string_view sectionTitle, std::vector& section_properties, std::ofstream& file); - - std::string name_ = referenceIniFileName; - std::vector nodal_property_names_ = { - "non-dispatchable-power", "dispatchable-hydro-power", "other-dispatchable-power", - "spread-unsupplied-energy-cost", "spread-spilled-energy-cost" }; - std::vector filtering_property_names_ = { "filter-synthesis", "filter-year-by-year" }; - std::map> properties_; + void save_section(std::string_view sectionTitle, + std::vector& section_properties, + std::ofstream& file); + + std::string name_ = referenceIniFileName; + std::vector nodal_property_names_ = {"non-dispatchable-power", + "dispatchable-hydro-power", + "other-dispatchable-power", + "spread-unsupplied-energy-cost", + "spread-spilled-energy-cost"}; + std::vector filtering_property_names_ = {"filter-synthesis", + "filter-year-by-year"}; + std::map> properties_; }; referenceIniFile::referenceIniFile() { - properties_[nodal_property_names_[0]] = "true"; - properties_[nodal_property_names_[1]] = "true"; - properties_[nodal_property_names_[2]] = "true"; - properties_[nodal_property_names_[3]] = "0.000000"; - properties_[nodal_property_names_[4]] = "0.000000"; - properties_[filtering_property_names_[0]] = "hourly, daily, weekly, monthly, annual"; - properties_[filtering_property_names_[1]] = "hourly, daily, weekly, monthly, annual"; + properties_[nodal_property_names_[0]] = "true"; + properties_[nodal_property_names_[1]] = "true"; + properties_[nodal_property_names_[2]] = "true"; + properties_[nodal_property_names_[3]] = "0.000000"; + properties_[nodal_property_names_[4]] = "0.000000"; + properties_[filtering_property_names_[0]] = "hourly, daily, weekly, monthly, annual"; + properties_[filtering_property_names_[1]] = "hourly, daily, weekly, monthly, annual"; } void referenceIniFile::save() { - std::ofstream file; - file.open(name_); - save_section("[nodal optimization]", nodal_property_names_, file); - save_section("[filtering]", filtering_property_names_, file); - file.close(); + std::ofstream file; + file.open(name_); + save_section("[nodal optimization]", nodal_property_names_, file); + save_section("[filtering]", filtering_property_names_, file); + file.close(); } -void referenceIniFile::save_section(std::string_view sectionTitle, std::vector& sectionProperties, std::ofstream & file) +void referenceIniFile::save_section(std::string_view sectionTitle, + std::vector& sectionProperties, + std::ofstream& file) { - file << sectionTitle << std::endl; - for (std::size_t i = 0; i < sectionProperties.size(); ++i) - file << sectionProperties[i] << " = " << properties_[sectionProperties[i]] << std::endl; - file << std::endl; + file << sectionTitle << std::endl; + for (std::size_t i = 0; i < sectionProperties.size(); ++i) + { + file << sectionProperties[i] << " = " << properties_[sectionProperties[i]] << std::endl; + } + file << std::endl; } BOOST_AUTO_TEST_SUITE(s) BOOST_FIXTURE_TEST_CASE(one_area_with_default_params, Fixture) { - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - referenceIniFile referenceFile; - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } BOOST_FIXTURE_TEST_CASE(one_area_with_none_default_params, Fixture) { - area->nodalOptimization = 0; - area->spreadUnsuppliedEnergyCost = 2.; - area->spreadSpilledEnergyCost = 3.; - area->filterSynthesis = filterNone; - area->filterYearByYear = filterHourly | filterDaily; - - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - - referenceIniFile referenceFile; - referenceFile.set_property("non-dispatchable-power", "false"); - referenceFile.set_property("dispatchable-hydro-power", "false"); - referenceFile.set_property("other-dispatchable-power", "false"); - referenceFile.set_property("spread-unsupplied-energy-cost", "2.000000"); - referenceFile.set_property("spread-spilled-energy-cost", "3.000000"); - referenceFile.set_property("filter-synthesis", ""); - referenceFile.set_property("filter-year-by-year", "hourly, daily"); - referenceFile.save(); - - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + area->nodalOptimization = 0; + area->spreadUnsuppliedEnergyCost = 2.; + area->spreadSpilledEnergyCost = 3.; + area->filterSynthesis = filterNone; + area->filterYearByYear = filterHourly | filterDaily; + + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + + referenceIniFile referenceFile; + referenceFile.set_property("non-dispatchable-power", "false"); + referenceFile.set_property("dispatchable-hydro-power", "false"); + referenceFile.set_property("other-dispatchable-power", "false"); + referenceFile.set_property("spread-unsupplied-energy-cost", "2.000000"); + referenceFile.set_property("spread-spilled-energy-cost", "3.000000"); + referenceFile.set_property("filter-synthesis", ""); + referenceFile.set_property("filter-year-by-year", "hourly, daily"); + referenceFile.save(); + + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } -BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_nonDispatchPower__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_nonDispatchPower__other_params_to_default, + Fixture) { - area->nodalOptimization = anoNonDispatchPower; + area->nodalOptimization = anoNonDispatchPower; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - referenceIniFile referenceFile; - referenceFile.set_property("non-dispatchable-power", "true"); - referenceFile.set_property("dispatchable-hydro-power", "false"); - referenceFile.set_property("other-dispatchable-power", "false"); - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.set_property("non-dispatchable-power", "true"); + referenceFile.set_property("dispatchable-hydro-power", "false"); + referenceFile.set_property("other-dispatchable-power", "false"); + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } - - -BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_dispatchHydroPower__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_dispatchHydroPower__other_params_to_default, + Fixture) { - area->nodalOptimization = anoDispatchHydroPower; + area->nodalOptimization = anoDispatchHydroPower; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - referenceIniFile referenceFile; - referenceFile.set_property("non-dispatchable-power", "false"); - referenceFile.set_property("dispatchable-hydro-power", "true"); - referenceFile.set_property("other-dispatchable-power", "false"); - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.set_property("non-dispatchable-power", "false"); + referenceFile.set_property("dispatchable-hydro-power", "true"); + referenceFile.set_property("other-dispatchable-power", "false"); + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } -BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_otherDispatchablePower__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_otherDispatchablePower__other_params_to_default, + Fixture) { - area->nodalOptimization = anoOtherDispatchPower; + area->nodalOptimization = anoOtherDispatchPower; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - referenceIniFile referenceFile; - referenceFile.set_property("non-dispatchable-power", "false"); - referenceFile.set_property("dispatchable-hydro-power", "false"); - referenceFile.set_property("other-dispatchable-power", "true"); - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.set_property("non-dispatchable-power", "false"); + referenceFile.set_property("dispatchable-hydro-power", "false"); + referenceFile.set_property("other-dispatchable-power", "true"); + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } -BOOST_FIXTURE_TEST_CASE(one_area_with_nodal_opt_to_non_or_other_DispatchPower__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE( + one_area_with_nodal_opt_to_non_or_other_DispatchPower__other_params_to_default, + Fixture) { - area->nodalOptimization = anoOtherDispatchPower | anoNonDispatchPower; + area->nodalOptimization = anoOtherDispatchPower | anoNonDispatchPower; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - referenceIniFile referenceFile; - referenceFile.set_property("non-dispatchable-power", "true"); - referenceFile.set_property("dispatchable-hydro-power", "false"); - referenceFile.set_property("other-dispatchable-power", "true"); - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.set_property("non-dispatchable-power", "true"); + referenceFile.set_property("dispatchable-hydro-power", "false"); + referenceFile.set_property("other-dispatchable-power", "true"); + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceIniFileName)); + BOOST_CHECK(files_identical(generatedIniFileName, referenceIniFileName)); } -BOOST_FIXTURE_TEST_CASE(one_area_with_unsupplied_energy_cost_negative__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_unsupplied_energy_cost_negative__other_params_to_default, + Fixture) { - area->spreadUnsuppliedEnergyCost = -1.; + area->spreadUnsuppliedEnergyCost = -1.; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "spread-unsupplied-energy-cost = -1.000000")); + BOOST_CHECK( + fileContainsLine(generatedIniFileName, "spread-unsupplied-energy-cost = -1.000000")); } -BOOST_FIXTURE_TEST_CASE(one_area_with_spilled_energy_cost_negative__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_spilled_energy_cost_negative__other_params_to_default, + Fixture) { - area->spreadSpilledEnergyCost = -1.; + area->spreadSpilledEnergyCost = -1.; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "spread-spilled-energy-cost = -1.000000")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "spread-spilled-energy-cost = -1.000000")); } -BOOST_FIXTURE_TEST_CASE(one_area_with_synthesis_to_hourly_monthly_annual__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_synthesis_to_hourly_monthly_annual__other_params_to_default, + Fixture) { - area->filterSynthesis = filterWeekly | filterMonthly | filterAnnual; + area->filterSynthesis = filterWeekly | filterMonthly | filterAnnual; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "filter-synthesis = weekly, monthly, annual")); + BOOST_CHECK( + fileContainsLine(generatedIniFileName, "filter-synthesis = weekly, monthly, annual")); } -BOOST_FIXTURE_TEST_CASE(one_area_with_year_by_year_to_daily_monthly__other_params_to_default, Fixture) +BOOST_FIXTURE_TEST_CASE(one_area_with_year_by_year_to_daily_monthly__other_params_to_default, + Fixture) { - area->filterYearByYear = filterDaily | filterMonthly; + area->filterYearByYear = filterDaily | filterMonthly; - BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); + BOOST_CHECK(saveAreaOptimisationIniFile(*area, path_to_generated_file)); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "filter-year-by-year = daily, monthly")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "filter-year-by-year = daily, monthly")); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/area/test-save-link-properties.cpp b/src/tests/src/libs/antares/study/area/test-save-link-properties.cpp index 584b0d2861..305241cd3e 100644 --- a/src/tests/src/libs/antares/study/area/test-save-link-properties.cpp +++ b/src/tests/src/libs/antares/study/area/test-save-link-properties.cpp @@ -1,17 +1,37 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE test save link properties.ini -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include #include #include +#include +#include +#include -#include -#include +#include + +#include +#include #include "files-helper.h" @@ -25,223 +45,250 @@ const string referenceIniFileName = "properties-reference.ini"; class referenceIniFile { public: - referenceIniFile(); - ~referenceIniFile() = default; - string name() const { return name_; } - void save(); + referenceIniFile(); + ~referenceIniFile() = default; - void set_property(const string & key, const string & value) { properties_[key] = value; } -private: - string name_ = referenceIniFileName; + string name() const + { + return name_; + } - // Keeps the properties ordered in the file - vector property_names_ = { - "hurdles-cost", "loop-flow", "use-phase-shifter", "transmission-capacities", - "asset-type", "link-style", "link-width", "colorr", "colorg", "colorb", - "display-comments", "filter-synthesis", "filter-year-by-year" }; + void save(); - map> properties_; + void set_property(const string& key, const string& value) + { + properties_[key] = value; + } + +private: + string name_ = referenceIniFileName; + + // Keeps the properties ordered in the file + vector property_names_ = {"hurdles-cost", + "loop-flow", + "use-phase-shifter", + "transmission-capacities", + "asset-type", + "link-style", + "link-width", + "colorr", + "colorg", + "colorb", + "display-comments", + "filter-synthesis", + "filter-year-by-year"}; + + map> properties_; }; referenceIniFile::referenceIniFile() { - properties_[property_names_[0]] = "false"; - properties_[property_names_[1]] = "false"; - properties_[property_names_[2]] = "false"; - properties_[property_names_[3]] = "enabled"; - properties_[property_names_[4]] = "ac"; - properties_[property_names_[5]] = "plain"; - properties_[property_names_[6]] = "1"; - properties_[property_names_[7]] = "112"; - properties_[property_names_[8]] = "112"; - properties_[property_names_[9]] = "112"; - properties_[property_names_[10]] = "true"; - properties_[property_names_[11]] = "hourly, daily, weekly, monthly, annual"; - properties_[property_names_[12]] = "hourly, daily, weekly, monthly, annual"; + properties_[property_names_[0]] = "false"; + properties_[property_names_[1]] = "false"; + properties_[property_names_[2]] = "false"; + properties_[property_names_[3]] = "enabled"; + properties_[property_names_[4]] = "ac"; + properties_[property_names_[5]] = "plain"; + properties_[property_names_[6]] = "1"; + properties_[property_names_[7]] = "112"; + properties_[property_names_[8]] = "112"; + properties_[property_names_[9]] = "112"; + properties_[property_names_[10]] = "true"; + properties_[property_names_[11]] = "hourly, daily, weekly, monthly, annual"; + properties_[property_names_[12]] = "hourly, daily, weekly, monthly, annual"; } void referenceIniFile::save() { - ofstream file; - file.open(name_); - file << "[area 2]" << endl; - for (std::size_t i = 0; i < property_names_.size(); ++i) - file << property_names_[i] << " = " << properties_[property_names_[i]] << endl; - file << endl; - file.close(); + ofstream file; + file.open(name_); + file << "[area 2]" << endl; + for (std::size_t i = 0; i < property_names_.size(); ++i) + { + file << property_names_[i] << " = " << properties_[property_names_[i]] << endl; + } + file << endl; + file.close(); } - struct Fixture { - Fixture(const Fixture & f) = delete; - Fixture(const Fixture && f) = delete; - Fixture & operator= (const Fixture & f) = delete; - Fixture& operator= (const Fixture && f) = delete; - Fixture() : study(std::make_shared()) - { - area_1 = study->areaAdd("Area 1"); - area_2 = study->areaAdd("Area 2"); - } - - ~Fixture() - { - vector filesToRemove = { generatedIniFileName, referenceIniFileName }; - remove_files(filesToRemove); - } - - Study::Ptr study; - Area* area_1; - Area* area_2; + Fixture(const Fixture& f) = delete; + Fixture(const Fixture&& f) = delete; + Fixture& operator=(const Fixture& f) = delete; + Fixture& operator=(const Fixture&& f) = delete; + + Fixture(): + study(std::make_shared()) + { + area_1 = study->areaAdd("Area 1"); + area_2 = study->areaAdd("Area 2"); + } + + ~Fixture() + { + vector filesToRemove = {generatedIniFileName, referenceIniFileName}; + remove_files(filesToRemove); + } + + Study::Ptr study; + Area* area_1; + Area* area_2; }; AreaLink* createLinkBetweenAreas(Area* a1, Area* a2) { - AreaLink* link = AreaAddLinkBetweenAreas(a1, a2, false); - return link; + AreaLink* link = AreaAddLinkBetweenAreas(a1, a2, false); + return link; } void saveAreaLinksOntoDisk(Area* area) { - BOOST_CHECK(saveAreaLinksConfigurationFileToFolder(area, fs::current_path().string().c_str())); + BOOST_CHECK(saveAreaLinksConfigurationFileToFolder(area, fs::current_path().string().c_str())); } BOOST_AUTO_TEST_SUITE(s) BOOST_FIXTURE_TEST_CASE(one_link_with_default_values, Fixture) { - createLinkBetweenAreas(area_1, area_2); + createLinkBetweenAreas(area_1, area_2); - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - referenceIniFile referenceFile; - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } - BOOST_FIXTURE_TEST_CASE(one_link_with_none_default_values, Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->useHurdlesCost = true; - link->useLoopFlow = true; - link->usePST = true; - link->transmissionCapacities = LocalTransmissionCapacities::infinite; - link->assetType = atDC; - link->style = stDash; - link->linkWidth = 3; - link->color[0] = 10; - link->color[1] = 9; - link->color[2] = 8; - link->displayComments = false; - link->filterSynthesis = filterNone; - link->filterYearByYear = filterHourly | filterDaily; - - saveAreaLinksOntoDisk(area_1); - - referenceIniFile referenceFile; - referenceFile.set_property("hurdles-cost", "true"); - referenceFile.set_property("loop-flow", "true"); - referenceFile.set_property("use-phase-shifter", "true"); - referenceFile.set_property("transmission-capacities", "infinite"); - referenceFile.set_property("asset-type", "dc"); - referenceFile.set_property("link-style", "dash"); - referenceFile.set_property("link-width", "3"); - referenceFile.set_property("colorr", "10"); - referenceFile.set_property("colorg", "9"); - referenceFile.set_property("colorb", "8"); - referenceFile.set_property("display-comments", "false"); - referenceFile.set_property("filter-synthesis", ""); - referenceFile.set_property("filter-year-by-year", "hourly, daily"); - referenceFile.save(); - - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->useHurdlesCost = true; + link->useLoopFlow = true; + link->usePST = true; + link->transmissionCapacities = LocalTransmissionCapacities::infinite; + link->assetType = atDC; + link->style = stDash; + link->linkWidth = 3; + link->color[0] = 10; + link->color[1] = 9; + link->color[2] = 8; + link->displayComments = false; + link->filterSynthesis = filterNone; + link->filterYearByYear = filterHourly | filterDaily; + + saveAreaLinksOntoDisk(area_1); + + referenceIniFile referenceFile; + referenceFile.set_property("hurdles-cost", "true"); + referenceFile.set_property("loop-flow", "true"); + referenceFile.set_property("use-phase-shifter", "true"); + referenceFile.set_property("transmission-capacities", "infinite"); + referenceFile.set_property("asset-type", "dc"); + referenceFile.set_property("link-style", "dash"); + referenceFile.set_property("link-width", "3"); + referenceFile.set_property("colorr", "10"); + referenceFile.set_property("colorg", "9"); + referenceFile.set_property("colorb", "8"); + referenceFile.set_property("display-comments", "false"); + referenceFile.set_property("filter-synthesis", ""); + referenceFile.set_property("filter-year-by-year", "hourly, daily"); + referenceFile.save(); + + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } - -BOOST_FIXTURE_TEST_CASE(one_link_with_transmission_capacity_to_ignore__all_others_properties_are_default, Fixture) +BOOST_FIXTURE_TEST_CASE( + one_link_with_transmission_capacity_to_ignore__all_others_properties_are_default, + Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->transmissionCapacities = LocalTransmissionCapacities::null; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->transmissionCapacities = LocalTransmissionCapacities::null; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - referenceIniFile referenceFile; - referenceFile.set_property("transmission-capacities", "ignore"); - referenceFile.save(); + referenceIniFile referenceFile; + referenceFile.set_property("transmission-capacities", "ignore"); + referenceFile.save(); - BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); + BOOST_CHECK(files_identical(generatedIniFileName, referenceFile.name())); } BOOST_FIXTURE_TEST_CASE(one_link_with_asset_type_to_gas__ini_file_contains_matching_line, Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->assetType = atGas; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->assetType = atGas; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "asset-type = gaz")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "asset-type = gaz")); } -BOOST_FIXTURE_TEST_CASE(one_link_with_asset_type_to_virtual__ini_file_contains_matching_line, Fixture) +BOOST_FIXTURE_TEST_CASE(one_link_with_asset_type_to_virtual__ini_file_contains_matching_line, + Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->assetType = atVirt; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->assetType = atVirt; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "asset-type = virt")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "asset-type = virt")); } BOOST_FIXTURE_TEST_CASE(one_link_with_asset_type_to_other__ini_file_contains_matching_line, Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->assetType = atOther; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->assetType = atOther; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "asset-type = other")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "asset-type = other")); } BOOST_FIXTURE_TEST_CASE(one_link_with_style_to_dot__ini_file_contains_matching_line, Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->style = stDot; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->style = stDot; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "link-style = dot")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "link-style = dot")); } BOOST_FIXTURE_TEST_CASE(one_link_with_style_to_dotdash__ini_file_contains_matching_line, Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->style = stDotDash; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->style = stDotDash; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "link-style = dotdash")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "link-style = dotdash")); } -BOOST_FIXTURE_TEST_CASE(one_link_with_synthesis_to_hourly_monthly_annual__ini_file_contains_matching_line, Fixture) +BOOST_FIXTURE_TEST_CASE( + one_link_with_synthesis_to_hourly_monthly_annual__ini_file_contains_matching_line, + Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->filterSynthesis = filterWeekly | filterMonthly | filterAnnual; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->filterSynthesis = filterWeekly | filterMonthly | filterAnnual; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "filter-synthesis = weekly, monthly, annual")); + BOOST_CHECK( + fileContainsLine(generatedIniFileName, "filter-synthesis = weekly, monthly, annual")); } -BOOST_FIXTURE_TEST_CASE(one_link_with_year_by_year_to_daily_monthly__ini_file_contains_matching_line, Fixture) +BOOST_FIXTURE_TEST_CASE( + one_link_with_year_by_year_to_daily_monthly__ini_file_contains_matching_line, + Fixture) { - AreaLink* link = createLinkBetweenAreas(area_1, area_2); - link->filterYearByYear = filterDaily | filterMonthly; + AreaLink* link = createLinkBetweenAreas(area_1, area_2); + link->filterYearByYear = filterDaily | filterMonthly; - saveAreaLinksOntoDisk(area_1); + saveAreaLinksOntoDisk(area_1); - BOOST_CHECK(fileContainsLine(generatedIniFileName, "filter-year-by-year = daily, monthly")); + BOOST_CHECK(fileContainsLine(generatedIniFileName, "filter-year-by-year = daily, monthly")); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/constraint/test_constraint.cpp b/src/tests/src/libs/antares/study/constraint/test_constraint.cpp index a671d7857c..e6e5cd54c3 100644 --- a/src/tests/src/libs/antares/study/constraint/test_constraint.cpp +++ b/src/tests/src/libs/antares/study/constraint/test_constraint.cpp @@ -1,26 +1,47 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ // // Created by marechaljas on 13/03/23. // #define WIN32_LEAN_AND_MEAN #define BOOST_TEST_MODULE binding_constraints -#define BOOST_TEST_DYN_LINK + +#include +#include +#include #include -#include -#include "antares/study/constraint.h" -#include "antares/study/area/area.h" #include -#include -#include "utils.h" +#include "antares/study/area/area.h" +#include "antares/study/constraint.h" using namespace Antares::Data; namespace fs = std::filesystem; BOOST_AUTO_TEST_SUITE(BindingConstraintTests) -BOOST_AUTO_TEST_CASE( load_basic_attributes ) { +BOOST_AUTO_TEST_CASE(load_basic_attributes) +{ auto study = std::make_shared(); StudyLoadOptions options; @@ -31,21 +52,22 @@ BOOST_AUTO_TEST_CASE( load_basic_attributes ) { std::ofstream constraints(working_tmp_dir / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" - <<"id = dummy_id\n" + << "id = dummy_id\n" << "enabled = false\n" << "type = hourly\n" << "operator = equal\n" << "filter-year-by-year = annual\n" << "filter-synthesis = hourly\n" << "comments = dummy_comment\n" - << "group = dummy_group\n" - ; + << "group = dummy_group\n"; constraints.close(); std::ofstream rhs(working_tmp_dir / "dummy_id_eq.txt"); rhs.close(); - study->header.version = version870; - const bool loading_ok = bindingConstraints.loadFromFolder(*study, options, working_tmp_dir.string()); + study->header.version = StudyVersion(8, 7); + const bool loading_ok = bindingConstraints.loadFromFolder(*study, + options, + working_tmp_dir.string()); BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(bindingConstraints.size(), 1); @@ -62,7 +84,8 @@ BOOST_AUTO_TEST_CASE( load_basic_attributes ) { BOOST_CHECK_EQUAL(constraint->group(), "dummy_group"); } -BOOST_AUTO_TEST_CASE(BC_load_RHS) { +BOOST_AUTO_TEST_CASE(BC_load_RHS) +{ auto study = std::make_shared(); study->areaAdd("area1"); study->areaAdd("area2"); @@ -76,7 +99,7 @@ BOOST_AUTO_TEST_CASE(BC_load_RHS) { std::ofstream constraints(working_tmp_dir / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" - <<"id = dummy_id\n" + << "id = dummy_id\n" << "enabled = false\n" << "type = hourly\n" << "operator = equal\n" @@ -86,16 +109,18 @@ BOOST_AUTO_TEST_CASE(BC_load_RHS) { << "group = dummy_group\n" << "area1%area2 = 1.000000\n" << "area2%area3 = -1.000000\n" - << "area3%area1 = 2.000000\n" - ; + << "area3%area1 = 2.000000\n"; constraints.close(); std::ofstream rhs(working_tmp_dir / "dummy_id_eq.txt"); - for (int i = 0; i < 8784; ++i) { + for (int i = 0; i < 8784; ++i) + { rhs << "0.2\t0.4\t0.6\n"; } rhs.close(); - study->header.version = version870; - const bool loading_ok = bindingConstraints.loadFromFolder(*study, options, working_tmp_dir.string()); + study->header.version = StudyVersion(8, 7); + const bool loading_ok = bindingConstraints.loadFromFolder(*study, + options, + working_tmp_dir.string()); BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(bindingConstraints.size(), 1); @@ -106,7 +131,8 @@ BOOST_AUTO_TEST_CASE(BC_load_RHS) { BOOST_CHECK_CLOSE(constraint->RHSTimeSeries()[2][8783], 0.6, 0.0001); } -BOOST_AUTO_TEST_CASE(BC_load_range_type) { +BOOST_AUTO_TEST_CASE(BC_load_range_type) +{ auto study = std::make_shared(); study->areaAdd("area1"); study->areaAdd("area2"); @@ -120,7 +146,7 @@ BOOST_AUTO_TEST_CASE(BC_load_range_type) { std::ofstream constraints(working_tmp_dir / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" - <<"id = dummy_id\n" + << "id = dummy_id\n" << "enabled = false\n" << "type = hourly\n" << "operator = both\n" @@ -130,32 +156,36 @@ BOOST_AUTO_TEST_CASE(BC_load_range_type) { << "group = dummy_group\n" << "area1%area2 = 1.000000\n" << "area2%area3 = -1.000000\n" - << "area3%area1 = 2.000000\n" - ; + << "area3%area1 = 2.000000\n"; constraints.close(); std::ofstream lt(working_tmp_dir / "dummy_id_lt.txt"); - for (int i = 0; i < 8784; ++i) { + for (int i = 0; i < 8784; ++i) + { lt << "0.2\t0.4\t0.6\n"; } lt.close(); std::ofstream gt(working_tmp_dir / "dummy_id_gt.txt"); - for (int i = 0; i < 8784; ++i) { + for (int i = 0; i < 8784; ++i) + { gt << "0.4\t0.6\t0.8\n"; } gt.close(); - study->header.version = version870; - const bool loading_ok = bindingConstraints.loadFromFolder(*study, options, working_tmp_dir.string()); + study->header.version = StudyVersion(8, 7); + const bool loading_ok = bindingConstraints.loadFromFolder(*study, + options, + working_tmp_dir.string()); BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(bindingConstraints.size(), 2); - auto bc_lt = std::find_if(bindingConstraints.begin(), bindingConstraints.end(), [](auto bc){ - return bc->operatorType() == BindingConstraint::opLess; - }); - auto bc_gt = std::find_if(bindingConstraints.begin(), bindingConstraints.end(), [](auto bc){ - return bc->operatorType() == BindingConstraint::opGreater; - }); - + auto bc_lt = std::find_if(bindingConstraints.begin(), + bindingConstraints.end(), + [](auto bc) + { return bc->operatorType() == BindingConstraint::opLess; }); + auto bc_gt = std::find_if(bindingConstraints.begin(), + bindingConstraints.end(), + [](auto bc) + { return bc->operatorType() == BindingConstraint::opGreater; }); BOOST_CHECK(bc_lt != bindingConstraints.end()); BOOST_CHECK_CLOSE((*bc_lt)->RHSTimeSeries()[0][0], 0.2, 0.0001); @@ -168,7 +198,8 @@ BOOST_AUTO_TEST_CASE(BC_load_range_type) { BOOST_CHECK_CLOSE((*bc_gt)->RHSTimeSeries()[2][8783], 0.8, 0.0001); } -BOOST_AUTO_TEST_CASE(BC_load_legacy) { +BOOST_AUTO_TEST_CASE(BC_load_legacy) +{ auto study = std::make_shared(); study->areaAdd("area1"); study->areaAdd("area2"); @@ -182,7 +213,7 @@ BOOST_AUTO_TEST_CASE(BC_load_legacy) { std::ofstream constraints(working_tmp_dir / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" - <<"id = dummy_id\n" + << "id = dummy_id\n" << "enabled = false\n" << "type = hourly\n" << "operator = less\n" @@ -191,17 +222,19 @@ BOOST_AUTO_TEST_CASE(BC_load_legacy) { << "comments = dummy_comment\n" << "area1%area2 = 1.000000\n" << "area2%area3 = -1.000000\n" - << "area3%area1 = 2.000000\n" - ; + << "area3%area1 = 2.000000\n"; constraints.close(); std::ofstream lt(working_tmp_dir / "dummy_id.txt"); - for (int i = 0; i < 8784; ++i) { + for (int i = 0; i < 8784; ++i) + { lt << "0.2\t0.4\t0.6\n"; } lt.close(); - study->header.version = version860; - const bool loading_ok = bindingConstraints.loadFromFolder(*study, options, working_tmp_dir.string()); + study->header.version = StudyVersion(8, 6); + const bool loading_ok = bindingConstraints.loadFromFolder(*study, + options, + working_tmp_dir.string()); BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(bindingConstraints.size(), 1); @@ -212,7 +245,8 @@ BOOST_AUTO_TEST_CASE(BC_load_legacy) { BOOST_CHECK_CLOSE(bc_lt->RHSTimeSeries()[0][8783], 0.2, 0.0001); } -BOOST_AUTO_TEST_CASE(BC_load_legacy_range) { +BOOST_AUTO_TEST_CASE(BC_load_legacy_range) +{ auto study = std::make_shared(); study->areaAdd("area1"); study->areaAdd("area2"); @@ -226,7 +260,7 @@ BOOST_AUTO_TEST_CASE(BC_load_legacy_range) { std::ofstream constraints(working_tmp_dir / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" - <<"id = dummy_id\n" + << "id = dummy_id\n" << "enabled = false\n" << "type = hourly\n" << "operator = both\n" @@ -235,27 +269,31 @@ BOOST_AUTO_TEST_CASE(BC_load_legacy_range) { << "comments = dummy_comment\n" << "area1%area2 = 1.000000\n" << "area2%area3 = -1.000000\n" - << "area3%area1 = 2.000000\n" - ; + << "area3%area1 = 2.000000\n"; constraints.close(); std::ofstream lt(working_tmp_dir / "dummy_id.txt"); - for (int i = 0; i < 8784; ++i) { + for (int i = 0; i < 8784; ++i) + { lt << "0.2\t0.4\t0.6\n"; } lt.close(); - study->header.version = version860; - const bool loading_ok = bindingConstraints.loadFromFolder(*study, options, working_tmp_dir.string()); + study->header.version = StudyVersion(8, 6); + const bool loading_ok = bindingConstraints.loadFromFolder(*study, + options, + working_tmp_dir.string()); BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(bindingConstraints.size(), 2); - auto bc_lt = std::find_if(bindingConstraints.begin(), bindingConstraints.end(), [](auto bc){ - return bc->operatorType() == BindingConstraint::opLess; - }); - auto bc_gt = std::find_if(bindingConstraints.begin(), bindingConstraints.end(), [](auto bc){ - return bc->operatorType() == BindingConstraint::opGreater; - }); + auto bc_lt = std::find_if(bindingConstraints.begin(), + bindingConstraints.end(), + [](auto bc) + { return bc->operatorType() == BindingConstraint::opLess; }); + auto bc_gt = std::find_if(bindingConstraints.begin(), + bindingConstraints.end(), + [](auto bc) + { return bc->operatorType() == BindingConstraint::opGreater; }); BOOST_CHECK(bc_lt != bindingConstraints.end()); BOOST_CHECK(bc_gt != bindingConstraints.end()); diff --git a/src/tests/src/libs/antares/study/constraint/test_group.cpp b/src/tests/src/libs/antares/study/constraint/test_group.cpp index c53f3c855d..21f5c7377a 100644 --- a/src/tests/src/libs/antares/study/constraint/test_group.cpp +++ b/src/tests/src/libs/antares/study/constraint/test_group.cpp @@ -1,49 +1,75 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ // // Created by marechaljas on 28/06/23. // #define BOOST_TEST_MODULE binding_constraints_groups -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN -#include +#include #include #include #include + +#include + #include "antares/study/study.h" -#include "utils.h" using namespace Antares::Data; namespace fs = std::filesystem; -class PublicStudy: public Study { +class PublicStudy: public Study +{ public: - bool internalLoadBindingConstraints(const StudyLoadOptions& options) override { + bool internalLoadBindingConstraints(const StudyLoadOptions& options) override + { return Study::internalLoadBindingConstraints(options); } }; -struct Fixture { - Fixture() { +struct Fixture +{ + Fixture() + { fs::create_directories(working_tmp_dir / "bindingconstraints"); - study->header.version = version870; + study->header.version = StudyVersion(8, 7); study->folderInput = working_tmp_dir.string(); } - void addConstraint(const std::string& name, const std::string& group) const { - std::ofstream constraints(working_tmp_dir / "bindingconstraints" / "bindingconstraints.ini", std::ios_base::app); + void addConstraint(const std::string& name, const std::string& group) const + { + std::ofstream constraints(working_tmp_dir / "bindingconstraints" / "bindingconstraints.ini", + std::ios_base::app); static unsigned constraintNumber = 1; constraints << "[" << constraintNumber++ << "]\n" << "name = " << name << "\n" - <<"id = " << name << "\n" + << "id = " << name << "\n" << "enabled = false\n" << "type = hourly\n" << "operator = equal\n" << "filter-year-by-year = annual\n" << "filter-synthesis = hourly\n" << "comments = dummy_comment\n" - << "group = " << group << "\n" - ; + << "group = " << group << "\n"; constraints.close(); - std::ofstream rhs(working_tmp_dir / "bindingconstraints"/ (name+"_eq.txt")); + std::ofstream rhs(working_tmp_dir / "bindingconstraints" / (name + "_eq.txt")); rhs.close(); } @@ -52,9 +78,10 @@ struct Fixture { std::filesystem::path working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); }; -BOOST_FIXTURE_TEST_SUITE(BindingConstraintTests_Groups, Fixture) +BOOST_AUTO_TEST_SUITE(BindingConstraintTests_Groups) -BOOST_AUTO_TEST_CASE(WhenLoadingAConstraint_AGroupExists) { +BOOST_FIXTURE_TEST_CASE(WhenLoadingAConstraint_AGroupExists, Fixture) +{ addConstraint("dummy_name", "dummy_group"); const bool loading_ok = study->internalLoadBindingConstraints(options); @@ -75,12 +102,13 @@ BOOST_AUTO_TEST_CASE(WhenLoadingAConstraint_AGroupExists) { BOOST_CHECK_EQUAL(constraint->group(), "dummy_group"); } -BOOST_AUTO_TEST_CASE(WhenLoadingsConstraints_AllGroupExists) { +BOOST_FIXTURE_TEST_CASE(WhenLoadingsConstraints_AllGroupExists, Fixture) +{ addConstraint("dummy_name_1", "dummy_group_uno"); addConstraint("dummy_name_2", "dummy_group_uno"); addConstraint("dummy_name_3", "dummy_group_other"); - study->header.version = version870; + study->header.version = StudyVersion(8, 7); study->folderInput = working_tmp_dir.string(); const bool loading_ok = study->internalLoadBindingConstraints(options); @@ -90,12 +118,13 @@ BOOST_AUTO_TEST_CASE(WhenLoadingsConstraints_AllGroupExists) { BOOST_CHECK_EQUAL(study->bindingConstraintsGroups.size(), 2); } -BOOST_AUTO_TEST_CASE(WhenLoadingsConstraints_AllGroupsNonEmpty) { +BOOST_FIXTURE_TEST_CASE(WhenLoadingsConstraints_AllGroupsNonEmpty, Fixture) +{ addConstraint("dummy_name_1", "dummy_group_uno"); addConstraint("dummy_name_2", "dummy_group_uno"); addConstraint("dummy_name_3", "dummy_group_other"); - study->header.version = version870; + study->header.version = StudyVersion(8, 7); study->folderInput = working_tmp_dir.string(); const bool loading_ok = study->internalLoadBindingConstraints(options); @@ -103,10 +132,9 @@ BOOST_AUTO_TEST_CASE(WhenLoadingsConstraints_AllGroupsNonEmpty) { BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(study->bindingConstraints.size(), 3); BOOST_CHECK_EQUAL(study->bindingConstraintsGroups.size(), 2); - BOOST_CHECK(std::all_of(study->bindingConstraintsGroups.begin(), study->bindingConstraintsGroups.end(), - [](const auto& group){ - return !group->constraints().empty(); - })); + BOOST_CHECK(std::all_of(study->bindingConstraintsGroups.begin(), + study->bindingConstraintsGroups.end(), + [](const auto& group) { return !group->constraints().empty(); })); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/output-folder/study.cpp b/src/tests/src/libs/antares/study/output-folder/study.cpp index 9f55894126..1675ae7909 100644 --- a/src/tests/src/libs/antares/study/output-folder/study.cpp +++ b/src/tests/src/libs/antares/study/output-folder/study.cpp @@ -1,15 +1,35 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE output folder -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include #include // setenv +#include +#include +#include + +#include -#include +#include // Test the generation of folder output names // We expect something like outputRoot/20221230-0914eco-test @@ -25,7 +45,9 @@ struct Fixture Fixture(const Fixture&& f) = delete; Fixture& operator=(const Fixture& f) = delete; Fixture& operator=(const Fixture&& f) = delete; - Fixture() : outputRoot(fs::temp_directory_path() / "output") + + Fixture(): + outputRoot(fs::temp_directory_path() / "output") { // We need to set a 0 offset in the timezone. Otherwise, function // DateTime::TimestampToString (a wrapper around ::strftime) will add 1 or 2 hours. We don't @@ -44,6 +66,7 @@ struct Fixture // Clean up our mess to avoid side-effects fs::remove_all(outputRoot); } + fs::path outputRoot; }; @@ -51,63 +74,81 @@ BOOST_AUTO_TEST_SUITE(s) BOOST_FIXTURE_TEST_CASE(economy_legacyfiles_emptylabel, Fixture) { - StudyMode mode = stdmEconomy; + SimulationMode mode = SimulationMode::Economy; ResultFormat fmt = legacyFilesDirectories; const YString label = ""; const int64_t startTime = 1; const YString expectedOutput = (outputRoot / "19700101-0000eco").string(); - const YString actualOutput - = StudyCreateOutputPath(mode, fmt, outputRoot.string(), label, startTime); + const YString actualOutput = StudyCreateOutputPath(mode, + fmt, + outputRoot.string(), + label, + startTime); BOOST_CHECK_EQUAL(actualOutput, expectedOutput); } BOOST_FIXTURE_TEST_CASE(economy_legacyfiles_label_now, Fixture) { - StudyMode mode = stdmEconomy; + SimulationMode mode = SimulationMode::Economy; ResultFormat fmt = legacyFilesDirectories; const YString label = "test"; const int64_t startTime = 1672391667; const YString expectedOutput = (outputRoot / "20221230-0914eco-test").string(); - const YString actualOutput - = StudyCreateOutputPath(mode, fmt, outputRoot.string(), label, startTime); + const YString actualOutput = StudyCreateOutputPath(mode, + fmt, + outputRoot.string(), + label, + startTime); BOOST_CHECK_EQUAL(actualOutput, expectedOutput); } BOOST_FIXTURE_TEST_CASE(adequacy_legacyfiles_label_now, Fixture) { - StudyMode mode = stdmAdequacy; + SimulationMode mode = SimulationMode::Adequacy; ResultFormat fmt = legacyFilesDirectories; const YString label = "test"; const int64_t startTime = 1672391667; const YString expectedOutput = (outputRoot / "20221230-0914adq-test").string(); - const YString actualOutput - = StudyCreateOutputPath(mode, fmt, outputRoot.string(), label, startTime); + const YString actualOutput = StudyCreateOutputPath(mode, + fmt, + outputRoot.string(), + label, + startTime); BOOST_CHECK_EQUAL(actualOutput, expectedOutput); fs::create_directory(outputRoot / "20221230-0914adq-test"); const YString expectedOutput_suffix = (outputRoot / "20221230-0914adq-test-2").string(); - const YString actualOutput_suffix - = StudyCreateOutputPath(mode, fmt, outputRoot.string(), label, startTime); + const YString actualOutput_suffix = StudyCreateOutputPath(mode, + fmt, + outputRoot.string(), + label, + startTime); BOOST_CHECK_EQUAL(actualOutput_suffix, expectedOutput_suffix); } BOOST_FIXTURE_TEST_CASE(adequacy_zip_label_now, Fixture) { - StudyMode mode = stdmAdequacy; + SimulationMode mode = SimulationMode::Adequacy; ResultFormat fmt = zipArchive; const YString label = "test"; const int64_t startTime = 1672391667; const YString expectedOutput = (outputRoot / "20221230-0914adq-test").string(); - const YString actualOutput - = StudyCreateOutputPath(mode, fmt, outputRoot.string(), label, startTime); + const YString actualOutput = StudyCreateOutputPath(mode, + fmt, + outputRoot.string(), + label, + startTime); BOOST_CHECK_EQUAL(actualOutput, expectedOutput); std::ofstream zip_file(outputRoot / "20221230-0914adq-test.zip"); zip_file << "I am a zip file. Well, not really."; const YString expectedOutput_suffix = (outputRoot / "20221230-0914adq-test-2").string(); - const YString actualOutput_suffix - = StudyCreateOutputPath(mode, fmt, outputRoot.string(), label, startTime); + const YString actualOutput_suffix = StudyCreateOutputPath(mode, + fmt, + outputRoot.string(), + label, + startTime); BOOST_CHECK_EQUAL(actualOutput_suffix, expectedOutput_suffix); } diff --git a/src/tests/src/libs/antares/study/parameters/CMakeLists.txt b/src/tests/src/libs/antares/study/parameters/CMakeLists.txt new file mode 100644 index 0000000000..7e22aad5d1 --- /dev/null +++ b/src/tests/src/libs/antares/study/parameters/CMakeLists.txt @@ -0,0 +1,20 @@ +# ==================================== +# Tests on Parameters class +# ==================================== +set(SRC_PARAMETERS_TESTS + parameters-tests.cpp +) +add_executable(parameters-tests ${SRC_PARAMETERS_TESTS}) + +target_link_libraries(parameters-tests + PRIVATE + Boost::unit_test_framework + Antares::study +) + +# Storing parameters-tests under the folder Unit-tests in the IDE +set_target_properties(parameters-tests PROPERTIES FOLDER Unit-tests/parameters-tests) + +add_test(NAME parameters-tests COMMAND parameters-tests) + +set_property(TEST parameters-tests PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/study/parameters/parameters-tests.cpp b/src/tests/src/libs/antares/study/parameters/parameters-tests.cpp new file mode 100644 index 0000000000..5e0da57a10 --- /dev/null +++ b/src/tests/src/libs/antares/study/parameters/parameters-tests.cpp @@ -0,0 +1,221 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE "test parameters" + +#include +#include +#include + +#include + +#include + +using namespace Antares::Data; + +// ================= +// The fixture +// ================= +struct Fixture +{ + Parameters p; + std::filesystem::path path; + StudyLoadOptions options; + StudyVersion version = StudyVersion::latest(); + + Fixture() + { + path = std::filesystem::temp_directory_path() / "generaldata.ini"; + } + + void writeValidFile(); + void writeInvalidFile(); +}; + +// ================== +// Tests section +// ================== + +BOOST_AUTO_TEST_SUITE(parameters_tests) + +BOOST_FIXTURE_TEST_CASE(reset, Fixture) +{ + p.reset(); + BOOST_CHECK_EQUAL(p.simulationDays.first, 0); + BOOST_CHECK_EQUAL(p.nbTimeSeriesThermal, 1); + BOOST_CHECK_EQUAL(p.synthesis, true); + BOOST_CHECK_EQUAL(p.optOptions.ortoolsSolver, "sirius"); +} + +BOOST_FIXTURE_TEST_CASE(loadValid, Fixture) +{ + options.optOptions.ortoolsSolver = "xpress"; + + writeValidFile(); + p.loadFromFile(path.string(), version); + p.validateOptions(options); + p.fixBadValues(); + + BOOST_CHECK_EQUAL(p.nbYears, 5); + BOOST_CHECK_EQUAL(p.seed[seedTsGenThermal], 5489); + BOOST_CHECK_EQUAL(p.include.reserve.dayAhead, true); + BOOST_CHECK_EQUAL(p.optOptions.ortoolsSolver, "xpress"); +} + +BOOST_FIXTURE_TEST_CASE(fixBadValue, Fixture) +{ + p.nbYears = 100; + p.derated = true; + p.nbTimeSeriesThermal = 0; + + p.fixBadValues(); + + BOOST_CHECK_EQUAL(p.nbYears, 1); + BOOST_CHECK_EQUAL(p.nbTimeSeriesThermal, 1); +} + +BOOST_FIXTURE_TEST_CASE(invalidValues, Fixture) +{ + writeInvalidFile(); + BOOST_CHECK(p.loadFromFile(path.string(), version)); + p.validateOptions(options); + p.fixBadValues(); + + BOOST_CHECK_EQUAL(p.nbYears, 1); + BOOST_CHECK_EQUAL(p.useCustomScenario, 0); + BOOST_CHECK_EQUAL(p.firstWeekday, 0); + BOOST_CHECK_EQUAL(p.renewableGeneration(), rgUnknown); +} + +BOOST_AUTO_TEST_SUITE_END() + +void Fixture::writeInvalidFile() +{ + std::ofstream outfile(path); + + outfile << R"([general] + nbyears = abc + custom-scenario = 27 + first.weekday = 21 + + [other preferences] + renewable-generation-modelling = abc)"; + + outfile.close(); +} + +void Fixture::writeValidFile() +{ + std::ofstream outfile(path); + outfile << R"([general] + mode = Economy + horizon = 2000 + nbyears = 5 + simulation.start = 1 + simulation.end = 365 + january.1st = Monday + first-month-in-year = january + first.weekday = Monday + leapyear = false + year-by-year = false + derated = false + custom-scenario = false + user-playlist = false + thematic-trimming = false + geographic-trimming = false + generate = hydro, wind, thermal + nbtimeseriesload = 1 + nbtimeserieshydro = 1 + nbtimeserieswind = 1 + nbtimeseriesthermal = 1 + nbtimeseriessolar = 1 + refreshtimeseries = + intra-modal = + inter-modal = + refreshintervalload = 0 + refreshintervalhydro = 5 + refreshintervalwind = 5 + refreshintervalthermal = 5 + refreshintervalsolar = 0 + readonly = false + + [input] + import = + + [output] + synthesis = false + storenewset = false + archives = + result-format = txt-files + + [optimization] + simplex-range = day + transmission-capacities = local-values + include-constraints = true + include-hurdlecosts = true + include-tc-minstablepower = true + include-tc-min-ud-time = true + include-dayahead = true + include-strategicreserve = true + include-spinningreserve = true + include-primaryreserve = true + include-exportmps = none + include-exportstructure = false + include-unfeasible-problem-behavior = error-verbose + + [adequacy patch] + include-adq-patch = false + set-to-null-ntc-from-physical-out-to-physical-in-for-first-step = true + set-to-null-ntc-between-physical-out-for-first-step = true + enable-first-step = true + price-taking-order = DENS + include-hurdle-cost-csr = false + check-csr-cost-function = false + threshold-initiate-curtailment-sharing-rule = 0.000000 + threshold-display-local-matching-rule-violations = 0.000000 + threshold-csr-variable-bounds-relaxation = 3 + + [other preferences] + hydro-heuristic-policy = accommodate rule curves + hydro-pricing-mode = fast + power-fluctuations = free modulations + shedding-policy = shave peaks + unit-commitment-mode = fast + number-of-cores-mode = medium + renewable-generation-modelling = aggregated + + [advanced parameters] + accuracy-on-correlation = + + [seeds - Mersenne Twister] + seed-tsgen-wind = 5489 + seed-tsgen-load = 5489 + seed-tsgen-hydro = 5489 + seed-tsgen-thermal = 5489 + seed-tsgen-solar = 5489 + seed-tsnumbers = 5489 + seed-unsupplied-energy-costs = 6005489 + seed-spilled-energy-costs = 7005489 + seed-thermal-costs = 8005489 + seed-hydro-costs = 9005489 + seed-initial-reservoir-levels = 10005489)"; + + outfile.close(); +} diff --git a/src/tests/src/libs/antares/study/parts/CMakeLists.txt b/src/tests/src/libs/antares/study/parts/CMakeLists.txt new file mode 100644 index 0000000000..e7ba85aa8e --- /dev/null +++ b/src/tests/src/libs/antares/study/parts/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(hydro) diff --git a/src/tests/src/libs/antares/study/parts/hydro/CMakeLists.txt b/src/tests/src/libs/antares/study/parts/hydro/CMakeLists.txt new file mode 100644 index 0000000000..52937063c8 --- /dev/null +++ b/src/tests/src/libs/antares/study/parts/hydro/CMakeLists.txt @@ -0,0 +1,44 @@ +# Hydro data reader +set(SRC_HYDRO_READER + test-hydroreader-class.cpp) + +add_executable(test-hydro-reader ${SRC_HYDRO_READER}) + +target_link_libraries(test-hydro-reader + PRIVATE + Boost::unit_test_framework + Antares::study + test_utils_unit +) + +# Linux +if(UNIX AND NOT APPLE) + target_link_libraries(test-hydro-reader PRIVATE stdc++fs) +endif() + +set_target_properties(test-hydro-reader PROPERTIES FOLDER Unit-tests/hydro) +add_test(NAME hydro-reader COMMAND test-hydro-reader) +set_property(TEST hydro-reader PROPERTY LABELS unit) + + +# Hydro series +set(SRC_HYDRO_SERIES + test-hydro-series.cpp) + +add_executable(test-hydro-series ${SRC_HYDRO_SERIES}) + +target_link_libraries(test-hydro-series + PRIVATE + Boost::unit_test_framework + Antares::study + test_utils_unit +) + +# Linux +if(UNIX AND NOT APPLE) + target_link_libraries(test-hydro-series PRIVATE stdc++fs) +endif() + +set_target_properties(test-hydro-series PROPERTIES FOLDER Unit-tests/hydro) +add_test(NAME hydro-series COMMAND test-hydro-series) +set_property(TEST hydro-series PROPERTY LABELS unit) \ No newline at end of file diff --git a/src/tests/src/libs/antares/study/parts/hydro/test-hydro-series.cpp b/src/tests/src/libs/antares/study/parts/hydro/test-hydro-series.cpp new file mode 100644 index 0000000000..d534ca7d53 --- /dev/null +++ b/src/tests/src/libs/antares/study/parts/hydro/test-hydro-series.cpp @@ -0,0 +1,250 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test hydro series + +#define WIN32_LEAN_AND_MEAN + +#include + +#include + +#include +#include + +#define SEP "/" + +using namespace Antares::Data; +namespace fs = std::filesystem; + +void fillTimeSeriesWithSpecialEnds(Matrix& timeSeries, double value) +{ + for (uint ts = 0; ts < timeSeries.width; ts++) + { + timeSeries[ts][0] = value + 1; + timeSeries[ts][timeSeries.height - 1] = value + 2; + } +} + +struct Fixture +{ + Fixture() + { + // Create studies + study = std::make_shared(true); + + // Add areas to studies + area_1 = study->areaAdd("Area1"); + study->areas.rebuildIndexes(); + + // Create necessary folders and files for these two areas + createFoldersAndFiles(); + + // Instantiating neccessary studies parameters + study->header.version = Antares::Data::StudyVersion(9, 1); + study->parameters.derated = false; + + // Setting necessary paths + pathToMaxHourlyGenPower_file.clear(); + pathToMaxHourlyGenPower_file = base_folder + SEP + series_folder + SEP + area_1->id.c_str() + + SEP + maxHourlyGenPower_file; + + pathToMaxHourlyPumpPower_file.clear(); + pathToMaxHourlyPumpPower_file = base_folder + SEP + series_folder + SEP + area_1->id.c_str() + + SEP + maxHourlyPumpPower_file; + + pathToSeriesFolder.clear(); + pathToSeriesFolder = base_folder + SEP + series_folder; + } + + void createFoldersAndFiles() + { + // series folder + std::string buffer; + createFolder(base_folder, series_folder); + + // area folder + std::string area1_folder = area_1->id.c_str(); + buffer.clear(); + buffer = base_folder + SEP + series_folder; + createFolder(buffer, area1_folder); + + // maxHourlyGenPower and maxHourlyPumpPower files + buffer.clear(); + buffer = base_folder + SEP + series_folder + SEP + area1_folder; + createFile(buffer, maxHourlyGenPower_file); + createFile(buffer, maxHourlyPumpPower_file); + } + + std::shared_ptr study; + Area* area_1; + std::string base_folder = fs::temp_directory_path().string(); + std::string series_folder = "series"; + std::string maxHourlyGenPower_file = "maxHourlyGenPower.txt"; + std::string maxHourlyPumpPower_file = "maxHourlyPumpPower.txt"; + std::string pathToMaxHourlyGenPower_file; + std::string pathToMaxHourlyPumpPower_file; + std::string pathToSeriesFolder; + + ~Fixture() + { + removeFolder(base_folder, series_folder); + } +}; + +BOOST_AUTO_TEST_SUITE(s) + +BOOST_FIXTURE_TEST_CASE(Testing_load_power_credits_matrices_equal_width, Fixture) +{ + bool ret = true; + + auto& maxHourlyGenPower = area_1->hydro.series->maxHourlyGenPower.timeSeries; + auto& maxHourlyPumpPower = area_1->hydro.series->maxHourlyPumpPower.timeSeries; + maxHourlyGenPower.reset(3, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(3, HOURS_PER_YEAR); + + fillTimeSeriesWithSpecialEnds(maxHourlyGenPower, 400.); + fillTimeSeriesWithSpecialEnds(maxHourlyPumpPower, 200.); + + ret = maxHourlyGenPower.saveToCSVFile(pathToMaxHourlyGenPower_file, 0) && ret; + ret = maxHourlyPumpPower.saveToCSVFile(pathToMaxHourlyPumpPower_file, 0) && ret; + + maxHourlyGenPower.reset(3, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(3, HOURS_PER_YEAR); + + ret = area_1->hydro.series->LoadMaxPower(area_1->id, pathToSeriesFolder) && ret; + BOOST_CHECK(ret); +} + +BOOST_FIXTURE_TEST_CASE(Testing_load_power_credits_both_matrix_equal_width_and_derated, Fixture) +{ + bool ret = true; + study->parameters.derated = true; + StudyVersion studyVersion(9, 1); + bool usedBySolver = true; + + auto& maxHourlyGenPower = area_1->hydro.series->maxHourlyGenPower.timeSeries; + auto& maxHourlyPumpPower = area_1->hydro.series->maxHourlyPumpPower.timeSeries; + maxHourlyGenPower.reset(3, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(3, HOURS_PER_YEAR); + + fillTimeSeriesWithSpecialEnds(maxHourlyGenPower, 400.); + fillTimeSeriesWithSpecialEnds(maxHourlyPumpPower, 200.); + + ret = maxHourlyGenPower.saveToCSVFile(pathToMaxHourlyGenPower_file, 0) && ret; + ret = maxHourlyPumpPower.saveToCSVFile(pathToMaxHourlyPumpPower_file, 0) && ret; + + maxHourlyGenPower.reset(3, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(3, HOURS_PER_YEAR); + + ret = area_1->hydro.series->LoadMaxPower(area_1->id, pathToSeriesFolder) && ret; + BOOST_CHECK(ret); +} + +BOOST_FIXTURE_TEST_CASE(Testing_load_power_credits_matrices_different_width_case_2, Fixture) +{ + bool ret = true; + + auto& maxHourlyGenPower = area_1->hydro.series->maxHourlyGenPower.timeSeries; + auto& maxHourlyPumpPower = area_1->hydro.series->maxHourlyPumpPower.timeSeries; + maxHourlyGenPower.reset(3, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(2, HOURS_PER_YEAR); + + fillTimeSeriesWithSpecialEnds(maxHourlyGenPower, 400.); + fillTimeSeriesWithSpecialEnds(maxHourlyPumpPower, 200.); + + ret = maxHourlyGenPower.saveToCSVFile(pathToMaxHourlyGenPower_file, 0) && ret; + ret = maxHourlyPumpPower.saveToCSVFile(pathToMaxHourlyPumpPower_file, 0) && ret; + + maxHourlyGenPower.reset(3, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(2, HOURS_PER_YEAR); + + ret = area_1->hydro.series->LoadMaxPower(area_1->id, pathToSeriesFolder) && ret; + BOOST_CHECK(ret); +} + +BOOST_FIXTURE_TEST_CASE(Testing_load_power_credits_different_width_case_1, Fixture) +{ + bool ret = true; + + auto& maxHourlyGenPower = area_1->hydro.series->maxHourlyGenPower.timeSeries; + auto& maxHourlyPumpPower = area_1->hydro.series->maxHourlyPumpPower.timeSeries; + maxHourlyGenPower.reset(1, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(3, HOURS_PER_YEAR); + + fillTimeSeriesWithSpecialEnds(maxHourlyGenPower, 400.); + fillTimeSeriesWithSpecialEnds(maxHourlyPumpPower, 200.); + + ret = maxHourlyGenPower.saveToCSVFile(pathToMaxHourlyGenPower_file, 0) && ret; + ret = maxHourlyPumpPower.saveToCSVFile(pathToMaxHourlyPumpPower_file, 0) && ret; + + maxHourlyGenPower.reset(1, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(3, HOURS_PER_YEAR); + + ret = area_1->hydro.series->LoadMaxPower(area_1->id, pathToSeriesFolder) && ret; + BOOST_CHECK(ret); +} + +BOOST_FIXTURE_TEST_CASE(Testing_load_power_credits_different_width_case_2, Fixture) +{ + bool ret = true; + + auto& maxHourlyGenPower = area_1->hydro.series->maxHourlyGenPower.timeSeries; + auto& maxHourlyPumpPower = area_1->hydro.series->maxHourlyPumpPower.timeSeries; + maxHourlyGenPower.reset(4, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(1, HOURS_PER_YEAR); + + fillTimeSeriesWithSpecialEnds(maxHourlyGenPower, 400.); + fillTimeSeriesWithSpecialEnds(maxHourlyPumpPower, 200.); + + ret = maxHourlyGenPower.saveToCSVFile(pathToMaxHourlyGenPower_file, 0) && ret; + ret = maxHourlyPumpPower.saveToCSVFile(pathToMaxHourlyPumpPower_file, 0) && ret; + + maxHourlyGenPower.reset(4, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(1, HOURS_PER_YEAR); + + ret = area_1->hydro.series->LoadMaxPower(area_1->id, pathToSeriesFolder) && ret; + BOOST_CHECK(ret); +} + +BOOST_FIXTURE_TEST_CASE(Testing_load_power_credits_both_zeros, Fixture) +{ + bool ret = true; + + auto& maxHourlyGenPower = area_1->hydro.series->maxHourlyGenPower.timeSeries; + auto& maxHourlyPumpPower = area_1->hydro.series->maxHourlyPumpPower.timeSeries; + maxHourlyGenPower.reset(4, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(1, HOURS_PER_YEAR); + + fillTimeSeriesWithSpecialEnds(maxHourlyGenPower, 400.); + fillTimeSeriesWithSpecialEnds(maxHourlyPumpPower, 200.); + + ret = maxHourlyGenPower.saveToCSVFile(pathToMaxHourlyGenPower_file, 0) && ret; + ret = maxHourlyPumpPower.saveToCSVFile(pathToMaxHourlyPumpPower_file, 0) && ret; + + maxHourlyGenPower.reset(4, HOURS_PER_YEAR); + maxHourlyPumpPower.reset(1, HOURS_PER_YEAR); + + ret = area_1->hydro.series->LoadMaxPower(area_1->id, pathToSeriesFolder) && ret; + BOOST_CHECK(ret); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/parts/hydro/test-hydroreader-class.cpp b/src/tests/src/libs/antares/study/parts/hydro/test-hydroreader-class.cpp new file mode 100644 index 0000000000..cf519c3cb7 --- /dev/null +++ b/src/tests/src/libs/antares/study/parts/hydro/test-hydroreader-class.cpp @@ -0,0 +1,211 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test hydro reader + +#define WIN32_LEAN_AND_MEAN + +#include + +#include + +#include +#include + +#define SEP "/" + +using namespace Antares::Data; +namespace fs = std::filesystem; + +bool equalDailyMaxPowerAsHourlyTs(const Matrix::ColumnType& hourlyColumn, + const Matrix::ColumnType& dailyColumn) +{ + uint hour = 0; + uint day = 0; + + while (hour < HOURS_PER_YEAR && day < DAYS_PER_YEAR) + { + for (uint i = 0; i < HOURS_PER_DAY; ++i) + { + if (hourlyColumn[hour] != dailyColumn[day]) + { + return false; + } + ++hour; + } + ++day; + } + + return true; +} + +bool equalDailyMaxEnergyTs(const Matrix::ColumnType& col1, + const Matrix::ColumnType& col2) +{ + for (uint h = 0; h < DAYS_PER_YEAR; ++h) + { + if (col1[h] != col2[h]) + { + return false; + } + } + + return true; +} + +void fillColumnWithSpecialEnds(Matrix::ColumnType& col, double value, uint heigth) +{ + col[0] = value + 1; + col[heigth - 1] = value + 2; +} + +struct Fixture +{ + Fixture() + { + study = std::make_shared(true); + + // Add areas + area_1 = study->areaAdd("Area1"); + study->areas.rebuildIndexes(); + dailyMaxPumpAndGen.reset(4U, DAYS_PER_YEAR); + reader = std::make_shared(area_1->hydro, + area_1->id.to(), + area_1->name.to()); + + // Create necessary folders and files for these two areas + createFoldersAndFiles(); + + auto& gen = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::genMaxP]; + fillColumnWithSpecialEnds(gen, 300., DAYS_PER_YEAR); + + auto& pump = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::pumpMaxP]; + fillColumnWithSpecialEnds(pump, 200., DAYS_PER_YEAR); + + auto& hoursGen = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::genMaxE]; + fillColumnWithSpecialEnds(hoursGen, 20., DAYS_PER_YEAR); + + auto& hoursPump = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::pumpMaxE]; + fillColumnWithSpecialEnds(hoursPump, 14., DAYS_PER_YEAR); + + std::string buffer; + buffer.clear(); + buffer = base_folder + SEP + hydro_folder + SEP + common_folder + SEP + capacity_folder + + SEP + maxpower + area_1->id.c_str() + ".txt"; + dailyMaxPumpAndGen.saveToCSVFile(buffer, 2); + } + + void createFoldersAndFiles() + { + std::string buffer; + std::string area1_ID = area_1->id.c_str(); + std::string maxpowerArea1 = maxpower + area1_ID + ".txt"; + std::string maxDailyGenEnergy_Area1 = maxDailyGenEnergy_ + area1_ID + ".txt"; + std::string maxDailyPumpEnergy_Area1 = maxDailyPumpEnergy_ + area1_ID + ".txt"; + + buffer.clear(); + + // hydro folder + createFolder(base_folder, hydro_folder); + + // series folder + buffer = base_folder + SEP + hydro_folder; + createFolder(buffer, series_folder); + + // area1 folder + buffer.clear(); + buffer = base_folder + SEP + hydro_folder + SEP + series_folder; + createFolder(buffer, area1_ID); + buffer.clear(); + buffer = base_folder + SEP + hydro_folder + SEP + series_folder + SEP + area1_ID; + + // maxHourlyGenPower and maxHourlyPumpPower files + createFile(buffer, maxHourlyGenPower); + createFile(buffer, maxHourlyPumpPower); + + // common and capacity folders + buffer.clear(); + buffer = base_folder + SEP + hydro_folder; + createFolder(buffer, common_folder); + buffer.clear(); + buffer = base_folder + SEP + hydro_folder + SEP + common_folder; + createFolder(buffer, capacity_folder); + + // max daily energy and power file + buffer.clear(); + buffer = base_folder + SEP + hydro_folder + SEP + common_folder + SEP + capacity_folder; + createFile(buffer, maxpowerArea1); + + // max daily energy files + createFile(buffer, maxDailyGenEnergy_Area1); + createFile(buffer, maxDailyPumpEnergy_Area1); + } + + std::shared_ptr study; + std::shared_ptr reader; + Area* area_1; + std::string base_folder = fs::temp_directory_path().string(); + std::string hydro_folder = "hydro"; + std::string series_folder = "series"; + std::string common_folder = "common"; + std::string capacity_folder = "capacity"; + std::string maxDailyGenEnergy_ = "maxDailyGenEnergy_"; + std::string maxDailyPumpEnergy_ = "maxDailyPumpEnergy_"; + std::string maxpower = "maxpower_"; + std::string maxHourlyGenPower = "maxHourlyGenPower.txt"; + std::string maxHourlyPumpPower = "maxHourlyPumpPower.txt"; + Matrix dailyMaxPumpAndGen; + + ~Fixture() + { + removeFolder(base_folder, hydro_folder); + } +}; + +BOOST_AUTO_TEST_SUITE(s) + +BOOST_FIXTURE_TEST_CASE(Testing_support_for_old_studies, Fixture) +{ + std::string buffer; + bool ret = true; + + auto& genP = area_1->hydro.series->maxHourlyGenPower.timeSeries[0]; + auto& pumpP = area_1->hydro.series->maxHourlyPumpPower.timeSeries[0]; + auto& genE = area_1->hydro.dailyNbHoursAtGenPmax[0]; + auto& pumpE = area_1->hydro.dailyNbHoursAtPumpPmax[0]; + + auto& genPReader = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::genMaxP]; + auto& pumpPReader = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::pumpMaxP]; + auto& genEReader = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::genMaxE]; + auto& pumpEReader = dailyMaxPumpAndGen[HydroMaxTimeSeriesReader::pumpMaxE]; + + buffer.clear(); + buffer = base_folder + SEP + hydro_folder; + ret = reader->read(buffer, study->usedByTheSolver) && ret; + + BOOST_CHECK(ret); + BOOST_CHECK(equalDailyMaxPowerAsHourlyTs(genP, genPReader)); + BOOST_CHECK(equalDailyMaxPowerAsHourlyTs(pumpP, pumpPReader)); + BOOST_CHECK(equalDailyMaxEnergyTs(genE, genEReader)); + BOOST_CHECK(equalDailyMaxEnergyTs(pumpE, pumpEReader)); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/scenario-builder/CMakeLists.txt b/src/tests/src/libs/antares/study/scenario-builder/CMakeLists.txt index 887529be2b..2f65c75b70 100644 --- a/src/tests/src/libs/antares/study/scenario-builder/CMakeLists.txt +++ b/src/tests/src/libs/antares/study/scenario-builder/CMakeLists.txt @@ -11,8 +11,7 @@ add_executable(test-sc-builder-file-read-line ${SRC_SC_BUILDER_READ}) target_include_directories(test-sc-builder-file-read-line PRIVATE - "${src_libs_antares_study}" - "${src_libs_antares_study}/scenario-builder" + "${src_libs_antares_study}/include" ) target_link_libraries(test-sc-builder-file-read-line diff --git a/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-read-line.cpp b/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-read-line.cpp index 798b91ab2f..de09d007d1 100644 --- a/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-read-line.cpp +++ b/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-read-line.cpp @@ -1,167 +1,175 @@ -#define BOOST_TEST_MODULE test read scenario-builder.dat -#define BOOST_TEST_DYN_LINK +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test read scenario - builder.dat #define WIN32_LEAN_AND_MEAN #include -#include -#include +#include +#include using namespace std; using namespace Antares::Data; - // =========================== // Add a cluster to an area // =========================== void addClusterToAreaList(Area* area, std::shared_ptr cluster) { - area->thermal.clusters.push_back(cluster.get()); - area->thermal.list.add(cluster); - area->thermal.list.mapping[cluster->id()] = cluster; + area->thermal.list.addToCompleteList(cluster); } void addClusterToAreaList(Area* area, std::shared_ptr cluster) { - area->renewable.clusters.push_back(cluster.get()); - area->renewable.list.add(cluster); + area->renewable.list.addToCompleteList(cluster); } template std::shared_ptr addClusterToArea(Area* area, const std::string& clusterName) { - auto cluster = std::make_shared(area); - cluster->setName(clusterName); - cluster->series = new DataSeriesCommon(); + auto cluster = std::make_shared(area); + cluster->setName(clusterName); - addClusterToAreaList(area, cluster); + addClusterToAreaList(area, cluster); - return cluster; + return cluster; } - // ================= // The fixture // ================= struct Fixture { - Fixture(const Fixture & f) = delete; - Fixture(const Fixture && f) = delete; - Fixture & operator= (const Fixture & f) = delete; - Fixture& operator= (const Fixture && f) = delete; - Fixture() : my_rule(*study) - { - // Set study parameters - study->parameters.nbYears = 20; - study->parameters.timeSeriesToGenerate = 0; // No generated time-series, only ready made time-series - - // Add areas - area_1 = study->areaAdd("Area 1"); - area_2 = study->areaAdd("Area 2"); - area_3 = study->areaAdd("Area 3"); - study->areas.rebuildIndexes(); - - // Load : set the nb of ready made TS - uint nbReadyMadeTS = 13; - area_1->load.series->timeSeries.resize(nbReadyMadeTS, 1); - area_2->load.series->timeSeries.resize(nbReadyMadeTS, 1); - area_3->load.series->timeSeries.resize(nbReadyMadeTS, 1); - - // Wind : set the nb of ready made TS - nbReadyMadeTS = 17; - area_1->wind.series->timeSeries.resize(nbReadyMadeTS, 1); - area_2->wind.series->timeSeries.resize(nbReadyMadeTS, 1); - area_3->wind.series->timeSeries.resize(nbReadyMadeTS, 1); - - // Solar : set the nb of ready made TS - nbReadyMadeTS = 9; - area_1->solar.series->timeSeries.resize(nbReadyMadeTS, 1); - area_2->solar.series->timeSeries.resize(nbReadyMadeTS, 1); - area_3->solar.series->timeSeries.resize(nbReadyMadeTS, 1); - - // Hydro : set the nb of ready made TS - nbReadyMadeTS = 12; - area_1->hydro.series->count = nbReadyMadeTS; - area_2->hydro.series->count = nbReadyMadeTS; - area_3->hydro.series->count = nbReadyMadeTS; - - // Links - link_12 = AreaAddLinkBetweenAreas(area_1, area_2, false); - link_12->directCapacities.resize(15, 1); - - link_13 = AreaAddLinkBetweenAreas(area_1, area_3, false); - link_13->directCapacities.resize(11, 1); - - link_23 = AreaAddLinkBetweenAreas(area_2, area_3, false); - link_23->directCapacities.resize(8, 1); - - // Add thermal clusters - thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); - thCluster_12 = addClusterToArea(area_1, "th-cluster-12"); - thCluster_31 = addClusterToArea(area_3, "th-cluster-31"); - - // Thermal clusters : set the nb of ready made TS - thCluster_11->series->timeSeries.resize(14, 1); - thCluster_12->series->timeSeries.resize(14, 1); - thCluster_31->series->timeSeries.resize(14, 1); - - // Thermal clusters : update areas local numbering for clusters - area_1->thermal.prepareAreaWideIndexes(); - area_2->thermal.prepareAreaWideIndexes(); - area_3->thermal.prepareAreaWideIndexes(); - - // Add renewable clusters - rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); - rnCluster_31 = addClusterToArea(area_3, "rn-cluster-31"); - rnCluster_32 = addClusterToArea(area_3, "rn-cluster-32"); - - // Renewable clusters : set the nb of ready made TS - rnCluster_21->series->timeSeries.resize(9, 1); - rnCluster_31->series->timeSeries.resize(9, 1); - rnCluster_32->series->timeSeries.resize(9, 1); - - // Renewable clusters : update areas local numbering for clusters - area_1->renewable.prepareAreaWideIndexes(); - area_2->renewable.prepareAreaWideIndexes(); - area_3->renewable.prepareAreaWideIndexes(); - - // Resize all TS numbers storage (1 column x nbYears lines) - area_1->resizeAllTimeseriesNumbers(study->parameters.nbYears); - area_2->resizeAllTimeseriesNumbers(study->parameters.nbYears); - area_3->resizeAllTimeseriesNumbers(study->parameters.nbYears); + Fixture(const Fixture& f) = delete; + Fixture(const Fixture&& f) = delete; + Fixture& operator=(const Fixture& f) = delete; + Fixture& operator=(const Fixture&& f) = delete; + + Fixture(): + my_rule(*study) + { + // Set study parameters + study->parameters.nbYears = 20; + study->parameters.timeSeriesToGenerate = 0; // No generated time-series, only ready made + // time-series + + // Add areas + area_1 = study->areaAdd("Area 1"); + area_2 = study->areaAdd("Area 2"); + area_3 = study->areaAdd("Area 3"); + study->areas.rebuildIndexes(); + + // Load : set the nb of ready made TS + uint nbReadyMadeTS = 13; + area_1->load.series.timeSeries.resize(nbReadyMadeTS, 1); + area_2->load.series.timeSeries.resize(nbReadyMadeTS, 1); + area_3->load.series.timeSeries.resize(nbReadyMadeTS, 1); + + // Wind : set the nb of ready made TS + nbReadyMadeTS = 17; + area_1->wind.series.timeSeries.resize(nbReadyMadeTS, 1); + area_2->wind.series.timeSeries.resize(nbReadyMadeTS, 1); + area_3->wind.series.timeSeries.resize(nbReadyMadeTS, 1); + + // Links + link_12 = AreaAddLinkBetweenAreas(area_1, area_2, false); + link_12->directCapacities.resize(15, 1); + // Solar : set the nb of ready made TS + nbReadyMadeTS = 9; + area_1->solar.series.timeSeries.resize(nbReadyMadeTS, 1); + area_2->solar.series.timeSeries.resize(nbReadyMadeTS, 1); + area_3->solar.series.timeSeries.resize(nbReadyMadeTS, 1); + + // Hydro : set the nb of ready made TS + nbReadyMadeTS = 12; + area_1->hydro.series->resizeTS(nbReadyMadeTS); + area_2->hydro.series->resizeTS(nbReadyMadeTS); + area_3->hydro.series->resizeTS(nbReadyMadeTS); + + // Links + link_12 = AreaAddLinkBetweenAreas(area_1, area_2, false); + link_12->directCapacities.resize(15, 1); + + link_13 = AreaAddLinkBetweenAreas(area_1, area_3, false); + link_13->directCapacities.resize(11, 1); + + link_23 = AreaAddLinkBetweenAreas(area_2, area_3, false); + link_23->directCapacities.resize(8, 1); + + // Add thermal clusters + thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); + thCluster_12 = addClusterToArea(area_1, "th-cluster-12"); + thCluster_31 = addClusterToArea(area_3, "th-cluster-31"); + + // Thermal clusters : set the nb of ready made TS + thCluster_11->series.timeSeries.resize(14, 1); + thCluster_12->series.timeSeries.resize(14, 1); + thCluster_31->series.timeSeries.resize(14, 1); + + // Add renewable clusters + rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); + rnCluster_31 = addClusterToArea(area_3, "rn-cluster-31"); + rnCluster_32 = addClusterToArea(area_3, "rn-cluster-32"); + + // Renewable clusters : set the nb of ready made TS + rnCluster_21->series.timeSeries.resize(9, 1); + rnCluster_31->series.timeSeries.resize(9, 1); + rnCluster_32->series.timeSeries.resize(9, 1); + + // Resize all TS numbers storage (1 column x nbYears lines) + area_1->resizeAllTimeseriesNumbers(study->parameters.nbYears); + area_2->resizeAllTimeseriesNumbers(study->parameters.nbYears); + area_3->resizeAllTimeseriesNumbers(study->parameters.nbYears); auto bc = study->bindingConstraints.add("BC_1"); bc->group("groupTest"); auto group = study->bindingConstraintsGroups.add("groupTest"); - group->add(bc); + group->add(bc); study->bindingConstraintsGroups.resizeAllTimeseriesNumbers(study->parameters.nbYears); bc->RHSTimeSeries().resize(7, 1); - BOOST_CHECK(my_rule.reset()); - } + BOOST_CHECK(my_rule.reset()); + } - ~Fixture() = default; + ~Fixture() = default; Study::Ptr study = std::make_shared(); - Area* area_1; - Area* area_2; - Area* area_3; - AreaLink* link_12; - AreaLink* link_13; - AreaLink* link_23; - std::shared_ptr thCluster_11; - std::shared_ptr thCluster_12; - std::shared_ptr thCluster_31; - std::shared_ptr rnCluster_21; - std::shared_ptr rnCluster_31; - std::shared_ptr rnCluster_32; - - ScenarioBuilder::Rules my_rule; + Area* area_1; + Area* area_2; + Area* area_3; + AreaLink* link_12; + AreaLink* link_13; + AreaLink* link_23; + std::shared_ptr thCluster_11; + std::shared_ptr thCluster_12; + std::shared_ptr thCluster_31; + std::shared_ptr rnCluster_21; + std::shared_ptr rnCluster_31; + std::shared_ptr rnCluster_32; + + ScenarioBuilder::Rules my_rule; }; - // ================== // Tests section // ================== @@ -173,15 +181,17 @@ BOOST_AUTO_TEST_SUITE(s) // ================= BOOST_FIXTURE_TEST_CASE(on_area2_and_on_year_18__load_TS_number_11_is_chosen__reading_OK, Fixture) { - AreaName yearNumber = "18"; - String tsNumber = "11"; - AreaName::Vector splitKey = { "l", "area 2", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "18"; + String tsNumber = "11"; + AreaName::Vector splitKey = {"l", "area 2", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.load.get_value(yearNumber.to(), area_2->index), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.load.get_value(yearNumber.to(), area_2->index), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(area_2->load.series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(area_2->load.series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } // ================= @@ -189,15 +199,17 @@ BOOST_FIXTURE_TEST_CASE(on_area2_and_on_year_18__load_TS_number_11_is_chosen__re // ================= BOOST_FIXTURE_TEST_CASE(on_area3_and_on_year_7__wind_TS_number_5_is_chosen__reading_OK, Fixture) { - AreaName yearNumber = "7"; - String tsNumber = "5"; - AreaName::Vector splitKey = { "w", "area 3", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "7"; + String tsNumber = "5"; + AreaName::Vector splitKey = {"w", "area 3", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.wind.get_value(yearNumber.to(), area_3->index), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.wind.get_value(yearNumber.to(), area_3->index), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(area_3->wind.series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(area_3->wind.series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } // ================= @@ -205,15 +217,17 @@ BOOST_FIXTURE_TEST_CASE(on_area3_and_on_year_7__wind_TS_number_5_is_chosen__read // ================= BOOST_FIXTURE_TEST_CASE(on_area1_and_on_year_4__solar_TS_number_8_is_chosen__reading_OK, Fixture) { - AreaName yearNumber = "4"; - String tsNumber = "8"; - AreaName::Vector splitKey = { "s", "area 1", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "4"; + String tsNumber = "8"; + AreaName::Vector splitKey = {"s", "area 1", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.solar.get_value(yearNumber.to(), area_1->index), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.solar.get_value(yearNumber.to(), area_1->index), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(area_1->solar.series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(area_1->solar.series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } // ================= @@ -221,194 +235,299 @@ BOOST_FIXTURE_TEST_CASE(on_area1_and_on_year_4__solar_TS_number_8_is_chosen__rea // ================= BOOST_FIXTURE_TEST_CASE(on_area2_and_on_year_15__solar_TS_number_3_is_chosen__reading_OK, Fixture) { - AreaName yearNumber = "15"; - String tsNumber = "3"; - AreaName::Vector splitKey = { "h", "area 2", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "15"; + String tsNumber = "3"; + AreaName::Vector splitKey = {"h", "area 2", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.hydro.get_value(yearNumber.to(), area_2->index), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.hydro.get_value(yearNumber.to(), area_2->index), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(area_2->hydro.series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(area_2->hydro.series->timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } - // =========================== // Tests on Thermal clusters // =========================== -BOOST_FIXTURE_TEST_CASE(on_th_cluster11_of_area1_and_on_year_6__solar_TS_number_3_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE( + on_th_cluster11_of_area1_and_on_year_6__solar_TS_number_3_is_chosen__reading_OK, + Fixture) { - AreaName yearNumber = "6"; - String tsNumber = "3"; - AreaName::Vector splitKey = { "t", "area 1", yearNumber, "th-cluster-11" }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "6"; + String tsNumber = "3"; + AreaName::Vector splitKey = {"t", "area 1", yearNumber, "th-cluster-11"}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.thermal[area_1->index].get(thCluster_11.get(), yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.thermal[area_1->index].get(thCluster_11.get(), yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(thCluster_11->series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(thCluster_11->series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } -BOOST_FIXTURE_TEST_CASE(on_th_cluster12_of_area1_and_on_year_13__solar_TS_number_5_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE( + on_th_cluster12_of_area1_and_on_year_13__solar_TS_number_5_is_chosen__reading_OK, + Fixture) { - AreaName yearNumber = "13"; - String tsNumber = "5"; - AreaName::Vector splitKey = { "t", "area 1", yearNumber, "th-cluster-12" }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "13"; + String tsNumber = "5"; + AreaName::Vector splitKey = {"t", "area 1", yearNumber, "th-cluster-12"}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.thermal[area_1->index].get(thCluster_12.get(), yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.thermal[area_1->index].get(thCluster_12.get(), yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(thCluster_12->series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(thCluster_12->series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } -BOOST_FIXTURE_TEST_CASE(on_th_cluster31_of_area3_and_on_year_10__solar_TS_number_7_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE( + on_th_cluster31_of_area3_and_on_year_10__solar_TS_number_7_is_chosen__reading_OK, + Fixture) { - AreaName yearNumber = "10"; - String tsNumber = "7"; - AreaName::Vector splitKey = { "t", "area 3", yearNumber, "th-cluster-31" }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "10"; + String tsNumber = "7"; + AreaName::Vector splitKey = {"t", "area 3", yearNumber, "th-cluster-31"}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.thermal[area_3->index].get(thCluster_31.get(), yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.thermal[area_3->index].get(thCluster_31.get(), yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(thCluster_31->series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(thCluster_31->series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } - // ============================= // Tests on Renewable clusters // ============================= -BOOST_FIXTURE_TEST_CASE(on_rn_cluster21_of_area2_and_on_year_16__solar_TS_number_8_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE( + on_rn_cluster21_of_area2_and_on_year_16__solar_TS_number_8_is_chosen__reading_OK, + Fixture) { - study->parameters.renewableGeneration.toClusters(); + study->parameters.renewableGeneration.toClusters(); - AreaName yearNumber = "16"; - String tsNumber = "8"; - AreaName::Vector splitKey = { "r", "area 2", yearNumber, "rn-cluster-21" }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "16"; + String tsNumber = "8"; + AreaName::Vector splitKey = {"r", "area 2", yearNumber, "rn-cluster-21"}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.renewable[area_2->index].get(rnCluster_21.get(), yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.renewable[area_2->index].get(rnCluster_21.get(), + yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(rnCluster_21->series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(rnCluster_21->series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } -BOOST_FIXTURE_TEST_CASE(on_rn_cluster32_of_area3_and_on_year_2__solar_TS_number_4_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE( + on_rn_cluster32_of_area3_and_on_year_2__solar_TS_number_4_is_chosen__reading_OK, + Fixture) { - study->parameters.renewableGeneration.toClusters(); + study->parameters.renewableGeneration.toClusters(); - AreaName yearNumber = "2"; - String tsNumber = "4"; - AreaName::Vector splitKey = { "r", "area 3", yearNumber, "rn-cluster-32" }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "2"; + String tsNumber = "4"; + AreaName::Vector splitKey = {"r", "area 3", yearNumber, "rn-cluster-32"}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.renewable[area_3->index].get(rnCluster_32.get(), yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.renewable[area_3->index].get(rnCluster_32.get(), + yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(rnCluster_32->series->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(rnCluster_32->series.timeseriesNumbers[yearNumber.to()], + tsNumber.to() - 1); } - // ======================== -// Tests on Hydro levels +// Tests on Hydro initial levels // ======================== BOOST_FIXTURE_TEST_CASE(on_area1_and_on_year_17__hydro_level_0_123_is_chosen__reading_OK, Fixture) { - AreaName yearNumber = "17"; - String level = "0.123"; - AreaName::Vector splitKey = { "hl", "area 1", yearNumber }; - my_rule.readLine(splitKey, level); + AreaName yearNumber = "17"; + String level = "0.123"; + AreaName::Vector splitKey = {"hl", "area 1", yearNumber}; + my_rule.readLine(splitKey, level); + + BOOST_CHECK_EQUAL(my_rule.hydroInitialLevels.get_value(yearNumber.to(), area_1->index), + level.to()); + + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_1->index][yearNumber.to()], + level.to()); +} + +BOOST_FIXTURE_TEST_CASE( + on_area2_and_on_year_9__hydro_level_1_5_is_chosen_level_lowered_to_1__reading_OK, + Fixture) +{ + AreaName yearNumber = "9"; + String level = "1.5"; + AreaName::Vector splitKey = {"hl", "area 2", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, level)); + + BOOST_CHECK_EQUAL(my_rule.hydroInitialLevels.get_value(yearNumber.to(), area_2->index), + 1.); + + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_2->index][yearNumber.to()], 1.); +} + +BOOST_FIXTURE_TEST_CASE( + on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__level_raised_to_0__reading_OK, + Fixture) +{ + AreaName yearNumber = "5"; + String level = "-3.5"; + AreaName::Vector splitKey = {"hl", "area 3", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, level)); - BOOST_CHECK_EQUAL(my_rule.hydroLevels.get_value(yearNumber.to(), area_1->index), level.to()); + BOOST_CHECK_EQUAL(my_rule.hydroInitialLevels.get_value(yearNumber.to(), area_3->index), + 0.); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(study->scenarioHydroLevels[area_1->index][yearNumber.to()], level.to()); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_3->index][yearNumber.to()], 0.); } -BOOST_FIXTURE_TEST_CASE(on_area2_and_on_year_9__hydro_level_1_5_is_chosen_level_lowered_to_1__reading_OK, Fixture) +// ======================== +// Tests on Hydro final levels +// ======================== +BOOST_FIXTURE_TEST_CASE(on_area1_and_on_year_8__hydro_level_0_342_is_chosen__reading_OK, Fixture) { - AreaName yearNumber = "9"; - String level = "1.5"; - AreaName::Vector splitKey = { "hl", "area 2", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, level)); + AreaName yearNumber = "8"; + String level = "0.342"; + AreaName::Vector splitKey = {"hfl", "area 1", yearNumber}; + my_rule.readLine(splitKey, level, false); - BOOST_CHECK_EQUAL(my_rule.hydroLevels.get_value(yearNumber.to(), area_2->index), 1.); + BOOST_CHECK_EQUAL(my_rule.hydroFinalLevels.get_value(yearNumber.to(), area_1->index), + level.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(study->scenarioHydroLevels[area_2->index][yearNumber.to()], 1.); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioFinalHydroLevels[area_1->index][yearNumber.to()], + level.to()); } -BOOST_FIXTURE_TEST_CASE(on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__level_raised_to_0__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE( + on_area2_and_on_year_1__hydro_level_2_4_is_chosen_level_lowered_to_1__reading_OK, + Fixture) { - AreaName yearNumber = "5"; - String level = "-3.5"; - AreaName::Vector splitKey = { "hl", "area 3", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, level)); + AreaName yearNumber = "1"; + String level = "2.4"; + AreaName::Vector splitKey = {"hfl", "area 2", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, level, false)); - BOOST_CHECK_EQUAL(my_rule.hydroLevels.get_value(yearNumber.to(), area_3->index), 0.); + BOOST_CHECK_EQUAL(my_rule.hydroFinalLevels.get_value(yearNumber.to(), area_2->index), 1.); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(study->scenarioHydroLevels[area_3->index][yearNumber.to()], 0.); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioFinalHydroLevels[area_2->index][yearNumber.to()], 1.); +} + +BOOST_FIXTURE_TEST_CASE( + on_area3_and_on_year_3__hydro_level_neg_5_2_is_chosen__level_raised_to_0__reading_OK, + Fixture) +{ + AreaName yearNumber = "3"; + String level = "-5.2"; + AreaName::Vector splitKey = {"hfl", "area 3", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, level, false)); + + BOOST_CHECK_EQUAL(my_rule.hydroFinalLevels.get_value(yearNumber.to(), area_3->index), 0.); + + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioFinalHydroLevels[area_3->index][yearNumber.to()], 0.); } // ====================== // Tests on Links NTC // ====================== -BOOST_FIXTURE_TEST_CASE(on_link_area1_area2_and_on_year_0__ntc_TS_number_10_is_chosen__reading_OK, Fixture) -{ - AreaName yearNumber = "0"; - String tsNumber = "10"; - AreaName::Vector splitKey = {"ntc", "area 1", "area 2", yearNumber}; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - - BOOST_CHECK_EQUAL(my_rule.linksNTC[area_1->index].get(link_12, yearNumber.to()), tsNumber.to()); - - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(link_12->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); +BOOST_FIXTURE_TEST_CASE(on_link_area1_area2_and_on_year_0__ntc_TS_number_10_is_chosen__reading_OK, + Fixture) +{ + AreaName yearNumber = "0"; + String tsNumber = "10"; + AreaName::Vector splitKey = {"ntc", "area 1", "area 2", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + + BOOST_CHECK_EQUAL(my_rule.linksNTC[area_1->index].get(link_12, yearNumber.to()), + tsNumber.to()); + + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(link_12->timeseriesNumbers[yearNumber.to()], tsNumber.to() - 1); } -BOOST_FIXTURE_TEST_CASE(on_link_area1_area3_and_on_year_15__ntc_TS_number_7_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE(on_link_area1_area3_and_on_year_15__ntc_TS_number_7_is_chosen__reading_OK, + Fixture) { - AreaName yearNumber = "15"; - String tsNumber = "7"; - AreaName::Vector splitKey = { "ntc", "area 1", "area 3", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "15"; + String tsNumber = "7"; + AreaName::Vector splitKey = {"ntc", "area 1", "area 3", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.linksNTC[area_1->index].get(link_13, yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.linksNTC[area_1->index].get(link_13, yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(link_13->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(link_13->timeseriesNumbers[yearNumber.to()], tsNumber.to() - 1); } -BOOST_FIXTURE_TEST_CASE(on_link_area2_area3_and_on_year_19__ntc_TS_number_6_is_chosen__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE(on_link_area2_area3_and_on_year_19__ntc_TS_number_6_is_chosen__reading_OK, + Fixture) { - AreaName yearNumber = "19"; - String tsNumber = "6"; - AreaName::Vector splitKey = { "ntc", "area 2", "area 3", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); + AreaName yearNumber = "19"; + String tsNumber = "6"; + AreaName::Vector splitKey = {"ntc", "area 2", "area 3", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber)); - BOOST_CHECK_EQUAL(my_rule.linksNTC[area_2->index].get(link_23, yearNumber.to()), tsNumber.to()); + BOOST_CHECK_EQUAL(my_rule.linksNTC[area_2->index].get(link_23, yearNumber.to()), + tsNumber.to()); - BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(link_23->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(link_23->timeseriesNumbers[yearNumber.to()], tsNumber.to() - 1); } // ======================== // Tests on Binding Constraints // ======================== -BOOST_FIXTURE_TEST_CASE(binding_constraints_group_groupTest__Load_TS_4_for_year_3__reading_OK, Fixture) +BOOST_FIXTURE_TEST_CASE(binding_constraints_group_groupTest__Load_TS_4_for_year_3__reading_OK, + Fixture) { auto yearNumber = 3; - auto tsNumber = 4; + uint32_t tsNumber = 4; - AreaName::Vector splitKey = { "bc", "groupTest", std::to_string(yearNumber) }; + AreaName::Vector splitKey = {"bc", "groupTest", std::to_string(yearNumber)}; BOOST_CHECK(my_rule.readLine(splitKey, std::to_string(tsNumber))); BOOST_CHECK_EQUAL(my_rule.binding_constraints.get("groupTest", yearNumber), tsNumber); BOOST_CHECK(my_rule.apply()); - auto actual = study->bindingConstraintsGroups["groupTest"]->timeseriesNumbers[0][yearNumber]; - BOOST_CHECK_EQUAL(actual, tsNumber-1); + auto actual = study->bindingConstraintsGroups["groupTest"]->timeseriesNumbers[yearNumber]; + BOOST_CHECK_EQUAL(actual, tsNumber - 1); +} + +// ======================== +// Tests on TSNumberData +// ======================== +BOOST_FIXTURE_TEST_CASE(thermalTSNumberData, Fixture) +{ + ScenarioBuilder::thermalTSNumberData tsdata; + tsdata.attachArea(area_1); + tsdata.reset(*study); + tsdata.setTSnumber(thCluster_12.get(), 2, 22); + tsdata.setTSnumber(thCluster_12.get(), 5, 32); // out of bounds + + study->parameters.nbTimeSeriesThermal = 1; + thCluster_12->tsGenBehavior = LocalTSGenerationBehavior::forceNoGen; + thCluster_12->series.timeSeries.resize(30, 8760); + + tsdata.apply(*study); + + BOOST_CHECK_EQUAL(thCluster_12->series.timeseriesNumbers[2], 21); + BOOST_CHECK_EQUAL(thCluster_12->series.timeseriesNumbers[5], 0); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-save.cpp b/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-save.cpp index 592ece1694..64813637fc 100644 --- a/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-save.cpp +++ b/src/tests/src/libs/antares/study/scenario-builder/test-sc-builder-file-save.cpp @@ -1,14 +1,34 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE test save scenario - builder.dat -#define BOOST_TEST_DYN_LINK -#include - -#include #include #include +#include + +#include + +#include +#include +#include -#include -#include -#include #include "area/files-helper.h" using namespace std; @@ -26,10 +46,12 @@ class referenceScBuilderFile public: referenceScBuilderFile() = default; ~referenceScBuilderFile() = default; + string path() const { return absolute_path_; } + void write(); void append(const string line); @@ -49,7 +71,9 @@ void referenceScBuilderFile::write() ofstream file; file.open(absolute_path_); for (uint i = 0; i < content_.size(); ++i) + { file << content_[i] << endl; + } file << endl; } @@ -59,15 +83,12 @@ void referenceScBuilderFile::write() void addClusterToAreaList(Area* area, std::shared_ptr cluster) { - area->thermal.clusters.push_back(cluster.get()); - area->thermal.list.add(cluster); - area->thermal.list.mapping[cluster->id()] = cluster; + area->thermal.list.addToCompleteList(cluster); } void addClusterToAreaList(Area* area, std::shared_ptr cluster) { - area->renewable.clusters.push_back(cluster.get()); - area->renewable.list.add(cluster); + area->renewable.list.addToCompleteList(cluster); } template @@ -75,7 +96,6 @@ std::shared_ptr addClusterToArea(Area* area, const std::string& clu { auto cluster = std::make_shared(area); cluster->setName(clusterName); - cluster->series = new DataSeriesCommon(); addClusterToAreaList(area, cluster); @@ -91,13 +111,14 @@ struct commonFixture commonFixture(const commonFixture&& f) = delete; commonFixture& operator=(const commonFixture& f) = delete; commonFixture& operator=(const commonFixture&& f) = delete; + commonFixture() { study = std::make_shared(); // Set study parameters study->parameters.nbYears = 20; - study->parameters.timeSeriesToGenerate - = 0; // No generated time-series, only ready made time-series + study->parameters.timeSeriesToGenerate = 0; // No generated time-series, only ready made + // time-series // Add areas area_1 = study->areaAdd("Area 1"); @@ -107,27 +128,21 @@ struct commonFixture // Load : set the nb of ready made TS uint nbReadyMadeTS = 13; - area_1->load.series->timeSeries.resize(nbReadyMadeTS, 1); - area_2->load.series->timeSeries.resize(nbReadyMadeTS, 1); - area_3->load.series->timeSeries.resize(nbReadyMadeTS, 1); + area_1->load.series.timeSeries.resize(nbReadyMadeTS, 1); + area_2->load.series.timeSeries.resize(nbReadyMadeTS, 1); + area_3->load.series.timeSeries.resize(nbReadyMadeTS, 1); // Wind : set the nb of ready made TS nbReadyMadeTS = 17; - area_1->wind.series->timeSeries.resize(nbReadyMadeTS, 1); - area_2->wind.series->timeSeries.resize(nbReadyMadeTS, 1); - area_3->wind.series->timeSeries.resize(nbReadyMadeTS, 1); + area_1->wind.series.timeSeries.resize(nbReadyMadeTS, 1); + area_2->wind.series.timeSeries.resize(nbReadyMadeTS, 1); + area_3->wind.series.timeSeries.resize(nbReadyMadeTS, 1); // Solar : set the nb of ready made TS nbReadyMadeTS = 9; - area_1->solar.series->timeSeries.resize(nbReadyMadeTS, 1); - area_2->solar.series->timeSeries.resize(nbReadyMadeTS, 1); - area_3->solar.series->timeSeries.resize(nbReadyMadeTS, 1); - - // Hydro : set the nb of ready made TS - nbReadyMadeTS = 12; - area_1->hydro.series->count = nbReadyMadeTS; - area_2->hydro.series->count = nbReadyMadeTS; - area_3->hydro.series->count = nbReadyMadeTS; + area_1->solar.series.timeSeries.resize(nbReadyMadeTS, 1); + area_2->solar.series.timeSeries.resize(nbReadyMadeTS, 1); + area_3->solar.series.timeSeries.resize(nbReadyMadeTS, 1); // Links link_12 = AreaAddLinkBetweenAreas(area_1, area_2, false); @@ -145,14 +160,9 @@ struct commonFixture thCluster_31 = addClusterToArea(area_3, "th-cluster-31"); // Thermal clusters : set the nb of ready made TS - thCluster_11->series->timeSeries.resize(14, 1); - thCluster_12->series->timeSeries.resize(14, 1); - thCluster_31->series->timeSeries.resize(14, 1); - - // Thermal clusters : update areas local numbering for clusters - area_1->thermal.prepareAreaWideIndexes(); - area_2->thermal.prepareAreaWideIndexes(); - area_3->thermal.prepareAreaWideIndexes(); + thCluster_11->series.timeSeries.resize(14, 1); + thCluster_12->series.timeSeries.resize(14, 1); + thCluster_31->series.timeSeries.resize(14, 1); // Add renewable clusters rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); @@ -160,14 +170,9 @@ struct commonFixture rnCluster_32 = addClusterToArea(area_3, "rn-cluster-32"); // Renewable clusters : set the nb of ready made TS - rnCluster_21->series->timeSeries.resize(9, 1); - rnCluster_31->series->timeSeries.resize(9, 1); - rnCluster_32->series->timeSeries.resize(9, 1); - - // Renewable clusters : update areas local numbering for clusters - area_1->renewable.prepareAreaWideIndexes(); - area_2->renewable.prepareAreaWideIndexes(); - area_3->renewable.prepareAreaWideIndexes(); + rnCluster_21->series.timeSeries.resize(9, 1); + rnCluster_31->series.timeSeries.resize(9, 1); + rnCluster_32->series.timeSeries.resize(9, 1); // Resize all TS numbers storage (1 column x nbYears lines) area_1->resizeAllTimeseriesNumbers(study->parameters.nbYears); @@ -182,7 +187,6 @@ struct commonFixture study->bindingConstraintsGroups.add("group2"); study->bindingConstraintsGroups.add("group3"); - // Scenario builder initialization study->scenarioRules = new ScenarioBuilder::Sets(); study->scenarioRules->setStudy(*study); @@ -214,17 +218,20 @@ struct commonFixture // Scenario builder save fixture // ====================================== -struct saveFixture : public commonFixture +struct saveFixture: public commonFixture { - saveFixture() : commonFixture() + saveFixture(): + commonFixture() { } + ~saveFixture(); void saveScenarioBuilder(); // Data members - std::string path_to_generated_file - = fs::current_path().append(generatedScBuilderFileName).string(); + std::string path_to_generated_file = fs::current_path() + .append(generatedScBuilderFileName) + .string(); referenceScBuilderFile referenceFile; }; @@ -249,7 +256,8 @@ BOOST_AUTO_TEST_SUITE(s) // Tests on Load // ==================== BOOST_FIXTURE_TEST_CASE( - LOAD__on_area2_and_year_11_chosen_ts_number_is_6__generated_and_ref_sc_buider_files_are_identical, saveFixture) + LOAD__on_area2_and_year_11_chosen_ts_number_is_6__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->load.setTSnumber(area_2->index, 11, 6); @@ -264,7 +272,8 @@ BOOST_FIXTURE_TEST_CASE( } BOOST_FIXTURE_TEST_CASE( - LOAD__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + LOAD__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->load.setTSnumber(area_3->index, 7, 2); my_rule->load.setTSnumber(area_2->index, 11, 6); @@ -292,7 +301,8 @@ BOOST_FIXTURE_TEST_CASE( // Tests on Wind // ==================== BOOST_FIXTURE_TEST_CASE( - WIND__on_area3_and_year_19_chosen_ts_number_is_17__generated_and_ref_sc_buider_files_are_identical, saveFixture) + WIND__on_area3_and_year_19_chosen_ts_number_is_17__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->wind.setTSnumber(area_3->index, 19, 17); @@ -310,7 +320,8 @@ BOOST_FIXTURE_TEST_CASE( // Tests on Solar // ==================== BOOST_FIXTURE_TEST_CASE( - SOLAR__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + SOLAR__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->solar.setTSnumber(area_1->index, 9, 9); my_rule->solar.setTSnumber(area_3->index, 18, 7); @@ -332,7 +343,8 @@ BOOST_FIXTURE_TEST_CASE( // Tests on Hydro // ================= BOOST_FIXTURE_TEST_CASE( - HYDRO__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + HYDRO__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->hydro.setTSnumber(area_2->index, 17, 12); my_rule->hydro.setTSnumber(area_3->index, 18, 7); @@ -354,7 +366,8 @@ BOOST_FIXTURE_TEST_CASE( // Tests on Thermal clusters // =========================== BOOST_FIXTURE_TEST_CASE( - THERMAL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + THERMAL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->thermal[area_3->index].setTSnumber(thCluster_31.get(), 5, 13); my_rule->thermal[area_1->index].setTSnumber(thCluster_11.get(), 19, 8); @@ -377,7 +390,8 @@ BOOST_FIXTURE_TEST_CASE( // Tests on Renewable clusters // ============================= BOOST_FIXTURE_TEST_CASE( - RENEWABLE_CLUSTERS__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + RENEWABLE_CLUSTERS__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->renewable[area_3->index].setTSnumber(rnCluster_32.get(), 5, 13); my_rule->renewable[area_2->index].setTSnumber(rnCluster_21.get(), 19, 8); @@ -397,14 +411,15 @@ BOOST_FIXTURE_TEST_CASE( } // ======================== -// Tests on Hydro levels +// Tests on Hydro initial levels // ======================== BOOST_FIXTURE_TEST_CASE( - HYDRO_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + HYDRO_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { - my_rule->hydroLevels.setTSnumber(area_1->index, 9, 9); - my_rule->hydroLevels.setTSnumber(area_3->index, 18, 7); - my_rule->hydroLevels.setTSnumber(area_1->index, 5, 8); + my_rule->hydroInitialLevels.setTSnumber(area_1->index, 9, 9); + my_rule->hydroInitialLevels.setTSnumber(area_3->index, 18, 7); + my_rule->hydroInitialLevels.setTSnumber(area_1->index, 5, 8); saveScenarioBuilder(); @@ -418,11 +433,35 @@ BOOST_FIXTURE_TEST_CASE( BOOST_CHECK(files_identical(path_to_generated_file, referenceFile.path())); } +// ======================== +// Tests on Hydro final levels +// ======================== +BOOST_FIXTURE_TEST_CASE( + HYDRO_FINAL_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) +{ + my_rule->hydroFinalLevels.setTSnumber(area_1->index, 4, 8); + my_rule->hydroFinalLevels.setTSnumber(area_2->index, 11, 3); + my_rule->hydroFinalLevels.setTSnumber(area_3->index, 15, 2); + + saveScenarioBuilder(); + + // Build reference scenario builder file + referenceFile.append("[my rule name]"); + referenceFile.append("hfl,area 1,4 = 8"); + referenceFile.append("hfl,area 2,11 = 3"); + referenceFile.append("hfl,area 3,15 = 2"); + referenceFile.write(); + + BOOST_CHECK(files_identical(path_to_generated_file, referenceFile.path())); +} + // ====================== // Tests on Links NTC // ====================== BOOST_FIXTURE_TEST_CASE( - LINKS_NTC__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + LINKS_NTC__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->linksNTC[area_1->index].setDataForLink(link_12, 5, 13); my_rule->linksNTC[area_1->index].setDataForLink(link_13, 19, 8); @@ -442,7 +481,9 @@ BOOST_FIXTURE_TEST_CASE( } BOOST_FIXTURE_TEST_CASE( - BC__TS_number_for_many_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) { + BC__TS_number_for_many_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) +{ my_rule->binding_constraints.setTSnumber("group1", 5, 20); my_rule->binding_constraints.setTSnumber("group2", 19, 1); my_rule->binding_constraints.setTSnumber("group3", 5, 43); @@ -464,7 +505,8 @@ BOOST_FIXTURE_TEST_CASE( // Tests on All assets together // ================================ BOOST_FIXTURE_TEST_CASE( - ALL_TOGETHER__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, saveFixture) + ALL_TOGETHER__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical, + saveFixture) { my_rule->load.setTSnumber(area_2->index, 11, 6); my_rule->load.setTSnumber(area_3->index, 7, 2); @@ -477,7 +519,7 @@ BOOST_FIXTURE_TEST_CASE( my_rule->renewable[area_3->index].setTSnumber(rnCluster_32.get(), 5, 13); my_rule->linksNTC[area_1->index].setDataForLink(link_13, 19, 8); my_rule->linksNTC[area_2->index].setDataForLink(link_23, 2, 4); - my_rule->hydroLevels.setTSnumber(area_1->index, 5, 8); + my_rule->hydroInitialLevels.setTSnumber(area_1->index, 5, 8); my_rule->binding_constraints.setTSnumber("group3", 10, 6); saveScenarioBuilder(); diff --git a/src/tests/src/libs/antares/study/series/CMakeLists.txt b/src/tests/src/libs/antares/study/series/CMakeLists.txt new file mode 100644 index 0000000000..f525878822 --- /dev/null +++ b/src/tests/src/libs/antares/study/series/CMakeLists.txt @@ -0,0 +1,21 @@ +# ==================================== +# Tests on TimeSeries class +# ==================================== +set(SRC_TIMESERIES_TESTS + timeseries-tests.cpp +) +add_executable(timeseries-tests ${SRC_TIMESERIES_TESTS}) + +target_link_libraries(timeseries-tests + PRIVATE + Boost::unit_test_framework + Antares::series + antares-solver-simulation +) + +# Storing timeseries-tests under the folder Unit-tests in the IDE +set_target_properties(timeseries-tests PROPERTIES FOLDER Unit-tests/timeseries-tests) + +add_test(NAME timeseries-tests COMMAND timeseries-tests) + +set_property(TEST timeseries-tests PROPERTY LABELS unit) diff --git a/src/tests/src/libs/antares/study/series/timeseries-tests.cpp b/src/tests/src/libs/antares/study/series/timeseries-tests.cpp new file mode 100644 index 0000000000..4908d10601 --- /dev/null +++ b/src/tests/src/libs/antares/study/series/timeseries-tests.cpp @@ -0,0 +1,258 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE "test time series" + +#define WIN32_LEAN_AND_MEAN + +#include +#include + +#include + +#include +#include + +using namespace Antares::Data; + +// ================= +// The fixture +// ================= +struct Fixture +{ + Fixture(const Fixture& f) = delete; + Fixture(const Fixture&& f) = delete; + Fixture& operator=(const Fixture& f) = delete; + Fixture& operator=(const Fixture&& f) = delete; + + Fixture(): + ts(tsnum) + { + ts.reset(1, HOURS_PER_YEAR); + tsnum.reset(1); + tsnum[0] = 0; + } + + TimeSeriesNumbers tsnum; + TimeSeries ts; + std::string folder; + + void fillColumn(unsigned int idx); + void fillColumnReverse(unsigned int idx); + + void fillTsnum(); +}; + +void Fixture::fillColumn(unsigned int idx) +{ + for (unsigned int i = 0; i < ts.timeSeries.height; i++) + { + ts.timeSeries[idx][i] = i; + } +} + +void Fixture::fillColumnReverse(unsigned int idx) +{ + for (unsigned int i = 0; i < ts.timeSeries.height; i++) + { + ts.timeSeries[idx][i] = HOURS_PER_YEAR - i; + } +} + +void Fixture::fillTsnum() +{ + tsnum.reset(ts.timeSeries.width); + for (unsigned int i = 0; i < ts.timeSeries.width; i++) + { + tsnum[i] = i; + } +} + +class FixtureMultipleTS +{ +public: + void init(const std::vector& width) + { + const int height = 10; // Arbitrary + ts.resize(width.size()); + for (size_t idx = 0; int w: width) + { + // TimeSeries::TimeSeries does not exist, so we use pointers + ts[idx] = std::make_unique(tsnum); // ts[idx] is registered to tsnum here + tsnum.registerSeries(ts[idx].get(), std::to_string(idx)); + ts[idx]->reset(w, height); + idx++; + } + } + +public: + TimeSeriesNumbers tsnum; + +private: + std::vector> ts; +}; + +// ================== +// Tests section +// ================== + +BOOST_AUTO_TEST_SUITE(timeseries_tests) + +BOOST_FIXTURE_TEST_CASE(getSeriesIndex, Fixture) +{ + tsnum.reset(10); + for (unsigned int i = 0; i < 10; i++) + { + tsnum[i] = i; + } + + ts.resize(2, HOURS_PER_YEAR); + for (unsigned int i = 0; i < 10; i++) + { + BOOST_CHECK_EQUAL(ts.getSeriesIndex(i), i); + } +} + +BOOST_FIXTURE_TEST_CASE(getCoefficientWidth1, Fixture) +{ + fillColumn(0); + BOOST_CHECK_EQUAL(ts.getCoefficient(0, 12), 12); + BOOST_CHECK_EQUAL(ts.getCoefficient(0, 8750), 8750); +} + +BOOST_FIXTURE_TEST_CASE(getCoefficientNotInitialized, Fixture) +{ + ts.resize(4, HOURS_PER_YEAR); + fillTsnum(); + BOOST_CHECK_EQUAL(ts.getCoefficient(3, 12), 0); + BOOST_CHECK_EQUAL(ts.getCoefficient(3, 8750), 0); +} + +BOOST_FIXTURE_TEST_CASE(getCoefficientWidthMoreThan1, Fixture) +{ + ts.resize(5, HOURS_PER_YEAR); + fillTsnum(); + + fillColumn(3); + BOOST_CHECK_EQUAL(ts.getCoefficient(3, 12), 12); + BOOST_CHECK_EQUAL(ts.getCoefficient(3, 4858), 4858); + + fillColumnReverse(2); + BOOST_CHECK_EQUAL(ts.getCoefficient(2, 20), 8740); + BOOST_CHECK_EQUAL(ts.getCoefficient(2, 4567), HOURS_PER_YEAR - 4567); +} + +BOOST_FIXTURE_TEST_CASE(getColumn, Fixture) +{ + auto col = ts.getColumn(0); + BOOST_CHECK_EQUAL(col[38], 0); + BOOST_CHECK_EQUAL(col[7463], 0); + + ts.resize(4, HOURS_PER_YEAR); + fillTsnum(); + fillColumn(2); + + col = ts.getColumn(2); + BOOST_CHECK_EQUAL(col[38], 38); + BOOST_CHECK_EQUAL(col[7463], 7463); +} + +BOOST_FIXTURE_TEST_CASE(operatorArray, Fixture) +{ + ts.resize(4, HOURS_PER_YEAR); + fillTsnum(); + auto* col = ts[2]; + col[27] = 12; + BOOST_CHECK_EQUAL(ts.getCoefficient(2, 27), 12); +} + +BOOST_FIXTURE_TEST_CASE(getCoefficientSpecificData, Fixture) +{ + ts.resize(2, 2); + fillTsnum(); + tsnum[0] = 1; + tsnum[1] = 0; + ts.timeSeries[0][0] = 12.5; + ts.timeSeries[0][1] = 74.74; + ts.timeSeries[1][0] = -57; + ts.timeSeries[1][1] = 29; + + BOOST_CHECK_EQUAL(ts.getCoefficient(1, 1), 74.74); + BOOST_CHECK_EQUAL(ts.getCoefficient(0, 0), -57); + BOOST_CHECK_EQUAL(ts.getCoefficient(1, 0), 12.5); +} + +// SINGLE COLUMN +BOOST_FIXTURE_TEST_CASE(getCoefficient_SingleColumn, Fixture) +{ + ts.resize(1, 2); + + // Here, we provide 2 time series numbers... + tsnum.reset(2); + for (unsigned int i = 0; i < 2; i++) + { + tsnum[i] = i; + } + + // ...but only one column + ts.timeSeries[0][0] = 12.5; + ts.timeSeries[0][1] = 74.74; + + // year=1 + BOOST_CHECK_EQUAL(ts.getCoefficient(0, 0), 12.5); + BOOST_CHECK_EQUAL(ts.getCoefficient(0, 1), 74.74); + + // year=2 + BOOST_CHECK_EQUAL(ts.getCoefficient(1, 0), 12.5); + BOOST_CHECK_EQUAL(ts.getCoefficient(1, 1), 74.74); +} + +// VALID CONFIGURATIONS +BOOST_FIXTURE_TEST_CASE(checkSizeOK_1TS, FixtureMultipleTS) +{ + init({11}); + BOOST_CHECK(!tsnum.checkSeriesNumberOfColumnsConsistency()); +} + +BOOST_FIXTURE_TEST_CASE(checkSizeOK_2TS, FixtureMultipleTS) +{ + init({12, 12}); + BOOST_CHECK(!tsnum.checkSeriesNumberOfColumnsConsistency()); +} + +BOOST_FIXTURE_TEST_CASE(checkSizeOK_4TS, FixtureMultipleTS) +{ + init({22, 22, 1, 22}); + BOOST_CHECK(!tsnum.checkSeriesNumberOfColumnsConsistency()); +} + +BOOST_FIXTURE_TEST_CASE(checkSizeKO_2TS, FixtureMultipleTS) +{ + init({11, 12}); + BOOST_CHECK(tsnum.checkSeriesNumberOfColumnsConsistency()); +} + +BOOST_FIXTURE_TEST_CASE(checkSizeKO_4TS, FixtureMultipleTS) +{ + init({22, 22, 1, 21}); + BOOST_CHECK(tsnum.checkSeriesNumberOfColumnsConsistency()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/short-term-storage-input/CMakeLists.txt b/src/tests/src/libs/antares/study/short-term-storage-input/CMakeLists.txt index 458fa7b28f..045e8ed944 100644 --- a/src/tests/src/libs/antares/study/short-term-storage-input/CMakeLists.txt +++ b/src/tests/src/libs/antares/study/short-term-storage-input/CMakeLists.txt @@ -5,7 +5,7 @@ set(src_libs_antares_study "${CMAKE_SOURCE_DIR}/libs/antares/study") # Tests on reading scenario-builder # ==================================== set(SRC_SC_BUILDER_READ - short-term-storage-input.cpp + short-term-storage-input-output.cpp ) add_executable(short-term-storage-input ${SRC_SC_BUILDER_READ}) diff --git a/src/tests/src/libs/antares/study/short-term-storage-input/short-term-storage-input-output.cpp b/src/tests/src/libs/antares/study/short-term-storage-input/short-term-storage-input-output.cpp new file mode 100644 index 0000000000..83965049e6 --- /dev/null +++ b/src/tests/src/libs/antares/study/short-term-storage-input/short-term-storage-input-output.cpp @@ -0,0 +1,348 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE "test short term storage" + +#define WIN32_LEAN_AND_MEAN + +#include +#include + +#include + +#include + +#include "antares/study/parts/short-term-storage/container.h" + +#define SEP Yuni::IO::Separator + +using namespace std; +using namespace Antares::Data; + +namespace +{ +std::string getFolder() +{ + std::filesystem::path tmpDir = std::filesystem::temp_directory_path(); + return tmpDir.string(); +} + +void resizeFillVectors(ShortTermStorage::Series& series, double value, unsigned int size) +{ + series.maxInjectionModulation.resize(size, value); + series.maxWithdrawalModulation.resize(size, value); + series.inflows.resize(size, value); + series.lowerRuleCurve.resize(size, value); + series.upperRuleCurve.resize(size, value); +} + +void createIndividualFileSeries(const std::string& path, double value, unsigned int size) +{ + std::ofstream outfile(path); + + for (unsigned int i = 0; i < size; i++) + { + outfile << value << std::endl; + } + + outfile.close(); +} + +void createIndividualFileSeries(const std::string& path, unsigned int size) +{ + std::ofstream outfile; + outfile.open(path, std::ofstream::out | std::ofstream::trunc); + + for (unsigned int i = 0; i < size; i++) + { + double value = i * 0.0001; + outfile << value << std::endl; + } + + outfile.close(); +} + +void createFileSeries(double value, unsigned int size) +{ + std::string folder = getFolder(); + + createIndividualFileSeries(folder + SEP + "PMAX-injection.txt", value, size); + createIndividualFileSeries(folder + SEP + "PMAX-withdrawal.txt", value, size); + createIndividualFileSeries(folder + SEP + "inflows.txt", value, size); + createIndividualFileSeries(folder + SEP + "lower-rule-curve.txt", value, size); + createIndividualFileSeries(folder + SEP + "upper-rule-curve.txt", value, size); +} + +void createFileSeries(unsigned int size) +{ + std::string folder = getFolder(); + + createIndividualFileSeries(folder + SEP + "PMAX-injection.txt", size); + createIndividualFileSeries(folder + SEP + "PMAX-withdrawal.txt", size); + createIndividualFileSeries(folder + SEP + "inflows.txt", size); + createIndividualFileSeries(folder + SEP + "lower-rule-curve.txt", size); + createIndividualFileSeries(folder + SEP + "upper-rule-curve.txt", size); +} + +void createIniFile(bool enabled) +{ + std::string folder = getFolder(); + + std::ofstream outfile; + outfile.open(folder + SEP + "list.ini", std::ofstream::out | std::ofstream::trunc); + + outfile << "[area]" << std::endl; + outfile << "name = area" << std::endl; + outfile << "group = PSP_open" << std::endl; + outfile << "injectionnominalcapacity = 870.000000" << std::endl; + outfile << "withdrawalnominalcapacity = 900.000000" << std::endl; + outfile << "reservoircapacity = 31200.000000" << std::endl; + outfile << "efficiency = 0.75" << std::endl; + outfile << "initiallevel = 0.50000" << std::endl; + outfile << "enabled = " << (enabled ? "true" : "false") << std::endl; + outfile.close(); +} + +void createIniFileWrongValue() +{ + std::string folder = getFolder(); + + std::ofstream outfile; + outfile.open(folder + SEP + "list.ini", std::ofstream::out | std::ofstream::trunc); + + outfile << "[area]" << std::endl; + outfile << "name = area" << std::endl; + outfile << "group = abcde" << std::endl; + outfile << "injectionnominalcapacity = -870.000000" << std::endl; + outfile << "withdrawalnominalcapacity = -900.000000" << std::endl; + outfile << "reservoircapacity = -31200.000000" << std::endl; + outfile << "efficiency = 4" << std::endl; + outfile << "initiallevel = -0.50000" << std::endl; + + outfile.close(); +} + +void createEmptyIniFile() +{ + std::string folder = getFolder(); + + std::ofstream outfile; + outfile.open(folder + SEP + "list.ini", std::ofstream::out | std::ofstream::trunc); + + outfile.close(); +} + +void removeIniFile() +{ + std::string folder = getFolder(); + std::filesystem::remove(folder + SEP + "list.ini"); +} +} // namespace + +// ================= +// The fixture +// ================= +struct Fixture +{ + Fixture(const Fixture& f) = delete; + Fixture(const Fixture&& f) = delete; + Fixture& operator=(const Fixture& f) = delete; + Fixture& operator=(const Fixture&& f) = delete; + Fixture() = default; + + ~Fixture() + { + std::filesystem::remove(folder + SEP + "PMAX-injection.txt"); + std::filesystem::remove(folder + SEP + "PMAX-withdrawal.txt"); + std::filesystem::remove(folder + SEP + "inflows.txt"); + std::filesystem::remove(folder + SEP + "lower-rule-curve.txt"); + std::filesystem::remove(folder + SEP + "upper-rule-curve.txt"); + } + + std::string folder = getFolder(); + + ShortTermStorage::Series series; + ShortTermStorage::Properties properties; + ShortTermStorage::STStorageCluster cluster; + ShortTermStorage::STStorageInput container; +}; + +// ================== +// Tests section +// ================== + +BOOST_AUTO_TEST_SUITE(s) + +BOOST_FIXTURE_TEST_CASE(check_vector_sizes, Fixture) +{ + resizeFillVectors(series, 0.0, 12); + BOOST_CHECK(!series.validate()); + + resizeFillVectors(series, 0.0, 8760); + BOOST_CHECK(series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_series_folder_loading, Fixture) +{ + createFileSeries(1.0, 8760); + + BOOST_CHECK(series.loadFromFolder(folder)); + BOOST_CHECK(series.validate()); + BOOST_CHECK(series.inflows[0] == 1 && series.maxInjectionModulation[8759] == 1 + && series.upperRuleCurve[1343] == 1); +} + +BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_different_values, Fixture) +{ + createFileSeries(8760); + + BOOST_CHECK(series.loadFromFolder(folder)); + BOOST_CHECK(series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_negative_value, Fixture) +{ + createFileSeries(-247.0, 8760); + + BOOST_CHECK(series.loadFromFolder(folder)); + BOOST_CHECK(!series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_too_big, Fixture) +{ + createFileSeries(1.0, 9000); + + BOOST_CHECK(series.loadFromFolder(folder)); + BOOST_CHECK(series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_too_small, Fixture) +{ + createFileSeries(1.0, 100); + + BOOST_CHECK(!series.loadFromFolder(folder)); + BOOST_CHECK(!series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_empty, Fixture) +{ + BOOST_CHECK(series.loadFromFolder(folder)); + BOOST_CHECK(!series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_series_vector_fill, Fixture) +{ + series.fillDefaultSeriesIfEmpty(); + BOOST_CHECK(series.validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_cluster_series_vector_fill, Fixture) +{ + BOOST_CHECK(cluster.loadSeries(folder)); + BOOST_CHECK(cluster.series->validate()); +} + +BOOST_FIXTURE_TEST_CASE(check_cluster_series_load_vector, Fixture) +{ + createFileSeries(0.5, 8760); + + BOOST_CHECK(cluster.loadSeries(folder)); + BOOST_CHECK(cluster.series->validate()); + BOOST_CHECK(cluster.series->maxWithdrawalModulation[0] == 0.5 + && cluster.series->inflows[2756] == 0.5 + && cluster.series->lowerRuleCurve[6392] == 0.5); +} + +BOOST_FIXTURE_TEST_CASE(check_container_properties_enabled_load, Fixture) +{ + createIniFile(true); + + BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); + + auto& properties = container.storagesByIndex[0].properties; + + BOOST_CHECK(properties.enabled); + BOOST_CHECK_EQUAL(container.count(), 1); + BOOST_CHECK(properties.validate()); + + removeIniFile(); +} + +BOOST_FIXTURE_TEST_CASE(check_container_properties_disabled_load, Fixture) +{ + createIniFile(false); + + BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); + + auto& properties = container.storagesByIndex[0].properties; + + BOOST_CHECK(!properties.enabled); + BOOST_CHECK_EQUAL(container.count(), 0); + BOOST_CHECK(properties.validate()); + + removeIniFile(); +} + +BOOST_FIXTURE_TEST_CASE(check_container_properties_wrong_value, Fixture) +{ + createIniFileWrongValue(); + + BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); + BOOST_CHECK(!container.storagesByIndex[0].properties.validate()); + + removeIniFile(); +} + +BOOST_FIXTURE_TEST_CASE(check_container_properties_empty_file, Fixture) +{ + createEmptyIniFile(); + + BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); + + removeIniFile(); +} + +BOOST_FIXTURE_TEST_CASE(check_file_save, Fixture) +{ + createIniFile(true); + + BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); + + removeIniFile(); + + BOOST_CHECK(container.saveToFolder(folder)); + + BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); + + removeIniFile(); +} + +BOOST_FIXTURE_TEST_CASE(check_series_save, Fixture) +{ + resizeFillVectors(series, 0.123456789, 8760); + + BOOST_CHECK(series.saveToFolder(folder)); + resizeFillVectors(series, 0, 0); + + BOOST_CHECK(series.loadFromFolder(folder)); + BOOST_CHECK(series.validate()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/short-term-storage-input/short-term-storage-input.cpp b/src/tests/src/libs/antares/study/short-term-storage-input/short-term-storage-input.cpp deleted file mode 100644 index bc2c4b0f8c..0000000000 --- a/src/tests/src/libs/antares/study/short-term-storage-input/short-term-storage-input.cpp +++ /dev/null @@ -1,302 +0,0 @@ -#define BOOST_TEST_MODULE "test short term storage" -#define BOOST_TEST_DYN_LINK - -#define WIN32_LEAN_AND_MEAN - -#include -#include -#include -#include - -#include "container.h" - -#define SEP Yuni::IO::Separator - -using namespace std; -using namespace Antares::Data; - -std::string getFolder() -{ - std::filesystem::path tmpDir = std::filesystem::temp_directory_path(); - return tmpDir.string(); -} - -void resizeFillVectors(ShortTermStorage::Series& series, double value, unsigned int size) -{ - series.maxInjectionModulation.resize(size, value); - series.maxWithdrawalModulation.resize(size, value); - series.inflows.resize(size, value); - series.lowerRuleCurve.resize(size, value); - series.upperRuleCurve.resize(size, value); -} - -void createIndividualFileSeries(const std::string& path, double value, unsigned int size) -{ - std::ofstream outfile(path); - - for (unsigned int i = 0; i < size; i++) - outfile << value << std::endl; - - outfile.close(); -} - -void createIndividualFileSeries(const std::string& path, unsigned int size) -{ - std::ofstream outfile; - outfile.open(path, std::ofstream::out | std::ofstream::trunc); - - for (unsigned int i = 0; i < size; i++) - { - double value = i * 0.0001; - outfile << value << std::endl; - } - - outfile.close(); -} - -void createFileSeries(double value, unsigned int size) -{ - std::string folder = getFolder(); - - createIndividualFileSeries(folder + SEP + "PMAX-injection.txt", value, size); - createIndividualFileSeries(folder + SEP + "PMAX-withdrawal.txt", value, size); - createIndividualFileSeries(folder + SEP + "inflows.txt", value, size); - createIndividualFileSeries(folder + SEP + "lower-rule-curve.txt", value, size); - createIndividualFileSeries(folder + SEP + "upper-rule-curve.txt", value, size); -} - -void createFileSeries(unsigned int size) -{ - std::string folder = getFolder(); - - createIndividualFileSeries(folder + SEP + "PMAX-injection.txt", size); - createIndividualFileSeries(folder + SEP + "PMAX-withdrawal.txt", size); - createIndividualFileSeries(folder + SEP + "inflows.txt", size); - createIndividualFileSeries(folder + SEP + "lower-rule-curve.txt", size); - createIndividualFileSeries(folder + SEP + "upper-rule-curve.txt", size); -} - -void createIniFile() -{ - std::string folder = getFolder(); - - std::ofstream outfile; - outfile.open(folder + SEP + "list.ini", std::ofstream::out | std::ofstream::trunc); - - outfile << "[area]" << std::endl; - outfile << "name = area" << std::endl; - outfile << "group = PSP_open" << std::endl; - outfile << "injectionnominalcapacity = 870.000000" << std::endl; - outfile << "withdrawalnominalcapacity = 900.000000" << std::endl; - outfile << "reservoircapacity = 31200.000000" << std::endl; - outfile << "efficiency = 0.75" << std::endl; - outfile << "initiallevel = 0.50000" << std::endl; - - outfile.close(); -} - -void createIniFileWrongValue() -{ - std::string folder = getFolder(); - - std::ofstream outfile; - outfile.open(folder + SEP + "list.ini", std::ofstream::out | std::ofstream::trunc); - - outfile << "[area]" << std::endl; - outfile << "name = area" << std::endl; - outfile << "group = abcde" << std::endl; - outfile << "injectionnominalcapacity = -870.000000" << std::endl; - outfile << "withdrawalnominalcapacity = -900.000000" << std::endl; - outfile << "reservoircapacity = -31200.000000" << std::endl; - outfile << "efficiency = 4" << std::endl; - outfile << "initiallevel = -0.50000" << std::endl; - - outfile.close(); -} - -void createEmptyIniFile() -{ - std::string folder = getFolder(); - - std::ofstream outfile; - outfile.open(folder + SEP + "list.ini", std::ofstream::out | std::ofstream::trunc); - - outfile.close(); -} - -void removeIniFile() -{ - std::string folder = getFolder(); - std::filesystem::remove(folder + SEP + "list.ini"); -} - -// ================= -// The fixture -// ================= -struct Fixture -{ - Fixture(const Fixture & f) = delete; - Fixture(const Fixture && f) = delete; - Fixture & operator= (const Fixture & f) = delete; - Fixture& operator= (const Fixture && f) = delete; - Fixture() = default; - ~Fixture() - { - std::filesystem::remove(folder + SEP + "PMAX-injection.txt"); - std::filesystem::remove(folder + SEP + "PMAX-withdrawal.txt"); - std::filesystem::remove(folder + SEP + "inflows.txt"); - std::filesystem::remove(folder + SEP + "lower-rule-curve.txt"); - std::filesystem::remove(folder + SEP + "upper-rule-curve.txt"); - } - - std::string folder = getFolder(); - - ShortTermStorage::Series series; - ShortTermStorage::Properties properties; - ShortTermStorage::STStorageCluster cluster; - ShortTermStorage::STStorageInput container; -}; - - -// ================== -// Tests section -// ================== - -BOOST_AUTO_TEST_SUITE(s) - -BOOST_FIXTURE_TEST_CASE(check_vector_sizes, Fixture) -{ - resizeFillVectors(series, 0.0, 12); - BOOST_CHECK(!series.validate()); - - resizeFillVectors(series, 0.0, 8760); - BOOST_CHECK(series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_series_folder_loading, Fixture) -{ - createFileSeries(1.0, 8760); - - BOOST_CHECK(series.loadFromFolder(folder)); - BOOST_CHECK(series.validate()); - BOOST_CHECK(series.inflows[0] == 1 && series.maxInjectionModulation[8759] == 1 - && series.upperRuleCurve[1343] == 1); -} - -BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_different_values, Fixture) -{ - createFileSeries(8760); - - BOOST_CHECK(series.loadFromFolder(folder)); - BOOST_CHECK(series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_negative_value, Fixture) -{ - createFileSeries(-247.0, 8760); - - BOOST_CHECK(series.loadFromFolder(folder)); - BOOST_CHECK(!series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_too_big, Fixture) -{ - createFileSeries(1.0, 9000); - - BOOST_CHECK(series.loadFromFolder(folder)); - BOOST_CHECK(series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_too_small, Fixture) -{ - createFileSeries(1.0, 100); - - BOOST_CHECK(!series.loadFromFolder(folder)); - BOOST_CHECK(!series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_series_folder_loading_empty, Fixture) -{ - BOOST_CHECK(series.loadFromFolder(folder)); - BOOST_CHECK(!series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_series_vector_fill, Fixture) -{ - series.fillDefaultSeriesIfEmpty(); - BOOST_CHECK(series.validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_cluster_series_vector_fill, Fixture) -{ - BOOST_CHECK(cluster.loadSeries(folder)); - BOOST_CHECK(cluster.series->validate()); -} - -BOOST_FIXTURE_TEST_CASE(check_cluster_series_load_vector, Fixture) -{ - createFileSeries(0.5, 8760); - - BOOST_CHECK(cluster.loadSeries(folder)); - BOOST_CHECK(cluster.series->validate()); - BOOST_CHECK(cluster.series->maxWithdrawalModulation[0] == 0.5 - && cluster.series->inflows[2756] == 0.5 - && cluster.series->lowerRuleCurve[6392] == 0.5); -} - -BOOST_FIXTURE_TEST_CASE(check_container_properties_load, Fixture) -{ - createIniFile(); - - BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); - BOOST_CHECK(container.storagesByIndex[0]->properties.validate()); - - removeIniFile(); -} - -BOOST_FIXTURE_TEST_CASE(check_container_properties_wrong_value, Fixture) -{ - createIniFileWrongValue(); - - BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); - BOOST_CHECK(!container.storagesByIndex[0]->properties.validate()); - - removeIniFile(); -} - -BOOST_FIXTURE_TEST_CASE(check_container_properties_empty_file, Fixture) -{ - createEmptyIniFile(); - - BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); - - removeIniFile(); -} - -BOOST_FIXTURE_TEST_CASE(check_file_save, Fixture) -{ - createIniFile(); - - BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); - - removeIniFile(); - - BOOST_CHECK(container.saveToFolder(folder)); - - BOOST_CHECK(container.createSTStorageClustersFromIniFile(folder)); - - removeIniFile(); -} - -BOOST_FIXTURE_TEST_CASE(check_series_save, Fixture) -{ - resizeFillVectors(series, 0.123456789, 8760); - - BOOST_CHECK(series.saveToFolder(folder)); - resizeFillVectors(series, 0, 0); - - BOOST_CHECK(series.loadFromFolder(folder)); - BOOST_CHECK(series.validate()); -} - -BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/study/test_study.cpp b/src/tests/src/libs/antares/study/test_study.cpp new file mode 100644 index 0000000000..104b304c0e --- /dev/null +++ b/src/tests/src/libs/antares/study/test_study.cpp @@ -0,0 +1,294 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE study +#define WIN32_LEAN_AND_MEAN +#include + +#include "antares/study/study.h" + +using namespace Antares::Data; + +/*! + * Study with one area named "A" + */ +struct OneAreaStudy +{ + OneAreaStudy() + { + study = std::make_unique(); + areaA = study->areaAdd("A"); + study->parameters.simulationDays.first = 0; + study->parameters.simulationDays.end = 7; + } + + std::unique_ptr study; + Area* areaA; +}; + +BOOST_AUTO_TEST_SUITE(areas_operations) + +BOOST_AUTO_TEST_CASE(area_add) +{ + auto study = std::make_unique(); + const auto areaA = study->areaAdd("A"); + BOOST_CHECK(areaA != nullptr); + BOOST_CHECK_EQUAL(areaA->name, "A"); + BOOST_CHECK_EQUAL(areaA->id, "a"); +} + +BOOST_FIXTURE_TEST_CASE(area_rename, OneAreaStudy) +{ + BOOST_CHECK(study->areaRename(areaA, "B")); + BOOST_CHECK(areaA->name == "B"); + BOOST_CHECK(areaA->id == "b"); +} + +BOOST_FIXTURE_TEST_CASE(area_delete, OneAreaStudy) +{ + BOOST_CHECK_EQUAL(study->areas.size(), 1); + BOOST_CHECK(study->areaDelete(areaA)); + BOOST_CHECK(study->areas.empty()); +} + +BOOST_AUTO_TEST_SUITE_END() // areas + +// Check that disabled objects are indeed removed from computations +BOOST_AUTO_TEST_SUITE(remove_disabled) + +BOOST_FIXTURE_TEST_CASE(thermal_cluster_delete, OneAreaStudy) +{ + auto disabledCluster = std::make_shared(areaA); + disabledCluster->setName("Cluster1"); + disabledCluster->enabled = false; + auto enabledCluster = std::make_shared(areaA); + enabledCluster->setName("Cluster2"); + enabledCluster->enabled = true; + + areaA->thermal.list.addToCompleteList(disabledCluster); + areaA->thermal.list.addToCompleteList(enabledCluster); + + // Check that "Cluster1" isn't found + for (const auto& c: areaA->thermal.list.each_enabled()) + { + BOOST_CHECK(c->name() != "Cluster1"); + } +} + +BOOST_FIXTURE_TEST_CASE(renewable_cluster_delete, OneAreaStudy) +{ + auto disabledCluster = std::make_shared(areaA); + disabledCluster->setName("Cluster1"); + disabledCluster->enabled = false; + auto enabledCluster = std::make_shared(areaA); + enabledCluster->setName("Cluster2"); + enabledCluster->enabled = true; + + areaA->renewable.list.addToCompleteList(disabledCluster); + areaA->renewable.list.addToCompleteList(enabledCluster); + + // Check that "Cluster1" isn't found + for (const auto& c: areaA->renewable.list.each_enabled()) + { + BOOST_CHECK(c->name() != "Cluster1"); + } +} + +BOOST_FIXTURE_TEST_CASE(short_term_storage_delete, OneAreaStudy) +{ + auto& sts = areaA->shortTermStorage.storagesByIndex; + + auto addSTS = [&sts](std::string&& name, bool enabled) + { + ShortTermStorage::STStorageCluster cluster; + cluster.properties.name = name; + cluster.properties.enabled = enabled; + sts.push_back(cluster); + }; + + addSTS("Cluster1", true); + addSTS("Cluster2", false); + + auto findDisabledCluster = [&sts](std::string&& name) + { + return std::find_if(sts.begin(), + sts.end(), + [&name](ShortTermStorage::STStorageCluster& c) + { return c.properties.name == name; }); + }; + + // Check that "Cluster1" and "Cluster2" are found + BOOST_CHECK(findDisabledCluster("Cluster1") != sts.end()); + BOOST_CHECK(findDisabledCluster("Cluster2") != sts.end()); + + study->initializeRuntimeInfos(); // This should remove all disabled short-term storages + + // Check that only "Cluster1" is found + BOOST_CHECK(findDisabledCluster("Cluster1") != sts.end()); + BOOST_CHECK(findDisabledCluster("Cluster2") == sts.end()); + + // operator<< doesn't exist for iterators, Boost can't generate output in case of failure, so we + // use BOOST_CHECK instead of BOOST_CHECK_EQUAL +} + +BOOST_AUTO_TEST_SUITE_END() // remove_disabled + +BOOST_AUTO_TEST_SUITE(thermal_clusters_operations) + +BOOST_FIXTURE_TEST_CASE(thermal_cluster_add, OneAreaStudy) +{ + auto newCluster = std::make_shared(areaA); + newCluster->setName("Cluster"); + BOOST_CHECK_EQUAL(newCluster->name(), "Cluster"); + BOOST_CHECK_EQUAL(newCluster->id(), "cluster"); + + areaA->thermal.list.addToCompleteList(newCluster); + BOOST_CHECK_EQUAL(areaA->thermal.list.findInAll("cluster"), newCluster.get()); + BOOST_CHECK_EQUAL(areaA->thermal.list.findInAll("Cluster"), nullptr); +} + +/*! + * Study with: + * - one area named "A" + * - one thermal cluster named "Cluster" + */ +struct ThermalClusterStudy: public OneAreaStudy +{ + ThermalClusterStudy() + { + auto newCluster = std::make_shared(areaA); + newCluster->setName("Cluster"); + areaA->thermal.list.addToCompleteList(newCluster); + cluster = newCluster.get(); + } + + ThermalCluster* cluster; +}; + +BOOST_FIXTURE_TEST_CASE(thermal_cluster_rename, ThermalClusterStudy) +{ + BOOST_CHECK(study->clusterRename(cluster, "Renamed")); + BOOST_CHECK(cluster->name() == "Renamed"); + BOOST_CHECK(cluster->id() == "renamed"); +} + +BOOST_FIXTURE_TEST_CASE(thermal_cluster_delete, ThermalClusterStudy) +{ + // gp : remove() only used in GUI (will go away when removing the GUI) + BOOST_CHECK(areaA->thermal.list.findInAll("cluster") == cluster); + areaA->thermal.list.remove("cluster"); + BOOST_CHECK(areaA->thermal.list.findInAll("cluster") == nullptr); + BOOST_CHECK(areaA->thermal.list.empty()); +} + +BOOST_AUTO_TEST_SUITE_END() // thermal clusters + +BOOST_AUTO_TEST_SUITE(renewable_clusters_operations) + +BOOST_FIXTURE_TEST_CASE(renewable_cluster_add, OneAreaStudy) +{ + auto newCluster = std::make_shared(areaA); + newCluster->setName("WindCluster"); + BOOST_CHECK(newCluster->name() == "WindCluster"); + BOOST_CHECK(newCluster->id() == "windcluster"); + + areaA->renewable.list.addToCompleteList(newCluster); + BOOST_CHECK(areaA->renewable.list.findInAll("windcluster") == newCluster.get()); + BOOST_CHECK(areaA->renewable.list.findInAll("WindCluster") == nullptr); +} + +/*! + * Study with: + * - one area named "A" + * - one renewable cluster named "WindCluster" + */ +struct RenewableClusterStudy: public OneAreaStudy +{ + RenewableClusterStudy() + { + areaA = study->areaAdd("A"); + auto newCluster = std::make_shared(areaA); + newCluster->setName("WindCluster"); + areaA->renewable.list.addToCompleteList(newCluster); + cluster = newCluster.get(); + } + + RenewableCluster* cluster; +}; + +BOOST_FIXTURE_TEST_CASE(renewable_cluster_rename, RenewableClusterStudy) +{ + BOOST_CHECK(study->clusterRename(cluster, "Renamed")); + BOOST_CHECK(cluster->name() == "Renamed"); + BOOST_CHECK(cluster->id() == "renamed"); +} + +BOOST_FIXTURE_TEST_CASE(renewable_cluster_delete, RenewableClusterStudy) +{ + // gp : remove() only used in GUI (will go away when removing the GUI) + BOOST_CHECK(areaA->renewable.list.findInAll("windcluster") == cluster); + BOOST_CHECK(areaA->renewable.list.remove("windcluster")); + BOOST_CHECK(areaA->renewable.list.findInAll("windcluster") == nullptr); + BOOST_CHECK(areaA->renewable.list.empty()); +} + +BOOST_AUTO_TEST_SUITE_END() // renewable clusters + +BOOST_AUTO_TEST_SUITE(studyVersion_class) + +BOOST_AUTO_TEST_CASE(version_comparison) +{ + StudyVersion v1(7, 2), v2(8, 0), v3; + v3.fromString("8.0"); + BOOST_CHECK(v1 < v2); + BOOST_CHECK(!(v1 > v2)); + BOOST_CHECK(v1 != v2); + BOOST_CHECK(v2 == v3); + BOOST_CHECK(StudyVersion(12, 3) > StudyVersion(1, 23)); + + BOOST_CHECK_EQUAL(StudyVersion(7, 5).toString(), "7.5"); +} + +BOOST_AUTO_TEST_CASE(version_parsing) +{ + StudyVersion v; + v.fromString("7.2"); + BOOST_CHECK(v == StudyVersion(7, 2)); + BOOST_CHECK(!v.fromString("abc")); + BOOST_CHECK(v == StudyVersion::unknown()); + BOOST_CHECK(!v.fromString("a8.7")); + BOOST_CHECK(!v.fromString("8.b7")); + + // legacy format + BOOST_CHECK(!v.fromString("8a60")); + BOOST_CHECK(!v.fromString("a860")); + v.fromString("860"); + BOOST_CHECK(v == StudyVersion(8, 6)); + + v.fromString("8.8"); + BOOST_CHECK(v == StudyVersion(8, 8)); + BOOST_CHECK(!v.fromString("8..6")); + + // 4.5 is not in the list of supported versions, thus failing + BOOST_CHECK(!v.fromString("4.5")); + BOOST_CHECK(v == StudyVersion::unknown()); +} +BOOST_AUTO_TEST_SUITE_END() // version diff --git a/src/tests/src/libs/antares/study/thermal-price-definition/thermal-price-definition.cpp b/src/tests/src/libs/antares/study/thermal-price-definition/thermal-price-definition.cpp index 7748e7466d..cfef5909e5 100644 --- a/src/tests/src/libs/antares/study/thermal-price-definition/thermal-price-definition.cpp +++ b/src/tests/src/libs/antares/study/thermal-price-definition/thermal-price-definition.cpp @@ -1,20 +1,39 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE "test thermal price definition" -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN -#include -#include #include #include -#include -#include +#include + +#include #include -#include "cluster_list.h" +#include +#include +#include "antares/study/parts/thermal/cluster_list.h" -const auto SEP = Yuni::IO::Separator; using namespace Antares::Data; using std::filesystem::temp_directory_path; @@ -55,7 +74,8 @@ struct ThermalIniFile struct TimeSeriesFile { - TimeSeriesFile(const std::string& name, std::size_t size) : name_(name) + TimeSeriesFile(const std::string& name, std::size_t size): + name_(name) { folder = temp_directory_path(); std::ofstream outfile(folder / name, std::ofstream::out | std::ofstream::trunc); @@ -71,7 +91,8 @@ struct TimeSeriesFile std::filesystem::remove(folder / name_); } - std::string getFolder() { + std::string getFolder() + { return folder.string(); } @@ -90,12 +111,13 @@ void fillThermalEconomicTimeSeries(ThermalCluster* c) // ================= // The fixture // ================= -struct FixtureFull : private ThermalIniFile +struct FixtureFull: private ThermalIniFile { FixtureFull(const FixtureFull& f) = delete; FixtureFull(const FixtureFull&& f) = delete; FixtureFull& operator=(const FixtureFull& f) = delete; FixtureFull& operator=(const FixtureFull&& f) = delete; + FixtureFull() { area = study->areaAdd("area"); @@ -123,6 +145,7 @@ struct FixtureStudyOnly // Here, we need the "lightweight fixture" BOOST_AUTO_TEST_SUITE(EconomicInputData_loadFromFolder) + BOOST_FIXTURE_TEST_CASE(EconomicInputData_loadFromFolder_OK, FixtureStudyOnly) { TimeSeriesFile fuelCostTSfile("fuelCost.txt", 8760); @@ -132,7 +155,8 @@ BOOST_FIXTURE_TEST_CASE(EconomicInputData_loadFromFolder_OK, FixtureStudyOnly) BOOST_CHECK_EQUAL(eco.fuelcost[0][1432], 1); } -BOOST_FIXTURE_TEST_CASE(EconomicInputData_loadFromFolder_failing_not_enough_values, FixtureStudyOnly) +BOOST_FIXTURE_TEST_CASE(EconomicInputData_loadFromFolder_failing_not_enough_values, + FixtureStudyOnly) { TimeSeriesFile fuelCostTSfile("fuelCost.txt", 80); EconomicInputData eco; @@ -148,10 +172,11 @@ BOOST_FIXTURE_TEST_CASE(EconomicInputData_loadFromFolder_working_with_many_value BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(s) + BOOST_FIXTURE_TEST_CASE(ThermalClusterList_loadFromFolder_basic, FixtureFull) { clusterList.loadFromFolder(*study, folder, area); - auto cluster = clusterList.mapping["some cluster"]; + auto cluster = clusterList.findInAll("some cluster"); BOOST_CHECK(cluster->startupCost == 70000.0); BOOST_CHECK(cluster->costgeneration == useCostTimeseries); @@ -162,12 +187,9 @@ BOOST_FIXTURE_TEST_CASE(ThermalClusterList_loadFromFolder_basic, FixtureFull) BOOST_FIXTURE_TEST_CASE(checkCo2_checkCO2CostColumnNumber_OK, FixtureFull) { area->thermal.list.loadFromFolder(*study, folder, area); - auto cluster = area->thermal.list.mapping["some cluster"]; + auto cluster = area->thermal.list.findInAll("some cluster"); - cluster->series = new DataSeriesCommon; - cluster->series->timeSeries.reset(3, 8760); - - area->thermal.prepareAreaWideIndexes(); + cluster->series.timeSeries.reset(3, 8760); auto& ecoInput = cluster->ecoInput; ecoInput.co2cost.reset(3, 8760); @@ -178,12 +200,9 @@ BOOST_FIXTURE_TEST_CASE(checkCo2_checkCO2CostColumnNumber_OK, FixtureFull) BOOST_FIXTURE_TEST_CASE(checkCo2_checkCO2CostColumnNumber_KO, FixtureFull) { area->thermal.list.loadFromFolder(*study, folder, area); - auto cluster = area->thermal.list.mapping["some cluster"]; - - cluster->series = new DataSeriesCommon; - cluster->series->timeSeries.reset(3, 8760); + auto cluster = area->thermal.list.findInAll("some cluster"); - area->thermal.prepareAreaWideIndexes(); + cluster->series.timeSeries.reset(3, 8760); auto& ecoInput = cluster->ecoInput; ecoInput.co2cost.reset(2, 8760); @@ -195,12 +214,9 @@ BOOST_FIXTURE_TEST_CASE(checkCo2_checkCO2CostColumnNumber_KO, FixtureFull) BOOST_FIXTURE_TEST_CASE(checkFuelAndCo2_checkColumnNumber_OK, FixtureFull) { area->thermal.list.loadFromFolder(*study, folder, area); - auto cluster = area->thermal.list.mapping["some cluster"]; - - cluster->series = new DataSeriesCommon; - cluster->series->timeSeries.reset(3, 8760); + auto cluster = area->thermal.list.findInAll("some cluster"); - area->thermal.prepareAreaWideIndexes(); + cluster->series.timeSeries.reset(3, 8760); cluster->ecoInput.fuelcost.reset(3, 8760); cluster->ecoInput.co2cost.reset(3, 8760); @@ -209,10 +225,11 @@ BOOST_FIXTURE_TEST_CASE(checkFuelAndCo2_checkColumnNumber_OK, FixtureFull) BOOST_CHECK_NO_THROW(Antares::Check::checkCO2CostColumnNumber(study->areas)); } -BOOST_FIXTURE_TEST_CASE(ThermalCluster_costGenManualCalculationOfMarketBidAndMarginalCostPerHour, FixtureFull) +BOOST_FIXTURE_TEST_CASE(ThermalCluster_costGenManualCalculationOfMarketBidAndMarginalCostPerHour, + FixtureFull) { clusterList.loadFromFolder(*study, folder, area); - auto cluster = clusterList.mapping["some cluster"]; + auto cluster = clusterList.findInAll("some cluster"); cluster->costgeneration = Data::setManually; cluster->ComputeCostTimeSeries(); @@ -221,17 +238,19 @@ BOOST_FIXTURE_TEST_CASE(ThermalCluster_costGenManualCalculationOfMarketBidAndMar BOOST_CHECK_EQUAL(cluster->costsTimeSeries[0].marginalCostTS[6737], 23); } -BOOST_FIXTURE_TEST_CASE(ThermalCluster_costGenTimeSeriesCalculationOfMarketBidAndMarginalCostPerHour, FixtureFull) +BOOST_FIXTURE_TEST_CASE( + ThermalCluster_costGenTimeSeriesCalculationOfMarketBidAndMarginalCostPerHour, + FixtureFull) { TimeSeriesFile fuel("fuelCost.txt", 8760); TimeSeriesFile co2("CO2Cost.txt", 8760); clusterList.loadFromFolder(*study, folder, area); - auto cluster = clusterList.mapping["some cluster"]; + auto cluster = clusterList.findInAll("some cluster"); cluster->modulation.reset(1, 8760); cluster->ecoInput.loadFromFolder(*study, folder); - fillThermalEconomicTimeSeries(cluster.get()); + fillThermalEconomicTimeSeries(cluster); cluster->ComputeCostTimeSeries(); @@ -242,7 +261,7 @@ BOOST_FIXTURE_TEST_CASE(ThermalCluster_costGenTimeSeriesCalculationOfMarketBidAn BOOST_FIXTURE_TEST_CASE(computeMarketBidCost, FixtureFull) { clusterList.loadFromFolder(*study, folder, area); - auto cluster = clusterList.mapping["some cluster"]; + auto cluster = clusterList.findInAll("some cluster"); BOOST_CHECK_CLOSE(cluster->computeMarketBidCost(1, 2, 1), 24.12, 0.001); } diff --git a/src/tests/src/libs/antares/test_utils.cpp b/src/tests/src/libs/antares/test_utils.cpp index a4cb101c9e..5cb05e27c4 100644 --- a/src/tests/src/libs/antares/test_utils.cpp +++ b/src/tests/src/libs/antares/test_utils.cpp @@ -1,15 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE test utils -#define BOOST_TEST_DYN_LINK +#include +#include + #include -#include +#include + #include +namespace fs = std::filesystem; -namespace { +namespace +{ -template -T beautify(const T& in) { +template +T beautify(const T& in) +{ T out; Antares::BeautifyName(out, in); return out; @@ -18,13 +44,15 @@ T beautify(const T& in) { constexpr auto beautifyStd = beautify; constexpr auto beautifyYuni = beautify; -} +} // namespace + +BOOST_AUTO_TEST_SUITE(utils) BOOST_AUTO_TEST_CASE(test_beautify_name_std) { - //Just checking that both std and yuni strings have similar behaviours with UTF8 chars... + // Just checking that both std and yuni strings have similar behaviours with UTF8 chars... BOOST_TEST(std::string("tÿst").size() == 5); - BOOST_TEST(Yuni::String ("tÿst").size() == 5); + BOOST_TEST(Yuni::String("tÿst").size() == 5); BOOST_TEST(beautifyStd("test") == "test"); BOOST_TEST(beautifyStd("tést") == "t st"); @@ -47,3 +75,35 @@ BOOST_AUTO_TEST_CASE(test_string_conversion) Yuni::String yuniConvertedBack = stdStr; BOOST_TEST(yuniConvertedBack == "hello"); } + +BOOST_AUTO_TEST_CASE(test_transform_name_into_id) +{ + BOOST_CHECK(Antares::transformNameIntoID("NA!ME") == "na me"); + BOOST_CHECK(Antares::transformNameIntoID("name!") == "name"); + BOOST_CHECK(Antares::transformNameIntoID("!name") == "name"); +} + +BOOST_AUTO_TEST_CASE(yuni_absolute_vs_std_absolute) +{ + fs::path pathToFile("abc.txt"); + + Yuni::String yuniAbs; + Yuni::IO::MakeAbsolute(yuniAbs, pathToFile.string()); + + BOOST_CHECK(fs::absolute(pathToFile).string() == yuniAbs); +} + +BOOST_AUTO_TEST_CASE(yuni_normalize_vs_std_lexically_normal) +{ + const auto helper = [](fs::path&& path) + { + Yuni::String yuniNorm; + Yuni::IO::Normalize(yuniNorm, path.string()); + BOOST_CHECK_MESSAGE(path.lexically_normal().string() == yuniNorm, + std::string("Check failed for ") + path.string()); + }; + helper(fs::path("a/./b/..")); + helper(fs::path("a/.///b/../")); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/writer/CMakeLists.txt b/src/tests/src/libs/antares/writer/CMakeLists.txt index 5d0e479419..b85bcce05c 100644 --- a/src/tests/src/libs/antares/writer/CMakeLists.txt +++ b/src/tests/src/libs/antares/writer/CMakeLists.txt @@ -1,13 +1,15 @@ -add_executable(test-writer) - -target_sources(test-writer PRIVATE test_zip_writer.cpp) +# Zip writer +add_executable(test-writer test_writer.cpp) target_link_libraries(test-writer - PRIVATE - Boost::unit_test_framework - Antares::result_writer - test_utils_unit - MINIZIP::minizip + PRIVATE + Boost::unit_test_framework + Antares::result_writer + test_utils_unit + MINIZIP::minizip ) +set_target_properties(test-writer PROPERTIES FOLDER Unit-tests/test-writer) + add_test(NAME writer COMMAND test-writer) +set_tests_properties(writer PROPERTIES LABELS unit) diff --git a/src/tests/src/libs/antares/writer/test_writer.cpp b/src/tests/src/libs/antares/writer/test_writer.cpp new file mode 100644 index 0000000000..e3af61cc44 --- /dev/null +++ b/src/tests/src/libs/antares/writer/test_writer.cpp @@ -0,0 +1,188 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test - writer tests +#include +#include + +#include "yuni/job/queue/service.h" + +#include "antares/benchmarking/DurationCollector.h" +#include "antares/writer/i_writer.h" +#include "antares/writer/in_memory_writer.h" +#include "antares/writer/writer_factory.h" + +#include "files-system.h" + +extern "C" +{ +#include +#include +#include +#include +} + +using namespace Yuni::Job; +using Antares::Solver::IResultWriter; +using Benchmarking::DurationCollector; + +// Handles lifetime of necessary objects +struct TestContext +{ + std::shared_ptr threadPool; + std::unique_ptr durationCollector; + std::shared_ptr writer; +}; + +std::shared_ptr createThreadPool(int size) +{ + auto threadPool = std::make_shared(); + threadPool->maximumThreadCount(size); + threadPool->start(); + return threadPool; +} + +std::string removeExtension(const std::string& name, const std::string& ext) +{ + int length = name.size(); + if (name.size() > ext.size() && name.substr(length - ext.size()) == ext) + { + return name.substr(0, length - ext.size()); + } + return name; +} + +TestContext createContext(const std::filesystem::path zipPath, + int threadCount, + Antares::Data::ResultFormat fmt) +{ + auto threadPool = createThreadPool(threadCount); + std::unique_ptr + durationCollector = std::make_unique(); + std::string archiveName = zipPath.string(); + auto writer = Antares::Solver::resultWriterFactory(fmt, + removeExtension(zipPath.string(), ".zip"), + threadPool, + *durationCollector); + return {threadPool, std::move(durationCollector), writer}; +} + +using ZipReaderHandle = void*; + +BOOST_AUTO_TEST_SUITE(writer) + +void checkZipContent(ZipReaderHandle handle, + const std::string& path, + const std::string& expectedContent) +{ + BOOST_CHECK(mz_zip_reader_locate_entry(handle, path.c_str(), 0) == MZ_OK); + BOOST_CHECK(mz_zip_reader_entry_open(handle) == MZ_OK); + char buffer[4096]; + int bytesRead = mz_zip_reader_entry_read(handle, buffer, sizeof(buffer)); + std::string stringRead(buffer, bytesRead); + BOOST_CHECK(stringRead == expectedContent); + mz_zip_reader_entry_close(handle); +} + +BOOST_AUTO_TEST_CASE(test_zip) +{ + // Writer some content to test.zip, possibly from 2 threads + auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); + auto zipPath = working_tmp_dir / "test.zip"; + auto context = createContext(zipPath, 2, Antares::Data::zipArchive); + std::string content1 = "test-content1"; + std::string content2 = "test-content2"; + context.writer->addEntryFromBuffer("test-path", content1); + context.writer->addEntryFromBuffer("test-second-path", content2); + context.writer->flush(); + context.writer->finalize(true); + + // Check content is correct + ZipReaderHandle readerHandle = mz_zip_reader_create(); + std::string zipPathStr = zipPath.string(); + BOOST_CHECK(mz_zip_reader_open_file(readerHandle, zipPathStr.c_str()) == MZ_OK); + checkZipContent(readerHandle, "test-path", "test-content1"); + checkZipContent(readerHandle, "test-second-path", "test-content2"); + mz_zip_reader_close(readerHandle); +} + +BOOST_AUTO_TEST_CASE(test_in_memory_concrete) +{ + // Writer some content to test.zip, possibly from 2 threads + std::string content1 = "test-content1"; + std::string content2 = "test-content2"; + + Benchmarking::DurationCollector durationCollector; + Antares::Solver::InMemoryWriter writer(durationCollector); + + writer.addEntryFromBuffer("folder/test", content1); + writer.addEntryFromBuffer("test-second-path", content2); + writer.flush(); + writer.finalize(true); + + const auto& map = writer.getMap(); + BOOST_CHECK(map.at("folder/test") == content1); + BOOST_CHECK(map.at("test-second-path") == content2); +} + +BOOST_AUTO_TEST_CASE(test_in_memory_dyncast) +{ + // Writer some content to test.zip, possibly from 2 threads + + auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); + auto zipPath = working_tmp_dir / "test.zip"; + auto context = createContext(zipPath /* unused */, 1 /* unused */, Antares::Data::inMemory); + + std::string content1 = "test-content1"; + std::string content2 = "test-content2"; + context.writer->addEntryFromBuffer("folder/test", content1); + context.writer->addEntryFromBuffer("test-second-path", content2); + context.writer->flush(); + context.writer->finalize(true); + + auto writer = std::dynamic_pointer_cast(context.writer); + BOOST_CHECK(writer != nullptr); + + const auto& map = writer->getMap(); + BOOST_CHECK(map.at("folder/test") == content1); + BOOST_CHECK(map.at("test-second-path") == content2); +} + +BOOST_AUTO_TEST_CASE(test_in_memory_sanitize_antislash) +{ + // Writer some content to test.zip, possibly from 2 threads + + auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); + auto zipPath = working_tmp_dir / "test.zip"; + auto context = createContext(zipPath /* unused */, 1 /* unused */, Antares::Data::inMemory); + + std::string content1 = "test-content1"; + context.writer->addEntryFromBuffer("folder\\test", content1); + context.writer->flush(); + context.writer->finalize(true); + + auto writer = std::dynamic_pointer_cast(context.writer); + BOOST_CHECK(writer != nullptr); + + const auto& map = writer->getMap(); + BOOST_CHECK(map.at("folder/test") == content1); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/libs/antares/writer/test_zip_writer.cpp b/src/tests/src/libs/antares/writer/test_zip_writer.cpp deleted file mode 100644 index 474b7c6c4a..0000000000 --- a/src/tests/src/libs/antares/writer/test_zip_writer.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#define BOOST_TEST_MODULE test-writer tests -#define BOOST_TEST_DYN_LINK -#include -#include - -#include "yuni/job/queue/service.h" -#include "antares/writer/i_writer.h" -#include "antares/writer/writer_factory.h" -#include "antares/benchmarking/DurationCollector.h" -#include "utils.h" - -extern "C" -{ -#include -#include -#include -#include -} - -using namespace Yuni::Job; -using Benchmarking::NullDurationCollector; -using Benchmarking::IDurationCollector; -using Antares::Solver::IResultWriter; - -// Handles lifetime of necessary objects -struct TestContext -{ - std::shared_ptr threadPool; - std::unique_ptr durationCollector; - std::shared_ptr writer; -}; - -std::shared_ptr createThreadPool(int size) -{ - auto threadPool = std::make_shared(); - threadPool->maximumThreadCount(size); - threadPool->start(); - return threadPool; -} - -std::string removeExtension(const std::string& name, const std::string& ext) -{ - int length = name.size(); - if (name.size() > ext.size() && name.substr(length - ext.size()) == ext) { - return name.substr(0, length - ext.size()); - } - return name; -} - - -TestContext createContext(const std::filesystem::path zipPath, int threadCount) -{ - auto threadPool = createThreadPool(threadCount); - std::unique_ptr durationCollector = std::make_unique(); - std::string archiveName = zipPath.string(); - auto writer = Antares::Solver::resultWriterFactory( - Antares::Data::zipArchive, - removeExtension(zipPath.string(), ".zip"), - threadPool, - *durationCollector - ); - return { - threadPool, - std::move(durationCollector), - writer - }; -} - -using ZipReaderHandle = void*; - -void checkZipContent(ZipReaderHandle handle, const std::string& path, const std::string& expectedContent) -{ - BOOST_CHECK(mz_zip_reader_locate_entry(handle, path.c_str(), 0) == MZ_OK); - BOOST_CHECK(mz_zip_reader_entry_open(handle) == MZ_OK); - char buffer[4096]; - int bytesRead = mz_zip_reader_entry_read(handle, buffer, sizeof(buffer)); - std::string stringRead(buffer, bytesRead); - BOOST_CHECK(stringRead == expectedContent); - mz_zip_reader_entry_close(handle); -} - -BOOST_AUTO_TEST_CASE(test_zip) -{ - // Writer some content to test.zip, possibly from 2 threads - auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); - auto zipPath = working_tmp_dir / "test.zip"; - auto context = createContext(zipPath, 2); - std::string content1 = "test-content1"; - std::string content2 = "test-content2"; - context.writer->addEntryFromBuffer("test-path", content1); - context.writer->addEntryFromBuffer("test-second-path", content2); - context.writer->flush(); - context.writer->finalize(true); - - // Check content is correct - ZipReaderHandle readerHandle; - mz_zip_reader_create(&readerHandle); - std::string zipPathStr = zipPath.string(); - BOOST_CHECK(mz_zip_reader_open_file(readerHandle, zipPathStr.c_str()) == MZ_OK); - checkZipContent(readerHandle, "test-path", "test-content1"); - checkZipContent(readerHandle, "test-second-path", "test-content2"); - mz_zip_reader_close(readerHandle); -} diff --git a/src/tests/src/libs/antares/yaml-parser/CMakeLists.txt b/src/tests/src/libs/antares/yaml-parser/CMakeLists.txt new file mode 100644 index 0000000000..1633966826 --- /dev/null +++ b/src/tests/src/libs/antares/yaml-parser/CMakeLists.txt @@ -0,0 +1,17 @@ + +find_package(yaml-cpp CONFIG REQUIRED) +Set(SRCS test_yaml_parser.cpp +) + +set(execname "yaml-parser-test") +add_executable(${execname} ${SRCS}) +target_link_libraries(${execname} + PRIVATE + yaml-cpp + Boost::unit_test_framework + ) + + +add_test(NAME yaml-parser COMMAND ${execname}) + +set_tests_properties(yaml-parser PROPERTIES LABELS unit) diff --git a/src/tests/src/libs/antares/yaml-parser/test_yaml_parser.cpp b/src/tests/src/libs/antares/yaml-parser/test_yaml_parser.cpp new file mode 100644 index 0000000000..87978fbcaa --- /dev/null +++ b/src/tests/src/libs/antares/yaml-parser/test_yaml_parser.cpp @@ -0,0 +1,167 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#define BOOST_TEST_MODULE yamlcpp tests +#include +#include +#include +#include + +#include +#include + +#include "yaml-cpp/yaml.h" + +// our data types +struct Vec3 +{ + float x, y, z; +}; + +struct Power +{ + std::string name; + int damage; +}; + +struct Monster +{ + std::string name; + Vec3 position; + std::vector powers; +}; + +namespace YAML +{ +template<> +struct convert +{ + static Node encode(const Vec3& rhs) + { + Node node; + node.push_back(rhs.x); + node.push_back(rhs.y); + node.push_back(rhs.z); + return node; + } + + static bool decode(const Node& node, Vec3& rhs) + { + if (!node.IsSequence() || node.size() != 3) + { + return false; + } + + rhs.x = node[0].as(); + rhs.y = node[1].as(); + rhs.z = node[2].as(); + return true; + } +}; + +template<> +struct convert +{ + static Node encode(const Power& rhs) + { + Node node; + node["name"] = rhs.name; + node["damage"] = rhs.damage; + return node; + } + + static bool decode(const Node& node, Power& rhs) + { + rhs.name = node["name"].as(); + rhs.damage = node["damage"].as(); + return true; + } +}; + +template<> +struct convert +{ + static Node encode(const Monster& rhs) + { + Node node; + node["name"] = rhs.name; + // node["position"] = node["position"].as(); + node["position"] = rhs.position; + node["powers"] = rhs.powers; + + return node; + } + + static bool decode(const Node& node, Monster& rhs) + { + rhs.name = node["name"].as(); + rhs.position = node["position"].as(); + const YAML::Node& powers = node["powers"]; + for (const auto power: powers) + { + rhs.powers.push_back(power.as()); + } + return true; + } +}; +} // namespace YAML + +BOOST_AUTO_TEST_CASE(test_yaml_parser) +{ + std::string my_yaml = R"(- name: Ogre + position: [0, 5, 0] + powers: + - name: Club + damage: 10 + - name: Fist + damage: 8 +- name: Dragon + position: [1, 0, 10] + powers: + - name: Fire Breath + damage: 25 + - name: Claws + damage: 15 +- name: Wizard + position: [5, -3, 0] + powers: + - name: Acid Rain + damage: 50 + - name: Staff + damage: 3)"; + + YAML::Node doc = YAML::Load(my_yaml); + std::vector monsters; + for (unsigned i = 0; i < doc.size(); i++) + { + monsters.push_back(doc[i].as()); + } + BOOST_CHECK(monsters.size() == 3); + auto ogre = monsters[0]; + BOOST_CHECK(ogre.name == "Ogre"); + BOOST_CHECK(ogre.position.x == 0); + BOOST_CHECK(ogre.position.y == 5); + BOOST_CHECK(ogre.position.z == 0); + auto ogre_powers = ogre.powers; + BOOST_CHECK(ogre_powers.size() == 2); + auto ogre_power_Club = ogre_powers[0]; + BOOST_CHECK(ogre_power_Club.name == "Club"); + BOOST_CHECK(ogre_power_Club.damage == 10); +} diff --git a/src/tests/src/solver/CMakeLists.txt b/src/tests/src/solver/CMakeLists.txt index cd2c028bf1..e301a13a77 100644 --- a/src/tests/src/solver/CMakeLists.txt +++ b/src/tests/src/solver/CMakeLists.txt @@ -1,3 +1,6 @@ add_subdirectory(simulation) add_subdirectory(optimisation) +add_subdirectory(utils) +add_subdirectory(infeasible-problem-analysis) +add_subdirectory(lps) diff --git a/src/tests/src/solver/infeasible-problem-analysis/CMakeLists.txt b/src/tests/src/solver/infeasible-problem-analysis/CMakeLists.txt new file mode 100644 index 0000000000..8a8a0e9544 --- /dev/null +++ b/src/tests/src/solver/infeasible-problem-analysis/CMakeLists.txt @@ -0,0 +1,16 @@ +add_executable(test-unfeasible-problem-analyzer) +target_sources(test-unfeasible-problem-analyzer + PRIVATE + test-unfeasible-problem-analyzer.cpp) +target_link_libraries(test-unfeasible-problem-analyzer + PRIVATE + Boost::unit_test_framework + infeasible_problem_analysis + ortools::ortools +) + +add_test(NAME test-unfeasible-problem-analyzer COMMAND test-unfeasible-problem-analyzer) + +# Storing the executable under the folder Unit-tests in Visual Studio +set_target_properties(test-unfeasible-problem-analyzer PROPERTIES FOLDER Unit-tests) +set_property(TEST test-unfeasible-problem-analyzer PROPERTY LABELS unit) diff --git a/src/tests/src/solver/infeasible-problem-analysis/test-unfeasible-problem-analyzer.cpp b/src/tests/src/solver/infeasible-problem-analysis/test-unfeasible-problem-analyzer.cpp new file mode 100644 index 0000000000..321bd4b3e7 --- /dev/null +++ b/src/tests/src/solver/infeasible-problem-analysis/test-unfeasible-problem-analyzer.cpp @@ -0,0 +1,215 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define WIN32_LEAN_AND_MEAN +#define BOOST_TEST_MODULE unfeasible_problem_analyzer + +#include + +#include +#include +#include + +#include "antares/solver/infeasible-problem-analysis/constraint-slack-analysis.h" +#include "antares/solver/infeasible-problem-analysis/unfeasible-pb-analyzer.h" +#include "antares/solver/infeasible-problem-analysis/variables-bounds-consistency.h" + +namespace bdata = boost::unit_test::data; + +using namespace operations_research; + +using Antares::Optimization::ConstraintSlackAnalysis; +using Antares::Optimization::UnfeasibilityAnalysis; +using Antares::Optimization::UnfeasiblePbAnalyzer; +using Antares::Optimization::VariableBounds; +using Antares::Optimization::VariablesBoundsConsistency; + +bool variableEquals(const VariableBounds& lhs, const VariableBounds& rhs) +{ + return lhs.name == rhs.name && lhs.lowBound == rhs.lowBound && lhs.upBound == rhs.upBound; +} + +/*! + * Analysis mock, used to assess which step has been run by the analyzer + */ +class AnalysisMock: public UnfeasibilityAnalysis +{ +public: + AnalysisMock(bool shouldDetectCause, bool& hasRun, bool& hasPrinted): + shouldDetectCause_(shouldDetectCause), + hasRun_(hasRun), + hasPrinted_(hasPrinted) + { + } + + ~AnalysisMock() override = default; + + void run(operations_research::MPSolver*) override + { + hasRun_ = true; + hasDetectedInfeasibilityCause_ = shouldDetectCause_; + } + + void printReport() const override + { + hasPrinted_ = true; + } + + std::string title() const override + { + return "mock"; + } + +private: + bool shouldDetectCause_; + bool& hasRun_; + bool& hasPrinted_; +}; + +BOOST_AUTO_TEST_SUITE(unfeasible_problem_analyzer) + +BOOST_AUTO_TEST_CASE(analyzer_should_call_analysis_and_print_detected_issues) +{ + bool hasRun1 = false; + bool hasPrinted1 = false; + bool hasRun2 = false; + bool hasPrinted2 = false; + // Vector is moved, iterators are invalidated. Can't hold references to element to get values. + std::vector> analysis; + analysis.push_back(std::make_unique(false, hasRun1, hasPrinted1)); + analysis.push_back(std::make_unique(true, hasRun2, hasPrinted2)); + std::unique_ptr problem(MPSolver::CreateSolver("GLOP")); + + UnfeasiblePbAnalyzer analyzer(std::move(analysis)); + BOOST_CHECK(!hasRun1); + BOOST_CHECK(!hasPrinted1); + BOOST_CHECK(!hasRun2); + BOOST_CHECK(!hasPrinted2); + + analyzer.run(problem.get()); + BOOST_CHECK(hasRun1); + BOOST_CHECK(!hasPrinted1); + BOOST_CHECK(hasRun2); + BOOST_CHECK(!hasPrinted2); + + // only failing analysis will print + analyzer.printReport(); + BOOST_CHECK(hasRun1); + BOOST_CHECK(!hasPrinted1); + BOOST_CHECK(hasRun2); + BOOST_CHECK(hasPrinted2); +} + +BOOST_AUTO_TEST_CASE(analysis_should_detect_inconsistent_variable_bounds) +{ + std::unique_ptr problem(MPSolver::CreateSolver("GLOP")); + problem->MakeNumVar(-1, 1, "ok-var"); + problem->MakeNumVar(1, -1, "not-ok-var"); + + VariablesBoundsConsistency analysis; + analysis.run(problem.get()); + auto incorrectVars = analysis.incorrectVars(); + BOOST_CHECK_EQUAL(incorrectVars.size(), 1); + + auto expected = VariableBounds("not-ok-var", 1, -1); + BOOST_CHECK(variableEquals(incorrectVars[0], expected)); +} + +/*! + * Creates a problem with 2 variables linked by 1 constraint: + * - Variable 1 must be greater than 1 + * - Variable 2 must be lesser than -1 + * - but if feasible is false, constraint enforces that variable 2 is greater than variable 1 --> + * infeasible + */ +std::unique_ptr createProblem(const std::string& constraintName, bool feasible) +{ + std::unique_ptr problem(MPSolver::CreateSolver("GLOP")); + const double infinity = problem->infinity(); + auto var1 = problem->MakeNumVar(1, infinity, "var1"); + auto var2 = problem->MakeNumVar(-infinity, -1, "var2"); + auto constraint = problem->MakeRowConstraint(constraintName); + constraint->SetBounds(0, infinity); + if (feasible) + { + constraint->SetCoefficient(var1, 1); + constraint->SetCoefficient(var2, -1); + } + else + { + constraint->SetCoefficient(var1, -1); + constraint->SetCoefficient(var2, 1); + } + return problem; +} + +std::unique_ptr createFeasibleProblem(const std::string& constraintName) +{ + return createProblem(constraintName, true); +} + +std::unique_ptr createUnfeasibleProblem(const std::string& constraintName) +{ + return createProblem(constraintName, false); +} + +static const std::string validConstraintNames[] = { + "BC::hourly::hour<36>", + "BC::daily::day<67>", + "BC::weekly::week<12>", + "FictiveLoads::hour<25>", + "AreaHydroLevel::hour<8>", +}; + +BOOST_DATA_TEST_CASE(analysis_should_detect_unfeasible_constraint, + bdata::make(validConstraintNames), + constraintName) +{ + std::unique_ptr unfeasibleProblem = createUnfeasibleProblem(constraintName); + BOOST_CHECK(unfeasibleProblem->Solve() == MPSolver::INFEASIBLE); + + ConstraintSlackAnalysis analysis; + analysis.run(unfeasibleProblem.get()); + BOOST_CHECK(analysis.hasDetectedInfeasibilityCause()); +} + +BOOST_AUTO_TEST_CASE(analysis_should_ignore_ill_named_constraint) +{ + std::unique_ptr unfeasibleProblem = createUnfeasibleProblem("ignored-name"); + BOOST_CHECK(unfeasibleProblem->Solve() == MPSolver::INFEASIBLE); + + ConstraintSlackAnalysis analysis; + analysis.run(unfeasibleProblem.get()); + BOOST_CHECK(!analysis.hasDetectedInfeasibilityCause()); +} + +// TODO: this test should be improved by changing the API, the current interface does not allow +// to check that no constraint was identified... +BOOST_AUTO_TEST_CASE(analysis_should_ignore_feasible_constraints) +{ + std::unique_ptr feasibleProblem = createFeasibleProblem("BC::hourly::hour<36>"); + BOOST_CHECK(feasibleProblem->Solve() == MPSolver::OPTIMAL); + + ConstraintSlackAnalysis analysis; + analysis.run(feasibleProblem.get()); + BOOST_CHECK(analysis.hasDetectedInfeasibilityCause()); // Would expect false here instead? +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/solver/lps/CMakeLists.txt b/src/tests/src/solver/lps/CMakeLists.txt new file mode 100644 index 0000000000..89121152ba --- /dev/null +++ b/src/tests/src/solver/lps/CMakeLists.txt @@ -0,0 +1,20 @@ +set(EXECUTABLE_NAME test-lps) +add_executable(${EXECUTABLE_NAME}) + +target_sources(${EXECUTABLE_NAME} + PRIVATE + test_lps.cpp +) + +target_link_libraries(${EXECUTABLE_NAME} + PRIVATE + Boost::unit_test_framework + antares-solver-simulation +) + +# Storing tests-ts-numbers under the folder Unit-tests in the IDE +set_target_properties(${EXECUTABLE_NAME} PROPERTIES FOLDER Unit-tests) + +add_test(NAME test-lps COMMAND ${EXECUTABLE_NAME}) + +set_property(TEST test-lps PROPERTY LABELS unit) diff --git a/src/tests/src/solver/lps/test_lps.cpp b/src/tests/src/solver/lps/test_lps.cpp new file mode 100644 index 0000000000..3a0bf4aa34 --- /dev/null +++ b/src/tests/src/solver/lps/test_lps.cpp @@ -0,0 +1,77 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test_translator +#define WIN32_LEAN_AND_MEAN + +#include + +#include + +using namespace Antares::Solver; + +BOOST_AUTO_TEST_CASE(new_lps_is_empty) +{ + LpsFromAntares lps; + BOOST_CHECK(lps.empty()); +} + +BOOST_AUTO_TEST_CASE(lps_with_only_constant_data_is_empty) +{ + LpsFromAntares lps; + lps.setConstantData(ConstantDataFromAntares()); + BOOST_CHECK(lps.empty()); +} + +BOOST_AUTO_TEST_CASE(lps_with_no_variabled_is_empty) +{ + LpsFromAntares lps; + lps.constantProblemData.VariablesCount = 0; + lps.addWeeklyData({0, 0}, WeeklyDataFromAntares()); + BOOST_CHECK(lps.empty()); +} + +BOOST_AUTO_TEST_CASE(lps_with_both_constant_and_weekly_data_is_not_empty) +{ + LpsFromAntares lps; + lps.constantProblemData.VariablesCount = 65; + lps.addWeeklyData({0, 0}, WeeklyDataFromAntares()); + BOOST_CHECK(!lps.empty()); +} + +BOOST_AUTO_TEST_CASE(replace_const_data) +{ + LpsFromAntares lps; + ConstantDataFromAntares var; + var.VariablesCount = 42; + lps.setConstantData(var); + BOOST_CHECK(lps.constantProblemData.VariablesCount == 42); +} + +// Add weekly data for week 1 year 1 +BOOST_AUTO_TEST_CASE(add_weekly_data_for_week_1_year_1) +{ + LpsFromAntares lps; + WeeklyDataFromAntares w; + w.RHS.push_back(43); + lps.addWeeklyData({1, 1}, w); + BOOST_CHECK(lps.weeklyData({1, 1}).RHS.size() != WeeklyDataFromAntares().RHS.size()); +} diff --git a/src/tests/src/solver/optimisation/CMakeLists.txt b/src/tests/src/solver/optimisation/CMakeLists.txt index 72d92448a3..d3b9a9a82e 100644 --- a/src/tests/src/solver/optimisation/CMakeLists.txt +++ b/src/tests/src/solver/optimisation/CMakeLists.txt @@ -1,24 +1,2 @@ -# Useful variables definitions -set(src_solver_optimisation "${CMAKE_SOURCE_DIR}/solver/optimisation") - -set(EXECUTABLE_NAME tests-adq-patch) -add_executable(${EXECUTABLE_NAME} adequacy_patch.cpp) - -target_include_directories(${EXECUTABLE_NAME} - PRIVATE - "${src_solver_optimisation}" -) - -target_link_libraries(${EXECUTABLE_NAME} - PRIVATE - Boost::unit_test_framework - model_antares - array -) - -# Storing tests-ts-numbers under the folder Unit-tests in the IDE -set_target_properties(${EXECUTABLE_NAME} PROPERTIES FOLDER Unit-tests) - -add_test(NAME test-adq-patch COMMAND ${EXECUTABLE_NAME}) - -set_property(TEST test-adq-patch PROPERTY LABELS unit) +add_subdirectory(adequacy_patch) +add_subdirectory(translator) \ No newline at end of file diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp deleted file mode 100644 index 2c6c0a5a4d..0000000000 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ /dev/null @@ -1,513 +0,0 @@ -#define BOOST_TEST_MODULE test adequacy patch functions -#define BOOST_TEST_DYN_LINK - -#define WIN32_LEAN_AND_MEAN - -#include - -#include "adequacy_patch_local_matching/adq_patch_local_matching.h" -#include "adequacy_patch_csr/adq_patch_curtailment_sharing.h" -#include -#include "antares/study/parameters/adq-patch-params.h" -#include -#include - -#include -#include - -static double origineExtremite = -1; -static double extremiteOrigine = 5; - -using namespace Antares::Data::AdequacyPatch; - -// NOTE -// Xmax limits the flux origin -> extremity (direct) -// -Xmin limits the flux extremity -> origin (indirect) - -std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originType, - AdequacyPatchMode extremityType, - bool SetNTCOutsideToOutsideToZero, - bool SetNTCOutsideToInsideToZero) -{ - PROBLEME_HEBDO problem; - problem.adequacyPatchRuntimeData = std::make_shared(); - problem.adequacyPatchRuntimeData->originAreaMode.resize(1); - problem.adequacyPatchRuntimeData->extremityAreaMode.resize(1); - - problem.adequacyPatchRuntimeData->originAreaMode[0] = originType; - problem.adequacyPatchRuntimeData->extremityAreaMode[0] = extremityType; - problem.adequacyPatchRuntimeData->AdequacyFirstStep = true; - - AdqPatchParams adqPatchParams; - adqPatchParams.enabled = true; - adqPatchParams.localMatching.setToZeroOutsideOutsideLinks = SetNTCOutsideToOutsideToZero; - adqPatchParams.localMatching.setToZeroOutsideInsideLinks = SetNTCOutsideToInsideToZero; - - VALEURS_DE_NTC_ET_RESISTANCES ValeursDeNTC; - ValeursDeNTC.ValeurDeNTCOrigineVersExtremite.assign(1, 0.); - ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine.assign(1, 0.); - ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[0] = origineExtremite; - ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[0] = extremiteOrigine; - - double Xmin(0.); - double Xmax(0.); - - setNTCbounds(Xmax, Xmin, ValeursDeNTC, 0, &problem, adqPatchParams); - - return std::make_pair(Xmin, Xmax); -} - -static const double flowArea0toArea1_positive = 10; -static const double flowArea0toArea1_negative = -10; -static const double flowArea2toArea0_positive = 30; -static const double flowArea2toArea0_negative = -30; -static const double positiveEnsInit = 50.0; - -std::pair calculateAreaFlowBalanceForOneTimeStep( - double ensInit, - bool includeFlowsOutsideAdqPatchToDensNew, - AdequacyPatchMode Area1Mode, - AdequacyPatchMode Area2Mode, - double flowToArea1, - double flowFromArea2) -{ - PROBLEME_HEBDO problem; - int Area = 0; - uint hour = 0; - - // allocate memory - problem.adequacyPatchRuntimeData = std::make_shared(); - problem.adequacyPatchRuntimeData->originAreaMode.resize(3); - problem.adequacyPatchRuntimeData->extremityAreaMode.resize(3); - - AdqPatchParams adqPatchParams; - - problem.ResultatsHoraires.resize(1); - problem.ResultatsHoraires[0].ValeursHorairesDeDefaillancePositive = std::vector(1); - problem.ValeursDeNTC = std::vector(1); - problem.ValeursDeNTC[0].ValeurDuFlux = std::vector(3); - problem.IndexSuivantIntercoOrigine = std::vector(3); - problem.IndexSuivantIntercoExtremite = std::vector(3); - problem.IndexDebutIntercoOrigine = std::vector(1); - problem.IndexDebutIntercoExtremite = std::vector(1); - - // input values - adqPatchParams.localMatching.setToZeroOutsideInsideLinks = !includeFlowsOutsideAdqPatchToDensNew; - problem.ResultatsHoraires[Area].ValeursHorairesDeDefaillancePositive[hour] = ensInit; - int Interco = 1; - problem.IndexDebutIntercoOrigine[Area] = Interco; - problem.adequacyPatchRuntimeData->extremityAreaMode[Interco] = Area1Mode; - problem.ValeursDeNTC[hour].ValeurDuFlux[Interco] = flowToArea1; - problem.IndexSuivantIntercoOrigine[Interco] = -1; - - Interco = 2; - problem.IndexDebutIntercoExtremite[Area] = Interco; - problem.adequacyPatchRuntimeData->originAreaMode[Interco] = Area2Mode; - problem.ValeursDeNTC[hour].ValeurDuFlux[Interco] = flowFromArea2; - problem.IndexSuivantIntercoExtremite[Interco] = -1; - - // get results - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew, std::ignore) - = calculateAreaFlowBalance(&problem, adqPatchParams.localMatching.setToZeroOutsideInsideLinks, Area, hour); - - return std::make_pair(netPositionInit, densNew); -} - -AdqPatchParams createParams() -{ - AdqPatchParams p; - p.enabled = true; - p.curtailmentSharing.includeHurdleCost = true; - p.localMatching.enabled = true; - p.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isDens; - - return p; -} - -// Virtual -> Virtual (0 -> 0) -// No change in bounds is expected -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_virtual_no_change_expected) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep( - virtualArea, virtualArea, true /*SetNTCOutsideToOutsideToZero*/, false); - BOOST_CHECK_EQUAL(Xmax, origineExtremite); - BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); -} - -// Virtual -> physical area inside adq-patch (0 -> 2) -// No change in bounds is expected -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_inside_no_change_expected) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep( - virtualArea, physicalAreaInsideAdqPatch, true /*SetNTCOutsideToOutsideToZero*/, false); - BOOST_CHECK_EQUAL(Xmax, origineExtremite); - BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); -} - -// Virtual -> physical area outside adq-patch (0 -> 1) -// No change in bounds is expected -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_outside_no_change_expected) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep( - virtualArea, physicalAreaOutsideAdqPatch, true /*SetNTCOutsideToOutsideToZero*/, false); - BOOST_CHECK_EQUAL(Xmax, origineExtremite); - BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); -} - -// physical area outside adq-patch -> physical area outside adq-patch (1 -> 1) -// NTC should be set to 0 in both directions -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_outside_zero_expected_both_directions) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaOutsideAdqPatch, - physicalAreaOutsideAdqPatch, - true /*SetNTCOutsideToOutsideToZero*/, - false); - BOOST_CHECK_EQUAL(Xmax, 0); - BOOST_CHECK_EQUAL(Xmin, 0); -} - -// physical area outside adq-patch -> physical area outside adq-patch (1 -> 1) -// SetNTCOutsideToOutsideToZero = true -// NTC should be set to 0 in both directions -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_outside_no_change_expected) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep( - physicalAreaOutsideAdqPatch, physicalAreaOutsideAdqPatch, false, false); - - BOOST_CHECK_EQUAL(Xmax, origineExtremite); - BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); -} - -// physical area inside adq-patch -> physical area outside adq-patch (2 -> 1) -// NTC should be set to 0 in both directions -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_inside_outside_zero_expected_both_directions) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep( - physicalAreaInsideAdqPatch, physicalAreaOutsideAdqPatch, false, false); - BOOST_CHECK_EQUAL(Xmax, 0); - BOOST_CHECK_EQUAL(Xmin, 0); -} - -// physical area outside adq-patch -> physical area inside adq-patch (1 -> 2) -// NTC should be set to 0 in both directions -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_zero_expected_both_directions) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaOutsideAdqPatch, - physicalAreaInsideAdqPatch, - false, - true /*SetNTCOutsideToInsideToZero*/); - BOOST_CHECK_EQUAL(Xmax, 0); - BOOST_CHECK_EQUAL(Xmin, 0); -} - -// physical area outside adq-patch -> physical area inside adq-patch (1 -> 2) -// NTC should be unchanged in direction origin->extremity (direct) -// NTC should be set to 0 in direction extremity->origin (indirect) -BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_change_expected_one_direction) -{ - double Xmin, Xmax; - std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep( - physicalAreaOutsideAdqPatch, physicalAreaInsideAdqPatch, false, false); - BOOST_CHECK_EQUAL(Xmax, origineExtremite); - BOOST_CHECK_EQUAL(Xmin, 0); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 virtual-area, and Area2-virtual area -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter should NOT include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE( - calculateAreaFlowBalanceForOneTimeStep_virtual_virtual_NotIncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( - 0.0, false, virtualArea, virtualArea, flowArea0toArea1_positive, flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, 0.0); - BOOST_CHECK_EQUAL(densNew, 0.0); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2-virtual area -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter should NOT include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE( - calculateAreaFlowBalanceForOneTimeStep_inside_virtual_NotIncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - false, - physicalAreaInsideAdqPatch, - virtualArea, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); - BOOST_CHECK_EQUAL(densNew, 0.0); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2-virtual area -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter should NOT include flows from areas outside adq patch -// ensInit = 50.0 -BOOST_AUTO_TEST_CASE( - calculateAreaFlowBalanceForOneTimeStep_inside_virtual_NotIncludeOut_positiveFlow_ensInitGraterThanZero) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(positiveEnsInit, - false, - physicalAreaInsideAdqPatch, - virtualArea, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); - BOOST_CHECK_EQUAL(densNew, positiveEnsInit - flowArea0toArea1_positive); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2 physical area outside adq-patch -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter should NOT include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE( - calculateAreaFlowBalanceForOneTimeStep_inside_outside_NotIncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - false, - physicalAreaInsideAdqPatch, - physicalAreaOutsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); - BOOST_CHECK_EQUAL(densNew, 0.0); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2 physical area inside adq-patch -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter should NOT include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE( - calculateAreaFlowBalanceForOneTimeStep_inside_inside_NotIncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - false, - physicalAreaInsideAdqPatch, - physicalAreaInsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive + flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_positive + flowArea2toArea0_positive); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2 physical area outside adq-patch -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter SHOULD include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_IncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - true, - physicalAreaInsideAdqPatch, - physicalAreaOutsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); - BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_positive + flowArea2toArea0_positive); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area outside adq-patch, and Area2 physical area outside adq-patch -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter SHOULD include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_IncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - true, - physicalAreaOutsideAdqPatch, - physicalAreaOutsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, 0.0); - BOOST_CHECK_EQUAL(densNew, flowArea2toArea0_positive); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area outside adq-patch, and Area2 physical area inside adq-patch -// flow from Area0 -> Area1 is positive -// flow from Area2 -> Area0 is positive -// DensNew parameter SHOULD include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_positiveFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - true, - physicalAreaOutsideAdqPatch, - physicalAreaInsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(netPositionInit, +flowArea2toArea0_positive); - BOOST_CHECK_EQUAL(densNew, +flowArea2toArea0_positive); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2 physical area outside adq-patch -// flow from Area0 -> Area1 is negative -// flow from Area2 -> Area0 is negative -// DensNew parameter SHOULD include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_IncludeOut_negativeFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - true, - physicalAreaInsideAdqPatch, - physicalAreaOutsideAdqPatch, - flowArea0toArea1_negative, - flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_negative); - BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_negative); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area outside adq-patch, and Area2 physical area outside adq-patch -// flow from Area0 -> Area1 is negative -// flow from Area2 -> Area0 is negative -// DensNew parameter SHOULD include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_IncludeOut_negativeFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - true, - physicalAreaOutsideAdqPatch, - physicalAreaOutsideAdqPatch, - flowArea0toArea1_negative, - flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(netPositionInit, 0.0); - BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_negative); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area outside adq-patch, and Area2 physical area inside adq-patch -// flow from Area0 -> Area1 is negative -// flow from Area2 -> Area0 is negative -// DensNew parameter SHOULD include flows from areas outside adq patch -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(0.0, - true, - physicalAreaOutsideAdqPatch, - physicalAreaInsideAdqPatch, - flowArea0toArea1_negative, - flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(netPositionInit, flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(densNew, 0.0); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2 physical area inside adq-patch -// flow from Area0 -> Area1 is positiive -// flow from Area2 -> Area0 is negative -// DensNew parameter SHOULD include flows from areas outside adq patch -// ensInit = 50.0 -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow_initEnsEqualTo50) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(positiveEnsInit, - true, - physicalAreaInsideAdqPatch, - physicalAreaInsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive + flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(densNew, positiveEnsInit + netPositionInit); -} - -// Area 0 is physical area inside adq-patch connected to two areas: -// Area1 physical area inside adq-patch, and Area2 physical area inside adq-patch -// flow from Area0 -> Area1 is positiive -// flow from Area2 -> Area0 is negative -// DensNew parameter SHOULD include flows from areas outside adq patch -// ensInit = 2.0 -BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow_initEnsEqualTo0) -{ - double netPositionInit; - double densNew; - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(2.0, - true, - physicalAreaInsideAdqPatch, - physicalAreaInsideAdqPatch, - flowArea0toArea1_positive, - flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive + flowArea2toArea0_negative); - BOOST_CHECK_EQUAL(densNew, 0.0); -} - -BOOST_AUTO_TEST_CASE(check_valid_adq_param) -{ - auto p = createParams(); - BOOST_CHECK_NO_THROW(p.checkAdqPatchStudyModeEconomyOnly(Antares::Data::stdmEconomy)); - BOOST_CHECK_NO_THROW(p.checkAdqPatchIncludeHurdleCost(true)); - BOOST_CHECK_NO_THROW(p.checkAdqPatchDisabledLocalMatching()); -} - -BOOST_AUTO_TEST_CASE(check_adq_param_wrong_mode) -{ - auto p = createParams(); - BOOST_CHECK_THROW(p.checkAdqPatchStudyModeEconomyOnly(Antares::Data::stdmAdequacy), - Error::IncompatibleStudyModeForAdqPatch); -} - -BOOST_AUTO_TEST_CASE(check_adq_param_wrong_hurdle_cost) -{ - auto p = createParams(); - BOOST_CHECK_THROW(p.checkAdqPatchIncludeHurdleCost(false), Error::IncompatibleHurdleCostCSR); -} - -BOOST_AUTO_TEST_CASE(check_adq_param_wrong_lmr_disabled) -{ - auto p = createParams(); - p.localMatching.enabled = false; - BOOST_CHECK_THROW(p.checkAdqPatchDisabledLocalMatching(), Error::AdqPatchDisabledLMR); -} diff --git a/src/tests/src/solver/optimisation/adequacy_patch/CMakeLists.txt b/src/tests/src/solver/optimisation/adequacy_patch/CMakeLists.txt new file mode 100644 index 0000000000..bb28a99864 --- /dev/null +++ b/src/tests/src/solver/optimisation/adequacy_patch/CMakeLists.txt @@ -0,0 +1,24 @@ +# Useful variables definitions +set(src_solver_optimisation "${CMAKE_SOURCE_DIR}/solver/optimisation") + +set(EXECUTABLE_NAME tests-adq-patch) +add_executable(${EXECUTABLE_NAME} adequacy_patch.cpp) + +target_include_directories(${EXECUTABLE_NAME} + PRIVATE + "${src_solver_optimisation}" +) + +target_link_libraries(${EXECUTABLE_NAME} + PRIVATE + Boost::unit_test_framework + model_antares + array +) + +# Storing tests-ts-numbers under the folder Unit-tests in the IDE +set_target_properties(${EXECUTABLE_NAME} PROPERTIES FOLDER Unit-tests) + +add_test(NAME test-adq-patch COMMAND ${EXECUTABLE_NAME}) + +set_property(TEST test-adq-patch PROPERTY LABELS unit) diff --git a/src/tests/src/solver/optimisation/adequacy_patch/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch/adequacy_patch.cpp new file mode 100644 index 0000000000..377969fd5d --- /dev/null +++ b/src/tests/src/solver/optimisation/adequacy_patch/adequacy_patch.cpp @@ -0,0 +1,549 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test adequacy patch functions + +#define WIN32_LEAN_AND_MEAN + +#include +#include +#include + +#include + +#include +#include +#include "antares/solver/optimisation/adequacy_patch_csr/adq_patch_curtailment_sharing.h" +#include "antares/solver/optimisation/adequacy_patch_local_matching/adq_patch_local_matching.h" +#include "antares/study/parameters/adq-patch-params.h" + +static double origineExtremite = -1; +static double extremiteOrigine = 5; + +using namespace Antares::Data::AdequacyPatch; + +// NOTE +// Xmax limits the flux origin -> extremity (direct) +// -Xmin limits the flux extremity -> origin (indirect) + +std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originType, + AdequacyPatchMode extremityType, + bool SetNTCOutsideToOutsideToZero, + bool SetNTCOutsideToInsideToZero) +{ + PROBLEME_HEBDO problem; + problem.adequacyPatchRuntimeData = std::make_shared(); + problem.adequacyPatchRuntimeData->originAreaMode.resize(1); + problem.adequacyPatchRuntimeData->extremityAreaMode.resize(1); + + problem.adequacyPatchRuntimeData->originAreaMode[0] = originType; + problem.adequacyPatchRuntimeData->extremityAreaMode[0] = extremityType; + problem.adequacyPatchRuntimeData->AdequacyFirstStep = true; + + AdqPatchParams adqPatchParams; + adqPatchParams.enabled = true; + adqPatchParams.localMatching.setToZeroOutsideOutsideLinks = SetNTCOutsideToOutsideToZero; + adqPatchParams.localMatching.setToZeroOutsideInsideLinks = SetNTCOutsideToInsideToZero; + + VALEURS_DE_NTC_ET_RESISTANCES ValeursDeNTC; + ValeursDeNTC.ValeurDeNTCOrigineVersExtremite.assign(1, 0.); + ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine.assign(1, 0.); + ValeursDeNTC.ValeurDeNTCOrigineVersExtremite[0] = origineExtremite; + ValeursDeNTC.ValeurDeNTCExtremiteVersOrigine[0] = extremiteOrigine; + + double Xmin(0.); + double Xmax(0.); + + setNTCbounds(Xmax, Xmin, ValeursDeNTC, 0, &problem, adqPatchParams); + + return std::make_pair(Xmin, Xmax); +} + +static const double flowArea0toArea1_positive = 10; +static const double flowArea0toArea1_negative = -10; +static const double flowArea2toArea0_positive = 30; +static const double flowArea2toArea0_negative = -30; +static const double positiveEnsInit = 50.0; + +std::pair calculateAreaFlowBalanceForOneTimeStep( + double ensInit, + bool includeFlowsOutsideAdqPatchToDensNew, + AdequacyPatchMode Area1Mode, + AdequacyPatchMode Area2Mode, + double flowToArea1, + double flowFromArea2) +{ + PROBLEME_HEBDO problem; + int Area = 0; + uint hour = 0; + + // allocate memory + problem.adequacyPatchRuntimeData = std::make_shared(); + problem.adequacyPatchRuntimeData->originAreaMode.resize(3); + problem.adequacyPatchRuntimeData->extremityAreaMode.resize(3); + + AdqPatchParams adqPatchParams; + + problem.ResultatsHoraires.resize(1); + problem.ResultatsHoraires[0].ValeursHorairesDeDefaillancePositive = std::vector(1); + problem.ValeursDeNTC = std::vector(1); + problem.ValeursDeNTC[0].ValeurDuFlux = std::vector(3); + problem.IndexSuivantIntercoOrigine = std::vector(3); + problem.IndexSuivantIntercoExtremite = std::vector(3); + problem.IndexDebutIntercoOrigine = std::vector(1); + problem.IndexDebutIntercoExtremite = std::vector(1); + + // input values + adqPatchParams.localMatching.setToZeroOutsideInsideLinks + = !includeFlowsOutsideAdqPatchToDensNew; + problem.ResultatsHoraires[Area].ValeursHorairesDeDefaillancePositive[hour] = ensInit; + int Interco = 1; + problem.IndexDebutIntercoOrigine[Area] = Interco; + problem.adequacyPatchRuntimeData->extremityAreaMode[Interco] = Area1Mode; + problem.ValeursDeNTC[hour].ValeurDuFlux[Interco] = flowToArea1; + problem.IndexSuivantIntercoOrigine[Interco] = -1; + + Interco = 2; + problem.IndexDebutIntercoExtremite[Area] = Interco; + problem.adequacyPatchRuntimeData->originAreaMode[Interco] = Area2Mode; + problem.ValeursDeNTC[hour].ValeurDuFlux[Interco] = flowFromArea2; + problem.IndexSuivantIntercoExtremite[Interco] = -1; + + // get results + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew, std::ignore) = calculateAreaFlowBalance( + &problem, + adqPatchParams.localMatching.setToZeroOutsideInsideLinks, + Area, + hour); + + return std::make_pair(netPositionInit, densNew); +} + +AdqPatchParams createParams() +{ + AdqPatchParams p; + p.enabled = true; + p.curtailmentSharing.includeHurdleCost = true; + p.localMatching.enabled = true; + p.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isDens; + + return p; +} + +// Virtual -> Virtual (0 -> 0) +// No change in bounds is expected +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_virtual_no_change_expected) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(virtualArea, + virtualArea, + true /*SetNTCOutsideToOutsideToZero*/, + false); + BOOST_CHECK_EQUAL(Xmax, origineExtremite); + BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); +} + +// Virtual -> physical area inside adq-patch (0 -> 2) +// No change in bounds is expected +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_inside_no_change_expected) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(virtualArea, + physicalAreaInsideAdqPatch, + true /*SetNTCOutsideToOutsideToZero*/, + false); + BOOST_CHECK_EQUAL(Xmax, origineExtremite); + BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); +} + +// Virtual -> physical area outside adq-patch (0 -> 1) +// No change in bounds is expected +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_outside_no_change_expected) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(virtualArea, + physicalAreaOutsideAdqPatch, + true /*SetNTCOutsideToOutsideToZero*/, + false); + BOOST_CHECK_EQUAL(Xmax, origineExtremite); + BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); +} + +// physical area outside adq-patch -> physical area outside adq-patch (1 -> 1) +// NTC should be set to 0 in both directions +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_outside_zero_expected_both_directions) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, + true /*SetNTCOutsideToOutsideToZero*/, + false); + BOOST_CHECK_EQUAL(Xmax, 0); + BOOST_CHECK_EQUAL(Xmin, 0); +} + +// physical area outside adq-patch -> physical area outside adq-patch (1 -> 1) +// SetNTCOutsideToOutsideToZero = true +// NTC should be set to 0 in both directions +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_outside_no_change_expected) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, + false, + false); + + BOOST_CHECK_EQUAL(Xmax, origineExtremite); + BOOST_CHECK_EQUAL(Xmin, -extremiteOrigine); +} + +// physical area inside adq-patch -> physical area outside adq-patch (2 -> 1) +// NTC should be set to 0 in both directions +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_inside_outside_zero_expected_both_directions) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + false, + false); + BOOST_CHECK_EQUAL(Xmax, 0); + BOOST_CHECK_EQUAL(Xmin, 0); +} + +// physical area outside adq-patch -> physical area inside adq-patch (1 -> 2) +// NTC should be set to 0 in both directions +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_zero_expected_both_directions) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaOutsideAdqPatch, + physicalAreaInsideAdqPatch, + false, + true /*SetNTCOutsideToInsideToZero*/); + BOOST_CHECK_EQUAL(Xmax, 0); + BOOST_CHECK_EQUAL(Xmin, 0); +} + +// physical area outside adq-patch -> physical area inside adq-patch (1 -> 2) +// NTC should be unchanged in direction origin->extremity (direct) +// NTC should be set to 0 in direction extremity->origin (indirect) +BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_change_expected_one_direction) +{ + double Xmin, Xmax; + std::tie(Xmin, Xmax) = setNTCboundsForOneTimeStep(physicalAreaOutsideAdqPatch, + physicalAreaInsideAdqPatch, + false, + false); + BOOST_CHECK_EQUAL(Xmax, origineExtremite); + BOOST_CHECK_EQUAL(Xmin, 0); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 virtual-area, and Area2-virtual area +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter should NOT include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_virtual_virtual_NotIncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + false, + virtualArea, + virtualArea, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, 0.0); + BOOST_CHECK_EQUAL(densNew, 0.0); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2-virtual area +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter should NOT include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_inside_virtual_NotIncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + false, + physicalAreaInsideAdqPatch, + virtualArea, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); + BOOST_CHECK_EQUAL(densNew, 0.0); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2-virtual area +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter should NOT include flows from areas outside adq patch +// ensInit = 50.0 +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_inside_virtual_NotIncludeOut_positiveFlow_ensInitGraterThanZero) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + positiveEnsInit, + false, + physicalAreaInsideAdqPatch, + virtualArea, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); + BOOST_CHECK_EQUAL(densNew, positiveEnsInit - flowArea0toArea1_positive); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2 physical area outside adq-patch +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter should NOT include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_inside_outside_NotIncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + false, + physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); + BOOST_CHECK_EQUAL(densNew, 0.0); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2 physical area inside adq-patch +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter should NOT include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_inside_inside_NotIncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + false, + physicalAreaInsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_positive + flowArea2toArea0_positive); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2 physical area outside adq-patch +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter SHOULD include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_IncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + true, + physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive); + BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_positive + flowArea2toArea0_positive); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area outside adq-patch, and Area2 physical area outside adq-patch +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter SHOULD include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_IncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + true, + physicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, 0.0); + BOOST_CHECK_EQUAL(densNew, flowArea2toArea0_positive); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area outside adq-patch, and Area2 physical area inside adq-patch +// flow from Area0 -> Area1 is positive +// flow from Area2 -> Area0 is positive +// DensNew parameter SHOULD include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_positiveFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + true, + physicalAreaOutsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(netPositionInit, +flowArea2toArea0_positive); + BOOST_CHECK_EQUAL(densNew, +flowArea2toArea0_positive); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2 physical area outside adq-patch +// flow from Area0 -> Area1 is negative +// flow from Area2 -> Area0 is negative +// DensNew parameter SHOULD include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_IncludeOut_negativeFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + true, + physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea0toArea1_negative, + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_negative); + BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_negative); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area outside adq-patch, and Area2 physical area outside adq-patch +// flow from Area0 -> Area1 is negative +// flow from Area2 -> Area0 is negative +// DensNew parameter SHOULD include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_IncludeOut_negativeFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + true, + physicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea0toArea1_negative, + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(netPositionInit, 0.0); + BOOST_CHECK_EQUAL(densNew, -flowArea0toArea1_negative); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area outside adq-patch, and Area2 physical area inside adq-patch +// flow from Area0 -> Area1 is negative +// flow from Area2 -> Area0 is negative +// DensNew parameter SHOULD include flows from areas outside adq patch +BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 0.0, + true, + physicalAreaOutsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea0toArea1_negative, + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(netPositionInit, flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(densNew, 0.0); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2 physical area inside adq-patch +// flow from Area0 -> Area1 is positiive +// flow from Area2 -> Area0 is negative +// DensNew parameter SHOULD include flows from areas outside adq patch +// ensInit = 50.0 +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow_initEnsEqualTo50) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + positiveEnsInit, + true, + physicalAreaInsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(densNew, positiveEnsInit + netPositionInit); +} + +// Area 0 is physical area inside adq-patch connected to two areas: +// Area1 physical area inside adq-patch, and Area2 physical area inside adq-patch +// flow from Area0 -> Area1 is positiive +// flow from Area2 -> Area0 is negative +// DensNew parameter SHOULD include flows from areas outside adq patch +// ensInit = 2.0 +BOOST_AUTO_TEST_CASE( + calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow_initEnsEqualTo0) +{ + double netPositionInit; + double densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + 2.0, + true, + physicalAreaInsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea0toArea1_positive, + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(netPositionInit, -flowArea0toArea1_positive + flowArea2toArea0_negative); + BOOST_CHECK_EQUAL(densNew, 0.0); +} + +BOOST_AUTO_TEST_CASE(check_valid_adq_param) +{ + auto p = createParams(); + BOOST_CHECK_NO_THROW( + p.checkAdqPatchSimulationModeEconomyOnly(Antares::Data::SimulationMode::Economy)); + BOOST_CHECK_NO_THROW(p.checkAdqPatchIncludeHurdleCost(true)); +} + +BOOST_AUTO_TEST_CASE(check_adq_param_wrong_mode) +{ + auto p = createParams(); + BOOST_CHECK_THROW(p.checkAdqPatchSimulationModeEconomyOnly( + Antares::Data::SimulationMode::Adequacy), + Error::IncompatibleSimulationModeForAdqPatch); +} + +BOOST_AUTO_TEST_CASE(check_adq_param_wrong_hurdle_cost) +{ + auto p = createParams(); + BOOST_CHECK_THROW(p.checkAdqPatchIncludeHurdleCost(false), Error::IncompatibleHurdleCostCSR); +} diff --git a/src/tests/src/solver/optimisation/translator/CMakeLists.txt b/src/tests/src/solver/optimisation/translator/CMakeLists.txt new file mode 100644 index 0000000000..87f3d5a0cb --- /dev/null +++ b/src/tests/src/solver/optimisation/translator/CMakeLists.txt @@ -0,0 +1,20 @@ +set(EXECUTABLE_NAME test-translator) +add_executable(${EXECUTABLE_NAME}) + +target_sources(${EXECUTABLE_NAME} + PRIVATE + test_translator.cpp +) + +target_link_libraries(${EXECUTABLE_NAME} + PRIVATE + Boost::unit_test_framework + model_antares +) + +# Storing tests-ts-numbers under the folder Unit-tests in the IDE +set_target_properties(${EXECUTABLE_NAME} PROPERTIES FOLDER Unit-tests) + +add_test(NAME test-translator COMMAND ${EXECUTABLE_NAME}) + +set_property(TEST test-translator PROPERTY LABELS unit) diff --git a/src/tests/src/solver/optimisation/translator/test_translator.cpp b/src/tests/src/solver/optimisation/translator/test_translator.cpp new file mode 100644 index 0000000000..2430c74cb0 --- /dev/null +++ b/src/tests/src/solver/optimisation/translator/test_translator.cpp @@ -0,0 +1,191 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ + +#define BOOST_TEST_MODULE test_translator +#define WIN32_LEAN_AND_MEAN + +#include + +#include + +#include +#include "antares/solver/utils/opt_period_string_generator.h" + +using namespace Antares::Solver; + +class StubOptPeriodStringGenerator: public OptPeriodStringGenerator +{ +public: + std::string to_string() const override + { + return "Plop"; + } +}; + +BOOST_AUTO_TEST_CASE(null_hebdo_is_empty_lps) +{ + HebdoProblemToLpsTranslator translator; + auto ret = translator.translate(nullptr, std::string()); + BOOST_CHECK(ret == WeeklyDataFromAntares()); +} + +BOOST_AUTO_TEST_CASE(non_null_hebdo_returns_non_empty_lps) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.CoutLineaire.push_back(45); + auto ret = translator.translate(&problemHebdo, std::string()); + BOOST_CHECK(ret != WeeklyDataFromAntares()); +} + +BOOST_AUTO_TEST_CASE(Data_properly_copied) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.CoutLineaire = {0, 1, 2}; + problemHebdo.Xmax = {10, 11, 12}; + problemHebdo.Xmin = {20, 21, 22}; + problemHebdo.NomDesVariables = {"a", "b", "c"}; + problemHebdo.NomDesContraintes = {"d", "e", "f"}; + problemHebdo.SecondMembre = {30, 31, 32}; + + auto ret = translator.translate(&problemHebdo, std::string()); + BOOST_CHECK(ret.LinearCost == problemHebdo.CoutLineaire); + BOOST_CHECK(ret.Xmax == problemHebdo.Xmax); + BOOST_CHECK(ret.Xmin == problemHebdo.Xmin); + BOOST_CHECK(ret.RHS == problemHebdo.SecondMembre); + + BOOST_CHECK(ret.variables == problemHebdo.NomDesVariables); + BOOST_CHECK(ret.constraints == problemHebdo.NomDesContraintes); +} + +BOOST_AUTO_TEST_CASE(translate_sens) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.Sens = "<=>"; + + auto ret = translator.translate(&problemHebdo, std::string()); + BOOST_CHECK(ret.Direction == std::vector({'<', '=', '>'})); +} + +BOOST_AUTO_TEST_CASE(translate_name_is_filled) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + + auto ret = translator.translate(&problemHebdo, "dummy"); + BOOST_CHECK(!ret.name.empty()); +} + +BOOST_AUTO_TEST_CASE(translate_name_is_properly_filled) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + + auto ret = translator.translate(&problemHebdo, "problem-Plop--optim-nb-1.mps"); + BOOST_CHECK_EQUAL(ret.name, "problem-Plop--optim-nb-1.mps"); +} + +BOOST_AUTO_TEST_CASE(empty_problem_empty_const_data) +{ + HebdoProblemToLpsTranslator translator; + auto ret = translator.commonProblemData(nullptr); + BOOST_CHECK(ret == ConstantDataFromAntares()); +} + +BOOST_AUTO_TEST_CASE(common_data_properly_copied) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.NombreDeVariables = 1; + problemHebdo.NombreDeContraintes = 2; + problemHebdo.TypeDeVariable = {0, 1, 2}; + problemHebdo.IndicesDebutDeLigne = {0, 3}; + problemHebdo.NombreDeTermesDesLignes = {3, 3}; + problemHebdo.CoefficientsDeLaMatriceDesContraintes = {0, 1, 2, 3, 4, 5}; + problemHebdo.IndicesColonnes = {0, 1, 2, 3, 4, 5}; + + auto ret = translator.commonProblemData(&problemHebdo); + BOOST_CHECK_EQUAL(ret.VariablesCount, problemHebdo.NombreDeVariables); + BOOST_CHECK_EQUAL(ret.ConstraintesCount, problemHebdo.NombreDeContraintes); + BOOST_CHECK(std::ranges::equal(ret.VariablesType, problemHebdo.TypeDeVariable)); + BOOST_CHECK(ret.ConstraintsMatrixCoeff == problemHebdo.CoefficientsDeLaMatriceDesContraintes); + BOOST_CHECK(std::ranges::equal(ret.ColumnIndexes, problemHebdo.IndicesColonnes)); + auto expectedMdeb = problemHebdo.IndicesDebutDeLigne; + expectedMdeb.push_back(problemHebdo.CoefficientsDeLaMatriceDesContraintes.size()); + BOOST_CHECK(std::ranges::equal(ret.Mdeb, expectedMdeb)); +} + +// throw exception if NombreDeVariables is 0 +BOOST_AUTO_TEST_CASE(throw_exception_if_NombreDeVariables_is_0) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.NombreDeVariables = 0; + BOOST_CHECK_THROW(translator.commonProblemData(&problemHebdo), std::runtime_error); +} + +BOOST_AUTO_TEST_CASE(throw_exception_if_NombreDeContraintes_is_0) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.NombreDeContraintes = 0; + BOOST_CHECK_THROW(translator.commonProblemData(&problemHebdo), std::runtime_error); +} + +BOOST_AUTO_TEST_CASE(throw_exception_if_IndicesDebutDeLigne_out_of_bound) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.NombreDeVariables = 1; + problemHebdo.NombreDeContraintes = 3; + problemHebdo.IndicesDebutDeLigne = {0, 3}; + problemHebdo.NombreDeTermesDesLignes = {0, 3, 6, 7, 8}; + BOOST_CHECK_THROW(translator.commonProblemData(&problemHebdo), std::runtime_error); +} + +BOOST_AUTO_TEST_CASE(throw_exception_if_NombreDeTermesDesLignes_out_of_bound) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.NombreDeVariables = 1; + problemHebdo.NombreDeContraintes = 3; + problemHebdo.NombreDeTermesDesLignes = {0, 3}; + problemHebdo.IndicesDebutDeLigne = {0, 3, 6, 7, 8}; + BOOST_CHECK_THROW(translator.commonProblemData(&problemHebdo), std::runtime_error); +} + +// NombreDeCoefficients +BOOST_AUTO_TEST_CASE(NombreDeCoefficients_is_properly_computed) +{ + HebdoProblemToLpsTranslator translator; + PROBLEME_ANTARES_A_RESOUDRE problemHebdo; + problemHebdo.NombreDeVariables = 1; + problemHebdo.NombreDeContraintes = 3; + problemHebdo.IndicesDebutDeLigne = {0, 3, 6}; + problemHebdo.NombreDeTermesDesLignes = {3, 3, 3}; + problemHebdo.CoefficientsDeLaMatriceDesContraintes = {0, 1, 2, 3, 4, 5, 6, 7, 8}; + problemHebdo.IndicesColonnes = {0, 1, 2, 3, 4, 5, 6, 7, 8}; + + auto ret = translator.commonProblemData(&problemHebdo); + BOOST_CHECK_EQUAL(ret.CoeffCount, 9); +} diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index 5a5d18266a..294005454b 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -1,14 +1,15 @@ # Useful variables definitions set(src_solver_simulation "${CMAKE_SOURCE_DIR}/solver/simulation") +set(src_solver_hydro "${CMAKE_SOURCE_DIR}/solver/hydro") set(src_libs_antares_study "${CMAKE_SOURCE_DIR}/libs/antares/study") set(SRC_TS_NUMBERS # For confort in IDE, but not necessary - ${src_solver_simulation}/timeseries-numbers.h + ${src_solver_simulation}/include/antares/solver/simulation/timeseries-numbers.h # Necessary cpp files ${src_solver_simulation}/timeseries-numbers.cpp - ${src_solver_simulation}/ITimeSeriesNumbersWriter.h) + ${src_solver_simulation}/include/antares/solver/simulation/ITimeSeriesNumbersWriter.h) add_executable(tests-ts-numbers tests-ts-numbers.cpp ${SRC_TS_NUMBERS}) @@ -19,9 +20,11 @@ target_include_directories(tests-ts-numbers ) target_link_libraries(tests-ts-numbers PRIVATE + Antares::utils Boost::unit_test_framework model_antares antares-solver-simulation + antares-solver-ts-generator ) # Storing tests-ts-numbers under the folder Unit-tests in the IDE @@ -87,3 +90,33 @@ add_test(NAME time_series COMMAND test-time_series) set_property(TEST time_series PROPERTY LABELS unit) +# =================================== +# Tests on hydro final reservoir level functions +# =================================== + +add_executable(test-hydro_final test-hydro-final-reservoir-level-functions.cpp) + +target_include_directories(test-hydro_final + PRIVATE + "${src_solver_simulation}" + "${src_libs_antares_study}" + "${src_solver_hydro}" +) +target_link_libraries(test-hydro_final + PRIVATE + Boost::unit_test_framework + Antares::study + antares-solver-simulation + Antares::array +) + +# Linux +if(UNIX AND NOT APPLE) + target_link_libraries(test-hydro_final PRIVATE stdc++fs) +endif() + +set_target_properties(test-hydro_final PROPERTIES FOLDER Unit-tests) + +add_test(NAME hydro_final COMMAND test-hydro_final) + +set_property(TEST hydro_final PROPERTY LABELS unit) \ No newline at end of file diff --git a/src/tests/src/solver/simulation/test-hydro-final-reservoir-level-functions.cpp b/src/tests/src/solver/simulation/test-hydro-final-reservoir-level-functions.cpp new file mode 100644 index 0000000000..e426d99da4 --- /dev/null +++ b/src/tests/src/solver/simulation/test-hydro-final-reservoir-level-functions.cpp @@ -0,0 +1,286 @@ +// +// Created by Nikola Ilic on 23/06/23. +// + +#define BOOST_TEST_MODULE hydro - final - level +#define WIN32_LEAN_AND_MEAN +#include + +#include + +#include "include/antares/solver/hydro/management/hydro-final-reservoir-level-functions.h" +#include "include/antares/study/parts/hydro/finalLevelValidator.h" + +using namespace Antares::Solver; +using namespace Antares::Data; + +struct Fixture +{ + Fixture(const Fixture& f) = delete; + Fixture(const Fixture&& f) = delete; + Fixture& operator=(const Fixture& f) = delete; + Fixture& operator=(const Fixture&& f) = delete; + + Fixture() + { + // Simulation last day must be 365 so that final level checks succeeds + study->parameters.simulationDays.end = 365; + study->parameters.firstMonthInYear = january; + uint nbYears = study->parameters.nbYears = 2; + + area_1 = study->areaAdd("Area1"); + area_2 = study->areaAdd("Area2"); + + area_1->hydro.reservoirManagement = true; + area_2->hydro.reservoirManagement = true; + + area_1->hydro.useWaterValue = false; + area_2->hydro.useWaterValue = false; + + // Level date must be 0, see hydroAllocationStartMatchesSimulation function + area_1->hydro.initializeReservoirLevelDate = 0; + area_2->hydro.initializeReservoirLevelDate = 0; + + area_1->hydro.reservoirCapacity = 340.; + area_2->hydro.reservoirCapacity = 300.; + + // Set reservoir max and min daily levels, but just for the last day in year + area_1->hydro.reservoirLevel.resize(3, DAYS_PER_YEAR); + area_1->hydro.reservoirLevel[PartHydro::minimum][DAYS_PER_YEAR - 1] = 2.4; + area_1->hydro.reservoirLevel[PartHydro::maximum][DAYS_PER_YEAR - 1] = 6.5; + + area_2->hydro.reservoirLevel.resize(3, DAYS_PER_YEAR); + area_2->hydro.reservoirLevel[PartHydro::minimum][DAYS_PER_YEAR - 1] = 2.7; + area_2->hydro.reservoirLevel[PartHydro::maximum][DAYS_PER_YEAR - 1] = 6.4; + + // Resize vector final levels delta with initial levels + area_1->hydro.deltaBetweenFinalAndInitialLevels.resize(nbYears); + area_2->hydro.deltaBetweenFinalAndInitialLevels.resize(nbYears); + + // Scenario builder for initial and final reservoir levels + // ------------------------------------------------------- + uint areasCount = study->areas.size(); + + study->parameters.yearsFilter.assign(2, true); + + study->scenarioInitialHydroLevels.resize(nbYears, areasCount); + study->scenarioFinalHydroLevels.resize(nbYears, areasCount); + + study->scenarioInitialHydroLevels[0][0] = 2.3; + study->scenarioInitialHydroLevels[0][1] = 4.2; + study->scenarioInitialHydroLevels[1][0] = 1.5; + study->scenarioInitialHydroLevels[1][1] = 2.4; + + study->scenarioFinalHydroLevels[0][0] = 3.4; + study->scenarioFinalHydroLevels[0][1] = 5.1; + study->scenarioFinalHydroLevels[1][0] = 3.5; + study->scenarioFinalHydroLevels[1][1] = 4.3; + + // Inflows time series matrices + // ----------------------------- + uint nbInflowTS = 2; + // ... Area 1 : Inflows time series numbers for each year + area_1->hydro.series->timeseriesNumbers.reset(nbYears); + area_1->hydro.series->timeseriesNumbers[0] = 0; + area_1->hydro.series->timeseriesNumbers[1] = 1; + // ... Area 1 : Inflows time series + area_1->hydro.series->storage.resize(nbInflowTS, 365); + area_1->hydro.series->storage.timeSeries.fill(200.); + area_1->hydro.series->storage[0][0] = 200. + 1.; + area_1->hydro.series->storage[0][DAYS_PER_YEAR - 1] = 200. + 2.; + + // ... Area 2 : time series numbers for each year + area_2->hydro.series->timeseriesNumbers.reset(nbYears); + area_2->hydro.series->timeseriesNumbers[0] = 0; + area_2->hydro.series->timeseriesNumbers[1] = 1; + // ... Area 2 : Inflows time series + area_2->hydro.series->storage.resize(nbInflowTS, 365); + area_2->hydro.series->storage.timeSeries.fill(300.); + area_2->hydro.series->storage[0][0] = 300. + 1.; // DAYS_PER_YEAR + area_2->hydro.series->storage[0][DAYS_PER_YEAR - 1] = 300. + 2.; + } + + ~Fixture() = default; + + Study::Ptr study = std::make_shared(); + Area* area_1; + Area* area_2; +}; + +BOOST_FIXTURE_TEST_SUITE(final_level_validator, Fixture) + +BOOST_AUTO_TEST_CASE(all_parameters_good___check_succeeds_and_final_level_is_usable) +{ + uint year = 0; + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), true); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), true); +} + +BOOST_AUTO_TEST_CASE(no_reservoir_management___check_succeeds_but_final_level_not_usable) +{ + uint year = 0; + area_1->hydro.reservoirManagement = false; + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), true); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE(use_water_value_is_true___check_succeeds_but_final_level_not_usable) +{ + area_1->hydro.useWaterValue = true; + uint year = 0; + + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), true); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE(final_level_not_set_by_user____check_succeeds_but_final_level_not_usable) +{ + uint year = 0; + study->scenarioFinalHydroLevels[area_1->index][year] = std::numeric_limits::quiet_NaN(); + + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), true); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE( + initial_level_month_and_simulation_first_month_different___check_fails_and_final_level_not_usable) +{ + uint year = 0; + area_1->hydro.initializeReservoirLevelDate = 3; // initialize reservoir level != January + + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE(simulation_does_last_a_whole_year___check_fails_and_final_level_not_usable) +{ + uint year = 0; + study->parameters.simulationDays.end = 300; + + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE(final_level_out_of_rule_curves___check_fails_and_final_level_not_usable) +{ + uint year = 0; + // Rule Curves on last simulation day = [2.4 - 6.5] + study->scenarioFinalHydroLevels[area_1->index][year] = 6.6; + + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE( + final_level_unreachable_because_of_too_few_inflows___check_fails_and_final_level_not_usable) +{ + area_1->hydro.reservoirCapacity = 185000; + uint year = 0; + study->scenarioInitialHydroLevels[area_1->index][year] = 10; + study->scenarioFinalHydroLevels[area_1->index][year] = 50; + + // Inflows = 200 MWh/day = 73 000 MWh/year + // (50 - 10) x Reservoir capacity == 74 000 > 73 000. + FinalLevelValidator validator(area_1->hydro, + area_1->index, + area_1->name, + study->scenarioInitialHydroLevels[area_1->index][year], + study->scenarioFinalHydroLevels[area_1->index][year], + year, + study->parameters.simulationDays.end, + study->parameters.firstMonthInYear); + + BOOST_CHECK_EQUAL(validator.check(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); +} + +BOOST_AUTO_TEST_CASE(check_all_areas_final_levels_when_config_is_ok___all_checks_succeed) +{ + for (uint year: {0, 1}) + { + CheckFinalReservoirLevelsConfiguration(study->areas, + study->parameters, + study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + year); + } + // CheckFinalReservoirLevelsConfiguration(*study, 0); + // CheckFinalReservoirLevelsConfiguration(*study, 1); + + // Checks on Area 1 modifier + BOOST_CHECK_EQUAL(area_1->hydro.deltaBetweenFinalAndInitialLevels[0].has_value(), true); + BOOST_CHECK_EQUAL(area_1->hydro.deltaBetweenFinalAndInitialLevels[1].has_value(), true); + BOOST_CHECK_EQUAL(area_1->hydro.deltaBetweenFinalAndInitialLevels[0].value(), 3.4 - 2.3); + BOOST_CHECK_EQUAL(area_1->hydro.deltaBetweenFinalAndInitialLevels[1].value(), 5.1 - 4.2); + + // Checks on Area 2 modifier + BOOST_CHECK_EQUAL(area_2->hydro.deltaBetweenFinalAndInitialLevels[0].has_value(), true); + BOOST_CHECK_EQUAL(area_2->hydro.deltaBetweenFinalAndInitialLevels[1].has_value(), true); + BOOST_CHECK_EQUAL(area_2->hydro.deltaBetweenFinalAndInitialLevels[0].value(), 3.5 - 1.5); + BOOST_CHECK_EQUAL(area_2->hydro.deltaBetweenFinalAndInitialLevels[1].value(), 4.3 - 2.4); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/tests/src/solver/simulation/test-store-timeseries-number.cpp b/src/tests/src/solver/simulation/test-store-timeseries-number.cpp index 43948da1a8..16cbb59fc2 100644 --- a/src/tests/src/solver/simulation/test-store-timeseries-number.cpp +++ b/src/tests/src/solver/simulation/test-store-timeseries-number.cpp @@ -1,26 +1,47 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ // // Created by marechaljas on 15/03/23. // -#define BOOST_TEST_MODULE store-timeseries-number -#define BOOST_TEST_DYN_LINK +#define BOOST_TEST_MODULE store - timeseries - number #define WIN32_LEAN_AND_MEAN - -#include +#include #include #include -#include "timeseries-numbers.h" -#include "BindingConstraintsTimeSeriesNumbersWriter.h" -#include "utils.h" -#include -#include + +#include + #include +#include +#include +#include "antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h" +#include "antares/solver/simulation/timeseries-numbers.h" using namespace Antares::Solver; using namespace Antares::Data; namespace fs = std::filesystem; -void initializeStudy(Study &study) { +void initializeStudy(Study& study) +{ study.parameters.derated = false; study.runtime = new StudyRuntimeInfos(); @@ -35,46 +56,52 @@ void initializeStudy(Study &study) { study.parameters.timeSeriesToRefresh = 0; } -BOOST_AUTO_TEST_CASE(BC_group_TestGroup_has_output_file) { +BOOST_AUTO_TEST_CASE(BC_group_TestGroup_has_output_file) +{ auto study = std::make_shared(); study->parameters.storeTimeseriesNumbers = true; study->bindingConstraintsGroups.add("TestGroup"); - study->bindingConstraintsGroups["TestGroup"]->timeseriesNumbers.resize(1, 1); + study->bindingConstraintsGroups["TestGroup"]->timeseriesNumbers.reset(1); auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); - Benchmarking::NullDurationCollector nullDurationCollector; - auto resultWriter = resultWriterFactory(ResultFormat::legacyFilesDirectories, working_tmp_dir.string().c_str(), - nullptr, nullDurationCollector); + Benchmarking::DurationCollector durationCollector; + auto resultWriter = resultWriterFactory(ResultFormat::legacyFilesDirectories, + working_tmp_dir.string().c_str(), + nullptr, + durationCollector); fs::path bc_path = working_tmp_dir / "ts-numbers" / "bindingconstraints" / "TestGroup.txt"; initializeStudy(*study); - TimeSeriesNumbers::Generate(*study); - TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(*study, *resultWriter); + Antares::Solver::TimeSeriesNumbers::Generate(*study); + Antares::Solver::TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(*study, *resultWriter); bool file_exists = fs::exists(bc_path); BOOST_CHECK_EQUAL(file_exists, true); } -BOOST_AUTO_TEST_CASE(BC_output_ts_numbers_file_for_each_group) { +BOOST_AUTO_TEST_CASE(BC_output_ts_numbers_file_for_each_group) +{ auto study = std::make_shared(); study->parameters.storeTimeseriesNumbers = true; study->bindingConstraintsGroups.add("test1"); study->bindingConstraintsGroups.add("test2"); - study->bindingConstraintsGroups["test1"]->timeseriesNumbers.resize(1, 1); - study->bindingConstraintsGroups["test2"]->timeseriesNumbers.resize(1, 1); + study->bindingConstraintsGroups["test1"]->timeseriesNumbers.reset(1); + study->bindingConstraintsGroups["test2"]->timeseriesNumbers.reset(1); auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); - Benchmarking::NullDurationCollector nullDurationCollector; - auto resultWriter = resultWriterFactory(ResultFormat::legacyFilesDirectories, working_tmp_dir.string().c_str(), - nullptr, nullDurationCollector); + Benchmarking::DurationCollector durationCollector; + auto resultWriter = resultWriterFactory(ResultFormat::legacyFilesDirectories, + working_tmp_dir.string().c_str(), + nullptr, + durationCollector); initializeStudy(*study); - TimeSeriesNumbers::Generate(*study); + Antares::Solver::TimeSeriesNumbers::Generate(*study); - TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(*study, *resultWriter); + Antares::Solver::TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(*study, *resultWriter); fs::path test1_path = working_tmp_dir / "ts-numbers" / "bindingconstraints" / "test1.txt"; fs::path test2_path = working_tmp_dir / "ts-numbers" / "bindingconstraints" / "test2.txt"; @@ -82,38 +109,38 @@ BOOST_AUTO_TEST_CASE(BC_output_ts_numbers_file_for_each_group) { BOOST_CHECK_EQUAL(fs::exists(test2_path), true); } -BOOST_AUTO_TEST_CASE(BC_timeseries_numbers_store_values) { +BOOST_AUTO_TEST_CASE(BC_timeseries_numbers_store_values) +{ auto study = std::make_shared(); study->parameters.storeTimeseriesNumbers = true; auto group = study->bindingConstraintsGroups.add("test1"); auto bc = std::make_shared(); - bc->RHSTimeSeries().resize(10,10); + bc->RHSTimeSeries().resize(10, 10); group->add(bc); - study->bindingConstraintsGroups["test1"]->timeseriesNumbers.resize(1, 1); + study->bindingConstraintsGroups["test1"]->timeseriesNumbers.reset(1); auto working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); - Benchmarking::NullDurationCollector nullDurationCollector; - auto resultWriter = resultWriterFactory(ResultFormat::legacyFilesDirectories, working_tmp_dir.string().c_str(), - nullptr, nullDurationCollector); + Benchmarking::DurationCollector durationCollector; + auto resultWriter = resultWriterFactory(ResultFormat::legacyFilesDirectories, + working_tmp_dir.string().c_str(), + nullptr, + durationCollector); initializeStudy(*study); - TimeSeriesNumbers::Generate(*study); - Matrix series(2, 2); - series[0][0] = 0; - series[0][1] = 1; - series[1][0] = 42; - series[1][1] = 3; - study->bindingConstraintsGroups["test1"]->timeseriesNumbers = series; + Antares::Solver::TimeSeriesNumbers::Generate(*study); + + auto& tsNumbers = study->bindingConstraintsGroups["test1"]->timeseriesNumbers; + tsNumbers.reset(2); + tsNumbers[0] = 0; + tsNumbers[1] = 1; - TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(*study, *resultWriter); + Antares::Solver::TimeSeriesNumbers::StoreTimeSeriesNumbersIntoOuput(*study, *resultWriter); fs::path test1_path = working_tmp_dir / "ts-numbers" / "bindingconstraints" / "test1.txt"; BOOST_CHECK_EQUAL(fs::exists(test1_path), true); Matrix out; out.loadFromCSVFile(test1_path.string()); - BOOST_CHECK_EQUAL(series[0][0]+1, out[0][0]); - BOOST_CHECK_EQUAL(series[0][1]+1, out[0][1]); - BOOST_CHECK_EQUAL(series[1][0]+1, out[1][0]); - BOOST_CHECK_EQUAL(series[1][1]+1, out[1][1]); + BOOST_CHECK_EQUAL(tsNumbers[0] + 1, out[0][0]); + BOOST_CHECK_EQUAL(tsNumbers[1] + 1, out[0][1]); } diff --git a/src/tests/src/solver/simulation/test-time_series.cpp b/src/tests/src/solver/simulation/test-time_series.cpp index 00357c5299..42f1fbddf4 100644 --- a/src/tests/src/solver/simulation/test-time_series.cpp +++ b/src/tests/src/solver/simulation/test-time_series.cpp @@ -1,15 +1,36 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ // // Created by marechaljas on 07/04/23. // #define BOOST_TEST_MODULE rhsTimeSeries -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN -#include -#include +#include #include #include -#include "utils.h" + +#include + +#include using namespace Antares::Solver; using namespace Antares::Data; @@ -31,26 +52,32 @@ void initializeStudy(Study& study) study.parameters.timeSeriesToRefresh = 0; } -class PublicStudy: public Study { +class PublicStudy: public Study +{ public: - bool internalLoadBindingConstraints(const StudyLoadOptions& options) override { + bool internalLoadBindingConstraints(const StudyLoadOptions& options) override + { return Study::internalLoadBindingConstraints(options); } }; template -void CheckEqual(const Matrix& a, const Matrix& b) { +void CheckEqual(const Matrix& a, const Matrix& b) +{ BOOST_CHECK_EQUAL(a.width, b.width); BOOST_CHECK_EQUAL(a.height, b.height); - if (a.height > 0 && a.width > 0) { + if (a.height > 0 && a.width > 0) + { BOOST_CHECK_EQUAL(a[0][0], b[0][0]); - BOOST_CHECK_EQUAL(a[a.width-1][a.height-1], b[b.width-1][b.height-1]); + BOOST_CHECK_EQUAL(a[a.width - 1][a.height - 1], b[b.width - 1][b.height - 1]); } } -struct Fixture { - Fixture() { - study->header.version = version870; +struct Fixture +{ + Fixture() + { + study->header.version = StudyVersion(8, 7); working_tmp_dir = CREATE_TMP_DIR_BASED_ON_TEST_NAME(); study->folderInput = working_tmp_dir.string(); @@ -76,35 +103,42 @@ struct Fixture { expected_equality_series.fillColumn(2, 0.9); expected_equality_series[0][8763] = 1; - expected_lower_bound_series.saveToCSVFile((working_tmp_dir / "bindingconstraints"/ "dummy_name_lt.txt").string()); - expected_upper_bound_series.saveToCSVFile((working_tmp_dir / "bindingconstraints"/ "dummy_name_gt.txt").string()); - expected_equality_series.saveToCSVFile((working_tmp_dir / "bindingconstraints"/ "dummy_name_eq.txt").string()); - }; + expected_lower_bound_series.saveToCSVFile( + (working_tmp_dir / "bindingconstraints" / "dummy_name_lt.txt").string()); + expected_upper_bound_series.saveToCSVFile( + (working_tmp_dir / "bindingconstraints" / "dummy_name_gt.txt").string()); + expected_equality_series.saveToCSVFile( + (working_tmp_dir / "bindingconstraints" / "dummy_name_eq.txt").string()); + } - void addConstraint(const std::string& name, const std::string& group, bool reset = false) const { + void addConstraint(const std::string& name, const std::string& group, bool reset = false) const + { std::ofstream constraints(working_tmp_dir / "bindingconstraints" / "bindingconstraints.ini", reset ? std::ios_base::out : std::ios_base::app); static unsigned constraintNumber = 1; - if (reset) constraintNumber = 1; + if (reset) + { + constraintNumber = 1; + } constraints << "[" << constraintNumber++ << "]\n" << "name = " << name << "\n" - <<"id = " << name << "\n" + << "id = " << name << "\n" << "enabled = false\n" << "type = hourly\n" << "operator = equal\n" << "filter-year-by-year = annual\n" << "filter-synthesis = hourly\n" << "comments = dummy_comment\n" - << "group = " << group << "\n" - ; + << "group = " << group << "\n"; constraints.close(); - std::ofstream rhs(working_tmp_dir / "bindingconstraints"/ (name+"_eq.txt")); + std::ofstream rhs(working_tmp_dir / "bindingconstraints" / (name + "_eq.txt")); rhs.close(); } std::shared_ptr study = std::make_shared(); StudyLoadOptions options; - std::filesystem::path working_tmp_dir;; + std::filesystem::path working_tmp_dir; + ; Matrix expected_lower_bound_series; Matrix expected_upper_bound_series; Matrix expected_equality_series; @@ -112,14 +146,17 @@ struct Fixture { BOOST_AUTO_TEST_SUITE(BC_TimeSeries) -BOOST_FIXTURE_TEST_CASE(load_binding_constraints_timeseries, Fixture) { +BOOST_FIXTURE_TEST_CASE(load_binding_constraints_timeseries, Fixture) +{ bool loading_ok = study->internalLoadBindingConstraints(options); BOOST_CHECK_EQUAL(loading_ok, true); BOOST_CHECK_EQUAL(study->bindingConstraints.size(), 1); - CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), expected_equality_series); + CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), + expected_equality_series); { - std::ofstream constraints(working_tmp_dir / "bindingconstraints"/ "bindingconstraints.ini"); + std::ofstream constraints(working_tmp_dir / "bindingconstraints" + / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" << "id = dummy_name\n" @@ -131,10 +168,12 @@ BOOST_FIXTURE_TEST_CASE(load_binding_constraints_timeseries, Fixture) { } loading_ok = study->internalLoadBindingConstraints(options); BOOST_CHECK_EQUAL(loading_ok, true); - CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), expected_lower_bound_series); + CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), + expected_lower_bound_series); { - std::ofstream constraints(working_tmp_dir / "bindingconstraints" / "bindingconstraints.ini"); + std::ofstream constraints(working_tmp_dir / "bindingconstraints" + / "bindingconstraints.ini"); constraints << "[1]\n" << "name = dummy_name\n" << "id = dummy_name\n" @@ -146,35 +185,44 @@ BOOST_FIXTURE_TEST_CASE(load_binding_constraints_timeseries, Fixture) { } loading_ok = study->internalLoadBindingConstraints(options); BOOST_CHECK_EQUAL(loading_ok, true); - CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), expected_upper_bound_series); + CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), + expected_upper_bound_series); } -BOOST_FIXTURE_TEST_CASE(verify_all_constraints_in_a_group_have_the_same_number_of_time_series_error_case, Fixture) { +BOOST_FIXTURE_TEST_CASE( + verify_all_constraints_in_a_group_have_the_same_number_of_time_series_error_case, + Fixture) +{ addConstraint("dummy_name_2", "dummy_group"); Matrix values; values.resize(5, 8784); values.fill(0.42); - values.saveToCSVFile((working_tmp_dir / "bindingconstraints"/ "dummy_name_2_eq.txt").string()); + values.saveToCSVFile((working_tmp_dir / "bindingconstraints" / "dummy_name_2_eq.txt").string()); auto loading_ok = study->internalLoadBindingConstraints(options); BOOST_CHECK_EQUAL(loading_ok, false); } -BOOST_FIXTURE_TEST_CASE(verify_all_constraints_in_a_group_have_the_same_number_of_time_series_good_case, Fixture) { +BOOST_FIXTURE_TEST_CASE( + verify_all_constraints_in_a_group_have_the_same_number_of_time_series_good_case, + Fixture) +{ addConstraint("dummy_name_2", "dummy_group"); Matrix values; values.resize(3, 8784); values.fill(0.42); - values.saveToCSVFile((working_tmp_dir / "bindingconstraints"/ "dummy_name_2_eq.txt").string()); + values.saveToCSVFile((working_tmp_dir / "bindingconstraints" / "dummy_name_2_eq.txt").string()); auto loading_ok = study->internalLoadBindingConstraints(options); BOOST_CHECK_EQUAL(loading_ok, true); } -BOOST_FIXTURE_TEST_CASE(Check_empty_file_interpreted_as_all_zeroes, Fixture) { - std::vector file_names = {working_tmp_dir / "bindingconstraints"/ "dummy_name_lt.txt", - working_tmp_dir / "bindingconstraints"/ "dummy_name_gt.txt", - working_tmp_dir / "bindingconstraints"/ "dummy_name_eq.txt"}; - for (auto file_name: file_names) { +BOOST_FIXTURE_TEST_CASE(Check_empty_file_interpreted_as_all_zeroes, Fixture) +{ + std::vector file_names = {working_tmp_dir / "bindingconstraints" / "dummy_name_lt.txt", + working_tmp_dir / "bindingconstraints" / "dummy_name_gt.txt", + working_tmp_dir / "bindingconstraints" / "dummy_name_eq.txt"}; + for (auto& file_name: file_names) + { std::ofstream ofs; ofs.open(file_name, std::ofstream::out | std::ofstream::trunc); ofs.close(); @@ -187,11 +235,13 @@ BOOST_FIXTURE_TEST_CASE(Check_empty_file_interpreted_as_all_zeroes, Fixture) { CheckEqual(study->bindingConstraints.find("dummy_name")->RHSTimeSeries(), expectation); } -BOOST_FIXTURE_TEST_CASE(Check_missing_file, Fixture) { - std::vector file_names = {working_tmp_dir / "bindingconstraints"/ "dummy_name_lt.txt", - working_tmp_dir / "bindingconstraints"/ "dummy_name_gt.txt", - working_tmp_dir / "bindingconstraints"/ "dummy_name_eq.txt"}; - for (auto file_name: file_names) { +BOOST_FIXTURE_TEST_CASE(Check_missing_file, Fixture) +{ + std::vector file_names = {working_tmp_dir / "bindingconstraints" / "dummy_name_lt.txt", + working_tmp_dir / "bindingconstraints" / "dummy_name_gt.txt", + working_tmp_dir / "bindingconstraints" / "dummy_name_eq.txt"}; + for (auto& file_name: file_names) + { std::filesystem::remove(file_name); } diff --git a/src/tests/src/solver/simulation/tests-ts-numbers.cpp b/src/tests/src/solver/simulation/tests-ts-numbers.cpp index 13cd2a187f..9767cbe525 100644 --- a/src/tests/src/solver/simulation/tests-ts-numbers.cpp +++ b/src/tests/src/solver/simulation/tests-ts-numbers.cpp @@ -1,33 +1,52 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #define BOOST_TEST_MODULE test solver simulation things -#define BOOST_TEST_DYN_LINK #define WIN32_LEAN_AND_MEAN +#include // std::adjacent_find + #include -#include - -#include // std::adjacent_find +#include +#include +#include "antares/solver/ts-generator/generator.h" using namespace Yuni; using namespace Antares::Data; using namespace Antares::Solver::TimeSeriesNumbers; - -void initializeStudy(Study::Ptr study) +void initializeStudy(Study::Ptr study, unsigned int nbYears = 1) { - study->parameters.derated = false; + study->parameters.derated = false; - study->runtime = new StudyRuntimeInfos(); - study->runtime->rangeLimits.year[rangeBegin] = 0; - study->runtime->rangeLimits.year[rangeEnd] = 0; - study->runtime->rangeLimits.year[rangeCount] = 1; + study->runtime = new StudyRuntimeInfos(); + study->runtime->rangeLimits.year[rangeBegin] = 0; + study->runtime->rangeLimits.year[rangeEnd] = nbYears - 1; - study->parameters.renewableGeneration.toAggregated(); // Default + study->parameters.renewableGeneration.toAggregated(); // Default - study->parameters.intraModal = 0; - study->parameters.interModal = 0; - study->parameters.timeSeriesToRefresh = 0; + study->parameters.intraModal = 0; + study->parameters.interModal = 0; + study->parameters.timeSeriesToRefresh = 0; } // ======================== @@ -35,43 +54,35 @@ void initializeStudy(Study::Ptr study) // ======================== Area* addAreaToStudy(Study::Ptr study, const std::string& areaName) { - Area* area = study->areaAdd(areaName); - BOOST_CHECK(area != NULL); + Area* area = study->areaAdd(areaName); + BOOST_CHECK(area); - return area; + return area; } // =========================== // Add a cluster to an area // =========================== -template -void addClusterToAreaList(Area* area, std::shared_ptr cluster); -template<> void addClusterToAreaList(Area* area, std::shared_ptr cluster) { - area->thermal.clusters.push_back(cluster.get()); - area->thermal.list.add(cluster); - area->thermal.list.mapping[cluster->id()] = cluster; + area->thermal.list.addToCompleteList(cluster); } -template<> void addClusterToAreaList(Area* area, std::shared_ptr cluster) { - area->renewable.clusters.push_back(cluster.get()); - area->renewable.list.add(cluster); + area->renewable.list.addToCompleteList(cluster); } template std::shared_ptr addClusterToArea(Area* area, const std::string& clusterName) { - auto cluster = std::make_shared(area); - cluster->setName(clusterName); - cluster->series = new DataSeriesCommon(); + auto cluster = std::make_shared(area); + cluster->setName(clusterName); - addClusterToAreaList(area, cluster); + addClusterToAreaList(area, cluster); - return cluster; + return cluster; } BOOST_AUTO_TEST_CASE(test_compare_function_identical_values_OK) @@ -111,486 +122,426 @@ BOOST_AUTO_TEST_CASE(test_compare_function_three_distinct_values_KO) BOOST_AUTO_TEST_CASE(two_areas_with_5_ready_made_ts_on_load___check_intra_modal_consistency_OK) { - // Creating a study + // Creating a study auto study = std::make_shared(); - initializeStudy(study); + initializeStudy(study); - study->parameters.intraModal |= timeSeriesLoad; + study->parameters.intraModal |= timeSeriesLoad; - // Area 1 - Area* area_1 = addAreaToStudy(study, "Area 1"); - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - area_1->load.series->timeSeries.resize(5, 1); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - // Area 2 - Area* area_2 = addAreaToStudy(study, "Area 2"); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - area_2->load.series->timeSeries.resize(5, 1); + area_1->load.series.timeSeries.resize(5, 1); + area_2->load.series.timeSeries.resize(5, 1); - BOOST_CHECK(Generate(*study)); + BOOST_CHECK(Generate(*study)); - // intra-modal for load : drawn TS numbers in all areas must be equal - uint year = 0; - BOOST_CHECK_EQUAL(area_1->load.series->timeseriesNumbers[0][year], area_2->load.series->timeseriesNumbers[0][year]); + // intra-modal for load : drawn TS numbers in all areas must be equal + uint year = 0; + BOOST_CHECK_EQUAL(area_1->load.series.timeseriesNumbers[year], + area_2->load.series.timeseriesNumbers[year]); } -static bool intermodal_load_two_areas(unsigned width_area_1, unsigned width_area_2) +// ======================= +// Tests on intra-modal +// ======================= + +static bool intramodal_load_two_areas(unsigned width_area_1, unsigned width_area_2) { - // Creating a study + // Creating a study auto study = std::make_shared(); - initializeStudy(study); + initializeStudy(study); - study->parameters.intraModal |= timeSeriesLoad; + study->parameters.intraModal |= timeSeriesLoad; - // Area 1 - Area* area_1 = addAreaToStudy(study, "Area 1"); - area_1->load.series->timeSeries.resize(width_area_1, 1); - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - // Area 2 - Area* area_2 = addAreaToStudy(study, "Area 2"); - area_2->load.series->timeSeries.resize(width_area_2, 1); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + area_1->load.series.timeSeries.resize(width_area_1, 1); + area_2->load.series.timeSeries.resize(width_area_2, 1); - return Generate(*study); + return Generate(*study); } -BOOST_AUTO_TEST_CASE(two_areas_with_respectively_5_and_4_ready_made_ts_on_load___check_intra_modal_consistency_KO) +BOOST_AUTO_TEST_CASE( + two_areas_with_respectively_5_and_4_ready_made_ts_on_load___check_intra_modal_consistency_KO) { - BOOST_CHECK(!intermodal_load_two_areas(5, 4)); + BOOST_CHECK(!intramodal_load_two_areas(5, 4)); } -BOOST_AUTO_TEST_CASE(two_areas_with_respectively_5_and_1_ready_made_ts_on_load___check_intra_modal_consistency_OK) +BOOST_AUTO_TEST_CASE( + two_areas_with_respectively_5_and_1_ready_made_ts_on_load___check_intra_modal_consistency_OK) { - BOOST_CHECK(intermodal_load_two_areas(5, 1)); + BOOST_CHECK(intramodal_load_two_areas(5, 1)); } -BOOST_AUTO_TEST_CASE(two_areas_3_thermal_clusters_with_same_number_of_ready_made_ts___check_intra_modal_consistency_OK) +BOOST_AUTO_TEST_CASE( + two_areas_3_thermal_clusters_with_same_number_of_ready_made_ts___check_intra_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.intraModal |= timeSeriesThermal; - - // ============= - // Area 1 - // ============= - Area* area_1 = addAreaToStudy(study, "Area 1"); - - // ... Area 1 : thermal cluster 1 - auto thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); - thCluster_11->series->timeSeries.resize(4, 1); - // ... Area 1 : thermal cluster 2 - auto thCluster_12 = addClusterToArea(area_1, "th-cluster-12"); - thCluster_12->series->timeSeries.resize(4, 1); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + study->parameters.intraModal |= timeSeriesThermal; - // ============= - // Area 2 - // ============= - Area* area_2 = addAreaToStudy(study, "Area 2"); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); - // ... Area 2 : thermal cluster 1 - auto thCluster_21 = addClusterToArea(area_2, "th-cluster-21"); - thCluster_21->series->timeSeries.resize(4, 1); + // Area 1 : thermal cluster 1 + auto thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); + thCluster_11->series.timeSeries.resize(4, 1); + // Area 1 : thermal cluster 2 + auto thCluster_12 = addClusterToArea(area_1, "th-cluster-12"); + thCluster_12->series.timeSeries.resize(4, 1); + // Area 2 : thermal cluster 1 + auto thCluster_21 = addClusterToArea(area_2, "th-cluster-21"); + thCluster_21->series.timeSeries.resize(4, 1); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(Generate(*study)); + BOOST_CHECK(Generate(*study)); - // TS number checks - uint year = 0; - BOOST_CHECK_EQUAL(thCluster_12->series->timeseriesNumbers[0][year], thCluster_11->series->timeseriesNumbers[0][year]); - BOOST_CHECK_EQUAL(thCluster_21->series->timeseriesNumbers[0][year], thCluster_11->series->timeseriesNumbers[0][year]); + // TS number checks + uint year = 0; + BOOST_CHECK_EQUAL(thCluster_12->series.timeseriesNumbers[year], + thCluster_11->series.timeseriesNumbers[year]); + BOOST_CHECK_EQUAL(thCluster_21->series.timeseriesNumbers[year], + thCluster_11->series.timeseriesNumbers[year]); } -BOOST_AUTO_TEST_CASE(two_areas_2_thermal_clusters_with_respectively_4_4_ready_made_ts___check_intra_modal_consistency_OK) +BOOST_AUTO_TEST_CASE( + two_areas_2_thermal_clusters_with_respectively_4_4_ready_made_ts___check_intra_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.intraModal |= timeSeriesThermal; - - // ============= - // Area 1 - // ============= - Area* area_1 = addAreaToStudy(study, "Area 1"); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - // ... Area 1 : thermal cluster 1 - auto thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); - thCluster_11->series->timeSeries.resize(4, 1); + study->parameters.intraModal |= timeSeriesThermal; - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); - // ============= - // Area 2 - // ============= - Area* area_2 = addAreaToStudy(study, "Area 2"); + // Area 1 : thermal cluster 1 + auto thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); + thCluster_11->series.timeSeries.resize(4, 1); - // ... Area 2 : thermal cluster 1 - auto thCluster_21 = addClusterToArea(area_2, "th-cluster-21"); - thCluster_21->series->timeSeries.resize(4, 1); + // Area 2 : thermal cluster 1 + auto thCluster_21 = addClusterToArea(area_2, "th-cluster-21"); + thCluster_21->series.timeSeries.resize(4, 1); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(Generate(*study)); + BOOST_CHECK(Generate(*study)); - // TS number checks - uint year = 0; - BOOST_CHECK_EQUAL(thCluster_21->series->timeseriesNumbers[0][year], thCluster_11->series->timeseriesNumbers[0][year]); + // TS number checks + uint year = 0; + BOOST_CHECK_EQUAL(thCluster_21->series.timeseriesNumbers[year], + thCluster_11->series.timeseriesNumbers[year]); } -BOOST_AUTO_TEST_CASE(two_areas_3_thermal_clusters_with_different_number_of_ready_made_ts___check_intra_modal_consistency_KO) +BOOST_AUTO_TEST_CASE( + two_areas_3_thermal_clusters_with_different_number_of_ready_made_ts___check_intra_modal_consistency_KO) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.intraModal |= timeSeriesThermal; - - // ============= - // Area 1 - // ============= - Area* area_1 = addAreaToStudy(study, "Area 1"); - - // ... Area 1 : thermal cluster 1 - auto thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); - thCluster_11->series->timeSeries.resize(4, 1); - // ... Area 1 : thermal cluster 2 - auto thCluster_12 = addClusterToArea(area_1, "th-cluster-12"); - thCluster_12->series->timeSeries.resize(4, 1); - - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - // ============= - // Area 2 - // ============= - Area* area_2 = addAreaToStudy(study, "Area 2"); + study->parameters.intraModal |= timeSeriesThermal; - // ... Area 2 : thermal cluster 1 - auto thCluster_21 = addClusterToArea(area_2, "th-cluster-21"); - thCluster_21->series->timeSeries.resize(3, 1); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + // Area 1 : thermal cluster 1 + auto thCluster_11 = addClusterToArea(area_1, "th-cluster-11"); + thCluster_11->series.timeSeries.resize(4, 1); + // Area 1 : thermal cluster 2 + auto thCluster_12 = addClusterToArea(area_1, "th-cluster-12"); + thCluster_12->series.timeSeries.resize(4, 1); + // Area 2 : thermal cluster 1 + auto thCluster_21 = addClusterToArea(area_2, "th-cluster-21"); + thCluster_21->series.timeSeries.resize(3, 1); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(not Generate(*study)); + BOOST_CHECK(not Generate(*study)); } -BOOST_AUTO_TEST_CASE(two_areas_3_renew_clusters_with_same_number_of_ready_made_ts___check_intra_modal_consistency_OK) +BOOST_AUTO_TEST_CASE( + two_areas_3_renew_clusters_with_same_number_of_ready_made_ts___check_intra_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.intraModal |= timeSeriesRenewable; - study->parameters.renewableGeneration.toClusters(); - - // ============= - // Area 1 - // ============= - Area* area_1 = addAreaToStudy(study, "Area 1"); - - // ... Area 1 : renewable cluster 1 - auto rnCluster_11 = addClusterToArea(area_1, "rn-cluster-11"); - rnCluster_11->series->timeSeries.resize(4, 1); - // ... Area 1 : renewable cluster 2 - auto rnCluster_12 = addClusterToArea(area_1, "rn-cluster-12"); - rnCluster_12->series->timeSeries.resize(4, 1); - - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - - // ============= - // Area 2 - // ============= - Area* area_2 = addAreaToStudy(study, "Area 2"); - // ... Area 2 : renewable cluster 1 - auto rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); - rnCluster_21->series->timeSeries.resize(4, 1); - - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - - BOOST_CHECK(Generate(*study)); - - // TS number checks - uint year = 0; - BOOST_CHECK_EQUAL(rnCluster_12->series->timeseriesNumbers[0][year], rnCluster_11->series->timeseriesNumbers[0][year]); - BOOST_CHECK_EQUAL(rnCluster_21->series->timeseriesNumbers[0][year], rnCluster_11->series->timeseriesNumbers[0][year]); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); + + study->parameters.intraModal |= timeSeriesRenewable; + study->parameters.renewableGeneration.toClusters(); + + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); + + // Area 1 : renewable cluster 1 + auto rnCluster_11 = addClusterToArea(area_1, "rn-cluster-11"); + rnCluster_11->series.timeSeries.resize(4, 1); + // Area 1 : renewable cluster 2 + auto rnCluster_12 = addClusterToArea(area_1, "rn-cluster-12"); + rnCluster_12->series.timeSeries.resize(4, 1); + // Area 2 : renewable cluster 1 + auto rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); + rnCluster_21->series.timeSeries.resize(4, 1); + + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + + BOOST_CHECK(Generate(*study)); + + // TS number checks + uint year = 0; + BOOST_CHECK_EQUAL(rnCluster_12->series.timeseriesNumbers[year], + rnCluster_11->series.timeseriesNumbers[year]); + BOOST_CHECK_EQUAL(rnCluster_21->series.timeseriesNumbers[year], + rnCluster_11->series.timeseriesNumbers[year]); } - -BOOST_AUTO_TEST_CASE(two_areas_2_renew_clusters_with_respectively_4_4_ready_made_ts___check_intra_modal_consistency_OK) +BOOST_AUTO_TEST_CASE( + two_areas_2_renew_clusters_with_respectively_4_4_ready_made_ts___check_intra_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.intraModal |= timeSeriesRenewable; - study->parameters.renewableGeneration.toClusters(); - - // ============= - // Area 1 - // ============= - Area* area_1 = addAreaToStudy(study, "Area 1"); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - // ... Area 1 : renewable cluster 1 - auto rnCluster_11 = addClusterToArea(area_1, "rn-cluster-11"); - rnCluster_11->series->timeSeries.resize(4, 1); - // ... Area 1 : renewable cluster 2 - auto rnCluster_12 = addClusterToArea(area_1, "rn-cluster-12"); - rnCluster_12->series->timeSeries.resize(4, 1); + study->parameters.intraModal |= timeSeriesRenewable; + study->parameters.renewableGeneration.toClusters(); - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); - // ============= - // Area 2 - // ============= - Area* area_2 = addAreaToStudy(study, "Area 2"); + // Area 1 : renewable cluster 1 + auto rnCluster_11 = addClusterToArea(area_1, "rn-cluster-11"); + rnCluster_11->series.timeSeries.resize(4, 1); + // Area 2 : renewable cluster 1 + auto rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); + rnCluster_21->series.timeSeries.resize(4, 1); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(Generate(*study)); + BOOST_CHECK(Generate(*study)); - // TS number checks - uint year = 0; - BOOST_CHECK_EQUAL(rnCluster_12->series->timeseriesNumbers[0][year], rnCluster_11->series->timeseriesNumbers[0][year]); + // TS number checks + uint year = 0; + BOOST_CHECK_EQUAL(rnCluster_21->series.timeseriesNumbers[year], + rnCluster_11->series.timeseriesNumbers[year]); } -BOOST_AUTO_TEST_CASE(two_areas_3_renew_clusters_with_different_number_of_ready_made_ts___check_intra_modal_consistency_KO) +BOOST_AUTO_TEST_CASE( + two_areas_3_renew_clusters_with_different_number_of_ready_made_ts___check_intra_modal_consistency_KO) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.intraModal |= timeSeriesRenewable; - study->parameters.renewableGeneration.toClusters(); - - // ============= - // Area 1 - // ============= - Area* area_1 = addAreaToStudy(study, "Area 1"); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - // ... Area 1 : renewable cluster 1 - auto rnCluster_11 = addClusterToArea(area_1, "rn-cluster-11"); - rnCluster_11->series->timeSeries.resize(4, 1); - // ... Area 1 : renewable cluster 2 - auto rnCluster_12 = addClusterToArea(area_1, "rn-cluster-12"); - rnCluster_12->series->timeSeries.resize(3, 1); // Caution : number of TS different from previous cluster + study->parameters.intraModal |= timeSeriesRenewable; + study->parameters.renewableGeneration.toClusters(); - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); - // ============= - // Area 2 - // ============= - Area* area_2 = addAreaToStudy(study, "Area 2"); + // Add 2 clusters to area 1 + auto rnCluster_11 = addClusterToArea(area_1, "rn-cluster-11"); + rnCluster_11->series.timeSeries.resize(4, 1); + auto rnCluster_12 = addClusterToArea(area_1, "rn-cluster-12"); + rnCluster_12->series.timeSeries + .resize(3, 1); // Caution : number of TS different from previous cluster - // ... Area 2 : renewable cluster 1 - auto rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); - rnCluster_21->series->timeSeries.resize(4, 1); + // Add a cluster to area 2 + auto rnCluster_21 = addClusterToArea(area_2, "rn-cluster-21"); + rnCluster_21->series.timeSeries.resize(4, 1); - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(not Generate(*study)); + BOOST_CHECK(not Generate(*study)); } // ======================= // Checks on inter-modal // ======================= -BOOST_AUTO_TEST_CASE(one_area__load_wind_thermal_are_turned_to_inter_modal__same_nb_of_ts____check_inter_modal_consistency_OK) +BOOST_AUTO_TEST_CASE( + one_area__load_wind_thermal_are_turned_to_inter_modal__same_nb_of_ts____check_inter_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesWind; - study->parameters.interModal |= timeSeriesThermal; - - // Area - Area* area = addAreaToStudy(study, "Area"); - - // ... Load - area->load.series->timeSeries.resize(5, 1); // Ready made TS for load - - // ... Wind - area->wind.series->timeSeries.resize(5, 1); // Ready made TS for wind - - // ... Thermal - study->parameters.timeSeriesToRefresh |= timeSeriesThermal; // Generated TS for thermal - study->parameters.nbTimeSeriesThermal = 5; - // ... ... clusters - auto thCluster_1 = addClusterToArea(area, "th-cluster-1"); - auto thCluster_2 = addClusterToArea(area, "th-cluster-2"); - - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - - BOOST_CHECK(Generate(*study)); - - // TS number checks - uint year = 0; - uint drawnTsNbForLoad = area->load.series->timeseriesNumbers[0][year]; - BOOST_CHECK_EQUAL(area->wind.series->timeseriesNumbers[0][year], drawnTsNbForLoad); - BOOST_CHECK_EQUAL(thCluster_1->series->timeseriesNumbers[0][year], drawnTsNbForLoad); - BOOST_CHECK_EQUAL(thCluster_2->series->timeseriesNumbers[0][year], drawnTsNbForLoad); -} - -BOOST_AUTO_TEST_CASE(one_area__load_wind_thermal_are_turned_to_inter_modal__same_nb_of_ts_except_1_for_load_check_inter_modal_consistency_OK) -{ - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesWind; - study->parameters.interModal |= timeSeriesThermal; + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesWind; + study->parameters.interModal |= timeSeriesThermal; - // Area - Area* area = addAreaToStudy(study, "Area"); + Area* area = addAreaToStudy(study, "Area"); - // ... Load - area->load.series->timeSeries.resize(1, 1); // Ready made TS for load + area->load.series.timeSeries.resize(5, 1); // Ready made TS for load + area->wind.series.timeSeries.resize(5, 1); // Ready made TS for wind - // ... Wind - area->wind.series->timeSeries.resize(5, 1); // Ready made TS for wind + // Thermal + study->parameters.timeSeriesToGenerate |= timeSeriesThermal; // Generated TS for thermal - // ... Thermal - study->parameters.timeSeriesToRefresh |= timeSeriesThermal; // Generated TS for thermal - study->parameters.nbTimeSeriesThermal = 5; - // ... ... clusters - auto thCluster_1 = addClusterToArea(area, "th-cluster-1"); - auto thCluster_2 = addClusterToArea(area, "th-cluster-2"); + study->parameters.nbTimeSeriesThermal = 5; + auto thCluster_1 = addClusterToArea(area, "th-cluster-1"); + auto thCluster_2 = addClusterToArea(area, "th-cluster-2"); - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(Generate(*study)); + TSGenerator::ResizeGeneratedTimeSeries(study->areas, study->parameters); + BOOST_CHECK(Generate(*study)); - // TS number checks - uint year = 0; - uint drawnTsNbForLoad = area->load.series->timeseriesNumbers[0][year]; - BOOST_CHECK_EQUAL(area->wind.series->timeseriesNumbers[0][year], drawnTsNbForLoad); - BOOST_CHECK_EQUAL(thCluster_1->series->timeseriesNumbers[0][year], drawnTsNbForLoad); - BOOST_CHECK_EQUAL(thCluster_2->series->timeseriesNumbers[0][year], drawnTsNbForLoad); + // TS number checks + uint year = 0; + uint drawnTsNbForLoad = area->load.series.timeseriesNumbers[year]; + BOOST_CHECK_EQUAL(area->wind.series.timeseriesNumbers[year], drawnTsNbForLoad); + BOOST_CHECK_EQUAL(thCluster_1->series.timeseriesNumbers[year], drawnTsNbForLoad); + BOOST_CHECK_EQUAL(thCluster_2->series.timeseriesNumbers[year], drawnTsNbForLoad); } -BOOST_AUTO_TEST_CASE(one_area__load_wind_thermal_are_turned_to_inter_modal__different_nb_of_ts____check_inter_modal_consistency_KO) +BOOST_AUTO_TEST_CASE( + one_area__load_wind_thermal_are_turned_to_inter_modal__same_nb_of_ts_except_1_for_load_check_inter_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesWind; - study->parameters.interModal |= timeSeriesThermal; + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesWind; + study->parameters.interModal |= timeSeriesThermal; - // Area - Area* area = addAreaToStudy(study, "Area"); + Area* area = addAreaToStudy(study, "Area"); - // ... Load - area->load.series->timeSeries.resize(5, 1); // Ready made TS for load + area->load.series.timeSeries.resize(1, 1); // Ready made TS for load + area->wind.series.timeSeries.resize(5, 1); // Ready made TS for wind - // ... Wind - area->wind.series->timeSeries.resize(5, 1); // Ready made TS for wind + // ... Thermal + study->parameters.timeSeriesToGenerate |= timeSeriesThermal; // Generated TS for thermal + study->parameters.nbTimeSeriesThermal = 5; + // ... ... clusters + auto thCluster_1 = addClusterToArea(area, "th-cluster-1"); + auto thCluster_2 = addClusterToArea(area, "th-cluster-2"); - // ... Thermal - study->parameters.timeSeriesToRefresh |= timeSeriesThermal; // Generated TS for thermal - study->parameters.nbTimeSeriesThermal = 4; - // ... ... clusters - auto thCluster_1 = addClusterToArea(area, "th-cluster-1"); - auto thCluster_2 = addClusterToArea(area, "th-cluster-2"); + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + TSGenerator::ResizeGeneratedTimeSeries(study->areas, study->parameters); + BOOST_CHECK(Generate(*study)); - BOOST_CHECK(not Generate(*study)); + // TS number checks + uint year = 0; + uint drawnTsNbForLoad = area->load.series.timeseriesNumbers[year]; + BOOST_CHECK_EQUAL(area->wind.series.timeseriesNumbers[year], drawnTsNbForLoad); + BOOST_CHECK_EQUAL(thCluster_1->series.timeseriesNumbers[year], drawnTsNbForLoad); + BOOST_CHECK_EQUAL(thCluster_2->series.timeseriesNumbers[year], drawnTsNbForLoad); } +BOOST_AUTO_TEST_CASE( + one_area__load_wind_thermal_are_turned_to_inter_modal__different_nb_of_ts____check_inter_modal_consistency_KO) +{ + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); + + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesWind; + study->parameters.interModal |= timeSeriesThermal; + + Area* area = addAreaToStudy(study, "Area"); -BOOST_AUTO_TEST_CASE(one_area__load_renewable_are_turned_to_inter_modal__same_nb_of_ts____check_inter_modal_consistency_OK) + area->load.series.timeSeries.resize(5, 1); // Ready made TS for load + area->wind.series.timeSeries.resize(5, 1); // Ready made TS for wind + + // Thermal + study->parameters.timeSeriesToGenerate |= timeSeriesThermal; // Generated TS for thermal + study->parameters.nbTimeSeriesThermal = 4; + // Add 2 clusters to area + auto thCluster_1 = addClusterToArea(area, "th-cluster-1"); + auto thCluster_2 = addClusterToArea(area, "th-cluster-2"); + + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + + TSGenerator::ResizeGeneratedTimeSeries(study->areas, study->parameters); + BOOST_CHECK(not Generate(*study)); +} + +BOOST_AUTO_TEST_CASE( + one_area__load_renewable_are_turned_to_inter_modal__same_nb_of_ts____check_inter_modal_consistency_OK) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - study->parameters.renewableGeneration.toClusters(); + study->parameters.renewableGeneration.toClusters(); - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesRenewable; + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesRenewable; - // Area - Area* area = addAreaToStudy(study, "Area"); + Area* area = addAreaToStudy(study, "Area"); - // ... Load - area->load.series->timeSeries.resize(5, 1); // Ready made TS for load + area->load.series.timeSeries.resize(5, 1); // Ready made TS for load - // ... Renewable - // ... ... clusters - auto rnCluster_1 = addClusterToArea(area, "rn-cluster-1"); - rnCluster_1->series->timeSeries.resize(5, 1); + auto rnCluster_1 = addClusterToArea(area, "rn-cluster-1"); + rnCluster_1->series.timeSeries.resize(5, 1); - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(Generate(*study)); + BOOST_CHECK(Generate(*study)); - // TS number checks - uint year = 0; - BOOST_CHECK_EQUAL(rnCluster_1->series->timeseriesNumbers[0][year], area->load.series->timeseriesNumbers[0][year]); + // TS number checks + uint year = 0; + BOOST_CHECK_EQUAL(rnCluster_1->series.timeseriesNumbers[year], + area->load.series.timeseriesNumbers[year]); } -BOOST_AUTO_TEST_CASE(one_area__load_renewable_are_turned_to_inter_modal__different_nb_of_ts____check_inter_modal_consistency_KO) +BOOST_AUTO_TEST_CASE( + one_area__load_renewable_are_turned_to_inter_modal__different_nb_of_ts____check_inter_modal_consistency_KO) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - study->parameters.renewableGeneration.toClusters(); + study->parameters.renewableGeneration.toClusters(); - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesRenewable; + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesRenewable; - // Area - Area* area = addAreaToStudy(study, "Area"); + Area* area = addAreaToStudy(study, "Area"); - // ... Load - area->load.series->timeSeries.resize(5, 1); // Ready made TS for load + area->load.series.timeSeries.resize(5, 1); // Ready made TS for load - // ... Renewable - // ... ... clusters - auto rnCluster_1 = addClusterToArea(area, "rn-cluster-1"); - rnCluster_1->series->timeSeries.resize(4, 1); + auto rnCluster_1 = addClusterToArea(area, "rn-cluster-1"); + rnCluster_1->series.timeSeries.resize(4, 1); - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(not Generate(*study)); + BOOST_CHECK(not Generate(*study)); } -BOOST_AUTO_TEST_CASE(one_area__load_renewable_are_turned_to_inter_modal_with_respectively_5_1_TS____check_inter_modal_consistency_KO) +BOOST_AUTO_TEST_CASE( + one_area__load_renewable_are_turned_to_inter_modal_with_respectively_5_1_TS____check_inter_modal_consistency_KO) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); - study->parameters.renewableGeneration.toClusters(); + study->parameters.renewableGeneration.toClusters(); - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesRenewable; + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesRenewable; - // Area - Area* area = addAreaToStudy(study, "Area"); + Area* area = addAreaToStudy(study, "Area"); - // ... Load - area->load.series->timeSeries.resize(5, 1); // Ready made TS for load + area->load.series.timeSeries.resize(5, 1); // Ready made TS for load - // ... Renewable - // ... ... clusters - auto rnCluster_1 = addClusterToArea(area, "rn-cluster-1"); - rnCluster_1->series->timeSeries.resize(1, 1); + auto rnCluster_1 = addClusterToArea(area, "rn-cluster-1"); + rnCluster_1->series.timeSeries.resize(1, 1); - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - BOOST_CHECK(Generate(*study)); + BOOST_CHECK(Generate(*study)); } // ======================================================== @@ -599,118 +550,147 @@ BOOST_AUTO_TEST_CASE(one_area__load_renewable_are_turned_to_inter_modal_with_res BOOST_AUTO_TEST_CASE(load_wind_thermal_in_intra_and_inter_modal____check_all_ts_numbers_are_equal) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - // Intra-modal for load, wind and thermal - study->parameters.intraModal |= timeSeriesLoad; - study->parameters.intraModal |= timeSeriesWind; - study->parameters.intraModal |= timeSeriesThermal; - - // Inter-modal for load, wind and thermal - study->parameters.interModal |= timeSeriesLoad; - study->parameters.interModal |= timeSeriesWind; - study->parameters.interModal |= timeSeriesThermal; - - // Generated TS for thermal - study->parameters.timeSeriesToRefresh |= timeSeriesThermal; - study->parameters.nbTimeSeriesThermal = 5; - - // =============== - // Area 1 - // =============== - Area* area_1 = addAreaToStudy(study, "Area 1"); - // ... Load - area_1->load.series->timeSeries.resize(5, 1); // Ready made TS for load - // ... Wind - area_1->wind.series->timeSeries.resize(5, 1); // Ready made TS for wind - // ... Thermal - auto thCluster_area_1 = addClusterToArea(area_1, "th-cluster-area-1"); - - area_1->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - - // =============== - // Area 2 - // =============== - Area* area_2 = addAreaToStudy(study, "Area 2"); - // ... Load - area_2->load.series->timeSeries.resize(5, 1); // Ready made TS for load - // ... Wind - area_2->wind.series->timeSeries.resize(5, 1); // Ready made TS for wind - // ... Thermal - auto thCluster_area_2 = addClusterToArea(area_2, "th-cluster-area-2"); - - area_2->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - - BOOST_CHECK(Generate(*study)); - - // TS number checks : all intra-modal & inter-modal modes have get the same ts number : - // - inside an area - // - for all areas - uint year = 0; - uint referenceLoadTsNumber = area_1->load.series->timeseriesNumbers[0][year]; - BOOST_CHECK_EQUAL(area_2->load.series->timeseriesNumbers[0][year], referenceLoadTsNumber); - BOOST_CHECK_EQUAL(area_1->wind.series->timeseriesNumbers[0][year], referenceLoadTsNumber); - BOOST_CHECK_EQUAL(area_2->wind.series->timeseriesNumbers[0][year], referenceLoadTsNumber); - BOOST_CHECK_EQUAL(thCluster_area_1->series->timeseriesNumbers[0][year], referenceLoadTsNumber); - BOOST_CHECK_EQUAL(thCluster_area_2->series->timeseriesNumbers[0][year], referenceLoadTsNumber); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); + + // Intra-modal for load, wind and thermal + study->parameters.intraModal |= timeSeriesLoad; + study->parameters.intraModal |= timeSeriesWind; + study->parameters.intraModal |= timeSeriesThermal; + + // Inter-modal for load, wind and thermal + study->parameters.interModal |= timeSeriesLoad; + study->parameters.interModal |= timeSeriesWind; + study->parameters.interModal |= timeSeriesThermal; + + // Generated TS for thermal + study->parameters.timeSeriesToGenerate |= timeSeriesThermal; // Generated TS for thermal + study->parameters.nbTimeSeriesThermal = 5; + + Area* area_1 = addAreaToStudy(study, "Area 1"); + Area* area_2 = addAreaToStudy(study, "Area 2"); + + // Acions on area 1 + area_1->load.series.timeSeries.resize(5, 1); // Ready made TS for load + area_1->wind.series.timeSeries.resize(5, 1); // Ready made TS for wind + auto thCluster_area_1 = addClusterToArea(area_1, "th-cluster-area-1"); + + // Acions on area 2 + area_2->load.series.timeSeries.resize(5, 1); // Ready made TS for load + area_2->wind.series.timeSeries.resize(5, 1); // Ready made TS for wind + auto thCluster_area_2 = addClusterToArea(area_2, "th-cluster-area-2"); + + study->areas.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + + TSGenerator::ResizeGeneratedTimeSeries(study->areas, study->parameters); + BOOST_CHECK(Generate(*study)); + + // TS number checks : all intra-modal & inter-modal modes have get the same ts number : + // - inside an area + // - for all areas + uint year = 0; + uint referenceLoadTsNumber = area_1->load.series.timeseriesNumbers[year]; + BOOST_CHECK_EQUAL(area_2->load.series.timeseriesNumbers[year], referenceLoadTsNumber); + BOOST_CHECK_EQUAL(area_1->wind.series.timeseriesNumbers[year], referenceLoadTsNumber); + BOOST_CHECK_EQUAL(area_2->wind.series.timeseriesNumbers[year], referenceLoadTsNumber); + BOOST_CHECK_EQUAL(thCluster_area_1->series.timeseriesNumbers[year], referenceLoadTsNumber); + BOOST_CHECK_EQUAL(thCluster_area_2->series.timeseriesNumbers[year], referenceLoadTsNumber); } BOOST_AUTO_TEST_CASE(check_all_drawn_ts_numbers_are_bounded_between_0_and_nb_of_ts) { - // Creating a study - auto study = std::make_shared(); - initializeStudy(study); - - // Generated TS for everyone - study->parameters.timeSeriesToRefresh |= timeSeriesLoad; - study->parameters.timeSeriesToRefresh |= timeSeriesWind; - study->parameters.timeSeriesToRefresh |= timeSeriesSolar; - study->parameters.timeSeriesToRefresh |= timeSeriesHydro; - study->parameters.timeSeriesToRefresh |= timeSeriesThermal; - - // Number of TS for each energy - uint loadNumberOfTs = 10; - uint windNumberOfTs = 3; - uint solarNumberOfTs = 7; - uint hydroNumberOfTs = 9; - uint thermalNumberOfTs = 5; - uint binding_constraints_number_of_TS = 42; - - study->parameters.nbTimeSeriesLoad = loadNumberOfTs; - study->parameters.nbTimeSeriesWind = windNumberOfTs; - study->parameters.nbTimeSeriesSolar = solarNumberOfTs; - study->parameters.nbTimeSeriesHydro = hydroNumberOfTs; - study->parameters.nbTimeSeriesThermal = thermalNumberOfTs; - - Area* area = addAreaToStudy(study, "Area"); - - // ... Thermal - auto thCluster = addClusterToArea(area, "th-cluster"); - - area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + // Creating a study + auto study = std::make_shared(); + initializeStudy(study); + + // Generated TS for everyone + study->parameters.timeSeriesToGenerate |= timeSeriesLoad; + study->parameters.timeSeriesToGenerate |= timeSeriesWind; + study->parameters.timeSeriesToGenerate |= timeSeriesSolar; + study->parameters.timeSeriesToGenerate |= timeSeriesHydro; + study->parameters.timeSeriesToGenerate |= timeSeriesThermal; + + // Number of TS for each energy + uint loadNumberOfTs = 10; + uint windNumberOfTs = 3; + uint solarNumberOfTs = 7; + uint hydroNumberOfTs = 9; + uint thermalNumberOfTs = 5; + uint binding_constraints_number_of_TS = 42; + + study->parameters.nbTimeSeriesLoad = loadNumberOfTs; + study->parameters.nbTimeSeriesWind = windNumberOfTs; + study->parameters.nbTimeSeriesSolar = solarNumberOfTs; + study->parameters.nbTimeSeriesHydro = hydroNumberOfTs; + study->parameters.nbTimeSeriesThermal = thermalNumberOfTs; + + Area* area = addAreaToStudy(study, "Area"); + + auto thCluster = addClusterToArea(area, "th-cluster"); + + area->resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); + auto bc = study->bindingConstraints.add("dummy"); bc->group("dummy"); study->bindingConstraintsGroups.add(bc->group()); bc->RHSTimeSeries().resize(42, 1); - study->bindingConstraintsGroups.resizeAllTimeseriesNumbers(1 + study->runtime->rangeLimits.year[rangeEnd]); - - BOOST_CHECK(Generate(*study)); - - // TS number checks : each energy drawn ts numbers are up-bounded with the number of TS of the related energy - uint year = 0; - uint loadTsNumber = area->load.series->timeseriesNumbers[0][year]; - uint windTsNumber = area->wind.series->timeseriesNumbers[0][year]; - uint solarTsNumber = area->solar.series->timeseriesNumbers[0][year]; - uint hydroTsNumber = area->hydro.series->timeseriesNumbers[0][year]; - uint thermalTsNumber = thCluster->series->timeseriesNumbers[0][year]; - auto binding_constraints_TS_number = study->bindingConstraintsGroups["dummy"]->timeseriesNumbers[0][year]; - - BOOST_CHECK(loadTsNumber < loadNumberOfTs); - BOOST_CHECK(windTsNumber < windNumberOfTs); - BOOST_CHECK(solarTsNumber < solarNumberOfTs); - BOOST_CHECK(hydroTsNumber < hydroNumberOfTs); - BOOST_CHECK(thermalTsNumber < thermalNumberOfTs); + study->bindingConstraintsGroups.resizeAllTimeseriesNumbers( + 1 + study->runtime->rangeLimits.year[rangeEnd]); + + TSGenerator::ResizeGeneratedTimeSeries(study->areas, study->parameters); + BOOST_CHECK(Generate(*study)); + + // TS number checks : each energy drawn ts numbers are up-bounded with the number of TS of the + // related energy + uint year = 0; + uint loadTsNumber = area->load.series.timeseriesNumbers[year]; + uint windTsNumber = area->wind.series.timeseriesNumbers[year]; + uint solarTsNumber = area->solar.series.timeseriesNumbers[year]; + uint hydroTsNumber = area->hydro.series->timeseriesNumbers[year]; + uint thermalTsNumber = thCluster->series.timeseriesNumbers[year]; + auto binding_constraints_TS_number = study->bindingConstraintsGroups["dummy"] + ->timeseriesNumbers[year]; + + BOOST_CHECK(loadTsNumber < loadNumberOfTs); + BOOST_CHECK(windTsNumber < windNumberOfTs); + BOOST_CHECK(solarTsNumber < solarNumberOfTs); + BOOST_CHECK(hydroTsNumber < hydroNumberOfTs); + BOOST_CHECK(thermalTsNumber < thermalNumberOfTs); BOOST_CHECK_LT(binding_constraints_TS_number, binding_constraints_number_of_TS); -} \ No newline at end of file +} + +BOOST_AUTO_TEST_CASE(split_string_ts_cluster_gen) +{ + char delimiter1 = ';'; + char delimiter2 = '.'; + + using stringPair = std::pair; + std::vector v; + + // only one pair of area cluster + v = splitStringIntoPairs("abc.def", delimiter1, delimiter2); + BOOST_CHECK(v[0] == stringPair("abc", "def")); + + // two pairs + v = splitStringIntoPairs("abc.def;ghi.jkl", delimiter1, delimiter2); + BOOST_CHECK(v[0] == stringPair("abc", "def")); + BOOST_CHECK(v[1] == stringPair("ghi", "jkl")); + + // first pair isn't valid + v = splitStringIntoPairs("abcdef;ghi.jkl", delimiter1, delimiter2); + BOOST_CHECK(v[0] == stringPair("ghi", "jkl")); + + // second pair isn't valid + v = splitStringIntoPairs("abc.def;ghijkl", delimiter1, delimiter2); + BOOST_CHECK(v[0] == stringPair("abc", "def")); + + // no semi colon + v = splitStringIntoPairs("abc.def.ghi.jkl", delimiter1, delimiter2); + BOOST_CHECK(v[0] == stringPair("abc", "def.ghi.jkl")); + + // no separator + v.clear(); + v = splitStringIntoPairs("abcdef", delimiter1, delimiter2); + BOOST_CHECK(v.empty()); +} diff --git a/src/tests/src/solver/utils/CMakeLists.txt b/src/tests/src/solver/utils/CMakeLists.txt new file mode 100644 index 0000000000..b3331c6249 --- /dev/null +++ b/src/tests/src/solver/utils/CMakeLists.txt @@ -0,0 +1,20 @@ +set(src_utils "${CMAKE_SOURCE_DIR}/solver/utils") + +set(EXECUTABLE_NAME tests-basis-status) +add_executable(${EXECUTABLE_NAME} basis_status.cpp) + + +target_include_directories(${EXECUTABLE_NAME} + PRIVATE + "${src_utils}" # basis_status_impl.h is private +) + +target_link_libraries(${EXECUTABLE_NAME} + PRIVATE + Boost::unit_test_framework + ortools::ortools + Antares::solverUtils +) + +add_test(NAME test-basis-status COMMAND ${EXECUTABLE_NAME}) +set_property(TEST test-basis-status PROPERTY LABELS unit) diff --git a/src/tests/src/solver/utils/basis_status.cpp b/src/tests/src/solver/utils/basis_status.cpp new file mode 100644 index 0000000000..292dc56c3c --- /dev/null +++ b/src/tests/src/solver/utils/basis_status.cpp @@ -0,0 +1,72 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#define BOOST_TEST_MODULE test adequacy patch functions + +#define WIN32_LEAN_AND_MEAN + +#include + +#include + +#include "basis_status_impl.h" +#include "ortools/linear_solver/linear_solver.h" + +using namespace operations_research; + +namespace Test +{ +class BasisStatus +{ +public: + BasisStatus(const Antares::Optimization::BasisStatus& b): + StatutDesVariables(b.impl->StatutDesVariables), + StatutDesContraintes(b.impl->StatutDesContraintes) + { + } + + using Status = operations_research::MPSolver::BasisStatus; + const std::vector& StatutDesVariables; + const std::vector& StatutDesContraintes; +}; +} // namespace Test + +BOOST_AUTO_TEST_CASE(basisStatusExtract) +{ + // CLP_LINEAR_PROGRAMMING should be always available + MPSolver solver("foo", MPSolver::CLP_LINEAR_PROGRAMMING); + auto x = solver.MakeNumVar(0, 1, "x"); + auto c = solver.MakeRowConstraint(0, 2, "c"); + auto obj = solver.MutableObjective(); + obj->SetCoefficient(x, 1); + c->SetCoefficient(x, 1); + Antares::Optimization::BasisStatus status; + solver.Solve(); + status.extractBasis(&solver); + + // Variables + Test::BasisStatus test(status); + BOOST_CHECK_EQUAL(test.StatutDesVariables.size(), 1); + BOOST_CHECK_EQUAL(test.StatutDesVariables[0], MPSolver::AT_LOWER_BOUND); + + // Constraints + BOOST_CHECK_EQUAL(test.StatutDesContraintes.size(), 1); + BOOST_CHECK_EQUAL(test.StatutDesContraintes[0], MPSolver::BASIC); +} diff --git a/src/tests/src/utils/CMakeLists.txt b/src/tests/src/utils/CMakeLists.txt index bc7f9bc1d7..fe3f0a00df 100644 --- a/src/tests/src/utils/CMakeLists.txt +++ b/src/tests/src/utils/CMakeLists.txt @@ -1,11 +1,11 @@ add_library(test_utils_unit - utils.cpp - utils.h + files-system.cpp + files-system.h ) target_include_directories( test_utils_unit - PUBLIC + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ) diff --git a/src/tests/src/utils/files-system.cpp b/src/tests/src/utils/files-system.cpp new file mode 100644 index 0000000000..f6097ee82b --- /dev/null +++ b/src/tests/src/utils/files-system.cpp @@ -0,0 +1,72 @@ +#include "files-system.h" + +namespace fs = std::filesystem; + +fs::path generateAndCreateDirName(const std::string& dirName) +{ + fs::path working_dir = fs::temp_directory_path() / dirName; + fs::remove_all(working_dir); + fs::create_directories(working_dir); + return working_dir; +} + +void createFolder(const std::string& path, const std::string& folder_name) +{ + fs::path folder_path = fs::path(path.c_str()) / folder_name.c_str(); + + try + { + fs::create_directory(folder_path); + } + catch (const fs::filesystem_error& e) + { + std::cerr << "Exception creating folder '" + folder_name + "': " + e.what() + "\n"; + } +} + +void createFile(const std::string& folder_path, const std::string& file_name) +{ + // Construct the full path to the file + fs::path path = fs::path(folder_path.c_str()) / file_name.c_str(); + + // Create an output file stream + std::ofstream outputFile(path); + + try + { + if (outputFile.is_open()) + { + // File was successfully created and is open + outputFile << "This is a sample content." << std::endl; + outputFile.close(); + std::cout << "File " + file_name + " is created in " + folder_path + "\n"; + } + else + { + // Failed to create or open the file + std::error_code ec = std::make_error_code(std::errc::io_error); + throw fs::filesystem_error("Failed to create the file.", ec); + } + } + catch (const fs::filesystem_error& e) + { + std::cerr << "Error creating file: " << file_name << "/" << e.what() << "\n"; + } +} + +void removeFolder(std::string& path, std::string& folder_name) +{ + fs::path folder_path = fs::path(path.c_str()) / folder_name.c_str(); + if (fs::exists(folder_path)) + { + try + { + fs::remove_all(folder_path); + std::cout << "Folder " + folder_name + " at " + folder_path.string() + " deleted.\n"; + } + catch (const fs::filesystem_error& e) + { + std::cerr << "Exception deleting folder '" + folder_name + "': " + e.what() + "\n"; + } + } +} diff --git a/src/tests/src/utils/files-system.h b/src/tests/src/utils/files-system.h new file mode 100644 index 0000000000..092b498350 --- /dev/null +++ b/src/tests/src/utils/files-system.h @@ -0,0 +1,36 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#pragma once + +#include +#include +#include +#include + +// The following macro is used due to linking issues with +#define CREATE_TMP_DIR_BASED_ON_TEST_NAME() \ + generateAndCreateDirName(boost::unit_test::framework::current_test_case().p_name); + +std::filesystem::path generateAndCreateDirName(const std::string&); + +void createFolder(const std::string& path, const std::string& folder_name); +void createFile(const std::string& folder_path, const std::string& file_name); +void removeFolder(std::string& path, std::string& folder_name); diff --git a/src/tests/src/utils/utils.cpp b/src/tests/src/utils/utils.cpp deleted file mode 100644 index 4fd0fe735e..0000000000 --- a/src/tests/src/utils/utils.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "utils.h" - -namespace fs = std::filesystem; - -fs::path generateAndCreateDirName(const std::string& dirName) -{ - fs::path working_dir = fs::temp_directory_path() / dirName; - fs::remove_all(working_dir); - fs::create_directories(working_dir); - return working_dir; -} diff --git a/src/tests/src/utils/utils.h b/src/tests/src/utils/utils.h deleted file mode 100644 index 9c7e70367f..0000000000 --- a/src/tests/src/utils/utils.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include - -// The following macro is used due to linking issues with -#define CREATE_TMP_DIR_BASED_ON_TEST_NAME() generateAndCreateDirName(boost::unit_test::framework::current_test_case().p_name); - -std::filesystem::path generateAndCreateDirName(const std::string&); diff --git a/src/tools/CMakeLists.txt b/src/tools/CMakeLists.txt index 90f2afcee6..4e643ed703 100644 --- a/src/tools/CMakeLists.txt +++ b/src/tools/CMakeLists.txt @@ -1,9 +1,8 @@ add_subdirectory(batchrun) add_subdirectory(finder) add_subdirectory(updater) -add_subdirectory(cleaner) add_subdirectory(yby-aggregator) add_subdirectory(config) add_subdirectory(vacuum) - add_subdirectory(kirchhoff-cbuilder) +add_subdirectory(ts-generator) diff --git a/src/tools/batchrun/CMakeLists.txt b/src/tools/batchrun/CMakeLists.txt index 3656f3d28d..1b80fc1356 100644 --- a/src/tools/batchrun/CMakeLists.txt +++ b/src/tools/batchrun/CMakeLists.txt @@ -25,7 +25,7 @@ endif(WIN32) -set(execname "antares-${ANTARES_PRG_VERSION}-batchrun") +set(execname "antares-batchrun") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-batchrun DESTINATION bin) @@ -36,11 +36,14 @@ INSTALL(EXPORT antares-batchrun ) set(BATCHRUN_LIBS - antares-core #local.h + antares-core yuni-static-core ${CMAKE_THREADS_LIBS_INIT} Antares::args_helper Antares::study + Antares::resources + Antares::locale + Antares::locator ) target_link_libraries(${execname} diff --git a/src/tools/batchrun/main.cpp b/src/tools/batchrun/main.cpp index 8cf5a97261..2ae0bc03e1 100644 --- a/src/tools/batchrun/main.cpp +++ b/src/tools/batchrun/main.cpp @@ -1,43 +1,43 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include -#include -#include -#include #include -#include +#include +#include + #include -#include +#include +#include + +#include #include -#include -#include +#include +#include +#include +#include +#include +#include +#include "antares/antares/antares.h" +#include "antares/locator/locator.h" + #ifdef YUNI_OS_WINDOWS #include #endif @@ -45,12 +45,14 @@ using namespace Yuni; using namespace Antares; +namespace fs = std::filesystem; + namespace // anonymous { -class MyStudyFinder final : public Data::StudyFinder +class MyStudyFinder final: public Data::StudyFinder { public: - void onStudyFound(const String& folder, Data::Version) override + void onStudyFound(const String& folder, const Data::StudyVersion&) override { logs.info() << "Found: " << folder; list.push_back(folder); @@ -84,7 +86,8 @@ int main(int argc, char* argv[]) Antares::Resources::Initialize(argc, argv, true); // options - String optInput; + std::string optInput; + std::string ortoolsSolver; bool optNoTSImport = false; bool optIgnoreAllConstraints = false; bool optForceExpansion = false; @@ -95,6 +98,7 @@ int main(int argc, char* argv[]) bool optNoOutput = false; bool optParallel = false; bool optVerbose = false; + bool ortoolsUsed = false; Nullable optYears; Nullable optSolver; Nullable optName; @@ -113,36 +117,59 @@ int main(int argc, char* argv[]) // Simulation mode options.addParagraph("\nSimulation mode"); - options.addFlag( - optForceExpansion, ' ', "economy", "Force the simulation(s) in expansion mode"); + options.addFlag(optForceExpansion, + ' ', + "economy", + "Force the simulation(s) in expansion mode"); options.addFlag(optForceEconomy, ' ', "economy", "Force the simulation(s) in economy mode"); - options.addFlag( - optForceAdequacy, ' ', "adequacy", "Force the simulation(s) in adequacy mode"); + options.addFlag(optForceAdequacy, + ' ', + "adequacy", + "Force the simulation(s) in adequacy mode"); options.addParagraph("\nParameters"); options.add(optName, 'n', "name", "Set the name of the new simulation outputs"); options.add(optYears, 'y', "year", "Override the number of MC years"); options.addFlag(optForce, 'f', "force", "Ignore all warnings at loading"); - options.addFlag( - optNoOutput, ' ', "no-output", "Do not write the results in the output folder"); + options.addFlag(optNoOutput, + ' ', + "no-output", + "Do not write the results in the output folder"); options.addFlag(optYearByYear, ' ', "year-by-year", "Force the writing of the result output for each year"); options.addParagraph("\nOptimization"); - options.addFlag( - optNoTSImport, ' ', "no-ts-import", "Do not import timeseries into the input folder."); + options.addFlag(optNoTSImport, + ' ', + "no-ts-import", + "Do not import timeseries into the input folder."); options.addFlag(optIgnoreAllConstraints, ' ', "no-constraints", "Ignore all constraints"); options.addParagraph("\nExtras"); options.add(optSolver, ' ', "solver", "Specify the antares-solver location"); - options.addFlag( - optParallel, 'p', "parallel", "Enable the parallel computation of MC years"); + options.addFlag(optParallel, + 'p', + "parallel", + "Enable the parallel computation of MC years"); options.add(optForceParallel, ' ', "force-parallel", "Override the max number of years computed simultaneously"); + + // add option for ortools use + // --use-ortools + options.addFlag(ortoolsUsed, ' ', "use-ortools", "Use ortools library to launch solver"); + + //--ortools-solver + options.add(ortoolsSolver, + ' ', + "ortools-solver", + "Ortools solver used for simulation (only available with use-ortools " + "option)\nAvailable solver list : " + + availableOrToolsSolversString()); + options.remainingArguments(optInput); // Version options.addParagraph("\nMisc."); @@ -151,7 +178,9 @@ int main(int argc, char* argv[]) options.addFlag(optVerbose, ' ', "verbose", "Displays study runs outputs"); if (options(argc, argv) == GetOpt::ReturnCode::error) + { return options.errors() ? 1 : 0; + } if (optVersion) { @@ -176,163 +205,225 @@ int main(int argc, char* argv[]) logs.error() << "contradictory options: --economy and --adequacy"; return EXIT_FAILURE; } - } - // Source Folder - logs.debug() << "Folder : `" << optInput << '`'; + if (ortoolsUsed) + { + const auto availableSolvers = getAvailableOrtoolsSolverName(); + if (auto it = std::find(availableSolvers.begin(), + availableSolvers.end(), + ortoolsSolver); + it == availableSolvers.end()) + { + logs.error() << "Please specify a solver using --ortools-solver. Available solvers " + << availableOrToolsSolversString() << ""; + return EXIT_FAILURE; + } + } - String solver; - if (optSolver.empty()) - { - Solver::FindLocation(solver); - if (solver.empty()) + // Source Folder + logs.debug() << "Folder : `" << optInput << '`'; + + String solver; + if (optSolver.empty()) { - logs.fatal() << "The solver has not been found"; - return EXIT_FAILURE; + Solver::FindLocation(solver); + if (solver.empty()) + { + logs.fatal() << "The solver has not been found"; + return EXIT_FAILURE; + } } - } - else - { - String tmp; - IO::MakeAbsolute(tmp, *optSolver); - IO::Normalize(solver, tmp); - if (not IO::File::Exists(solver)) + else { - logs.fatal() << "The solver has not been found. specify --solver=" << solver; - return EXIT_FAILURE; + std::string tmp = *optSolver; + fs::path solverPath = fs::absolute(tmp).lexically_normal(); + if (!fs::exists(solverPath)) + { + logs.fatal() << "The solver has not been found. specify --solver=" << solver; + return EXIT_FAILURE; + } } - } - logs.info() << " Solver: '" << solver << "'"; - logs.info(); - logs.info(); - logs.info() << "Searching for studies..."; - logs.info(); - MyStudyFinder finder; - finder.lookup(optInput); - finder.wait(); + logs.info() << " Solver: '" << solver << "'"; + logs.info(); + logs.info(); + logs.info() << "Searching for studies..."; + logs.info(); + MyStudyFinder finder; + finder.lookup(optInput); + finder.wait(); - if (not finder.list.empty()) - { - if (finder.list.size() > 1) - logs.info() << "Found " << finder.list.size() << " studyies"; - else - logs.info() << "Found 1 study"; - logs.info() << "Starting..."; - - if (!(!optName)) + if (not finder.list.empty()) { - String name; - name = *optName; - name.replace("\"", "\\\""); - *optName = name; - } + if (finder.list.size() > 1) + { + logs.info() << "Found " << finder.list.size() << " studyies"; + } + else + { + logs.info() << "Found 1 study"; + } + logs.info() << "Starting..."; - // The folder that contains the solver - String dirname; - IO::ExtractFilePath(dirname, solver); + if (!(!optName)) + { + String name; + name = *optName; + name.replace("\"", "\\\""); + *optName = name; + } - String cmd; + // The folder that contains the solver + String dirname; + IO::parent_path(dirname, solver); - uint studyIndx = 0; - foreach (auto& studypath, finder.list) - { - ++studyIndx; + String cmd; + + uint studyIndx = 0; + foreach (auto& studypath, finder.list) + { + ++studyIndx; - logs.info(); - if (optVerbose) logs.info(); + if (optVerbose) + { + logs.info(); + } - logs.checkpoint() << "Running simulation: `" << studypath << "` (" << studyIndx << '/' - << (uint)finder.list.size() << ')'; - if (optVerbose) - logs.debug(); + logs.checkpoint() << "Running simulation: `" << studypath << "` (" << studyIndx + << '/' << (uint)finder.list.size() << ')'; + if (optVerbose) + { + logs.debug(); + } - cmd.clear(); - if (not System::windows) - cmd << "nice "; - else - cmd << "call "; // why is it required for working ??? - cmd << "\"" << solver << "\""; - if (optForce) - cmd << " --force"; - if (optForceExpansion) - cmd << " --economy"; - if (optForceEconomy) - cmd << " --economy"; - if (optForceAdequacy) - cmd << " --adequacy"; - if (!(!optName)) - cmd << " --name=\"" << *optName << "\""; - if (!(!optYears)) - cmd << " --year=" << *optYears; - if (optNoOutput) - cmd << " --no-output"; - if (optYearByYear) - cmd << " --year-by-year"; - if (optNoTSImport) - cmd << " --no-ts-import"; - if (optIgnoreAllConstraints) - cmd << " --no-constraints"; - if (optParallel) - cmd << " --parallel"; - if (!(!optForceParallel)) - cmd << " --force-parallel=" << *optForceParallel; - cmd << " \"" << studypath << "\""; - if (!optVerbose) - cmd << sendToNull(); - - // Changing the current working directory - IO::Directory::Current::Set(dirname); - // Executing the converter - if (optVerbose) - logs.info() << "Executing " << cmd; + cmd.clear(); + if (not System::windows) + { + cmd << "nice "; + } + else + { + cmd << "call "; // why is it required for working ??? + } + cmd << "\"" << solver << "\""; + if (optForce) + { + cmd << " --force"; + } + if (optForceExpansion) + { + cmd << " --economy"; + } + if (optForceEconomy) + { + cmd << " --economy"; + } + if (optForceAdequacy) + { + cmd << " --adequacy"; + } + if (!(!optName)) + { + cmd << " --name=\"" << *optName << "\""; + } + if (!(!optYears)) + { + cmd << " --year=" << *optYears; + } + if (optNoOutput) + { + cmd << " --no-output"; + } + if (optYearByYear) + { + cmd << " --year-by-year"; + } + if (optNoTSImport) + { + cmd << " --no-ts-import"; + } + if (optIgnoreAllConstraints) + { + cmd << " --no-constraints"; + } + if (optParallel) + { + cmd << " --parallel"; + } + if (optForceParallel) + { + cmd << " --force-parallel=" << *optForceParallel; + } + if (ortoolsUsed) + { + cmd << " --use-ortools --ortools-solver=" << ortoolsSolver; + } - // Execute the command - int cmd_return_code = system(cmd.c_str()); + cmd << " \"" << studypath << "\""; + if (!optVerbose) + { + cmd << sendToNull(); + } - if (cmd_return_code != 0) - logs.error() << "An error occured."; - else - logs.info() << "Success."; + // Changing the current working directory + IO::Directory::Current::Set(dirname); + // Executing the converter + if (optVerbose) + { + logs.info() << "Executing " << cmd; + } - if (cmd_return_code == -1) - { -#ifdef YUNI_OS_WINDOWS - switch (errno) + // Execute the command + int cmd_return_code = system(cmd.c_str()); + + if (cmd_return_code != 0) + { + logs.error() << "An error occured."; + } + else { - case E2BIG: - logs.error() << "Argument list (which is system dependent) is too big"; - break; - case ENOENT: - logs.error() << "Command interpreter cannot be found"; - break; - case ENOEXEC: - logs.error() - << "Command-interpreter file has invalid format and is not executable"; - break; - case ENOMEM: - logs.error() << "Not enough memory is available to execute command"; - break; + logs.info() << "Success."; } + + if (cmd_return_code == -1) + { +#ifdef YUNI_OS_WINDOWS + switch (errno) + { + case E2BIG: + logs.error() << "Argument list (which is system dependent) is too big"; + break; + case ENOENT: + logs.error() << "Command interpreter cannot be found"; + break; + case ENOEXEC: + logs.error() + << "Command-interpreter file has invalid format and is not executable"; + break; + case ENOMEM: + logs.error() << "Not enough memory is available to execute command"; + break; + } #endif + } } - } - logs.info() << "Done."; + logs.info() << "Done."; - // Time interval - if (optVerbose) + // Time interval + if (optVerbose) + { + logs.debug(); + logs.debug(); + } + } + else { - logs.debug(); - logs.debug(); + logs.fatal() << "No study has been found."; + return 4; } - } - else - { - logs.fatal() << "No study has been found."; - return 4; - } - return 0; + return 0; + } } diff --git a/src/tools/cleaner/CMakeLists.txt b/src/tools/cleaner/CMakeLists.txt deleted file mode 100644 index ea87db4a79..0000000000 --- a/src/tools/cleaner/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ - -OMESSAGE("antares-study-cleaner") - - -# Le main -Set(SRCS main.cpp - ) - -if(WIN32 OR WIN64) - FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/cleaner.o") - CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/cleaner.rc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/win32/cleaner.rc") - FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/cleaner.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/cleaner.rc") -endif() - - -set(execname "antares-${ANTARES_PRG_VERSION}-study-cleaner") -add_executable(${execname} ${SRCS}) -install(TARGETS ${execname} EXPORT antares-study-cleaner DESTINATION bin) - -INSTALL(EXPORT antares-study-cleaner - FILE antares-study-cleanerConfig.cmake - DESTINATION cmake -) - -set(CLEANER_LIBS - yuni-static-core - Antares::args_helper - Antares::study - Antares::sys - antares-core #version.h - ${CMAKE_THREADS_LIBS_INIT} -) - -# The new ant library -target_include_directories(${execname} - PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/libs" - ) - -target_link_libraries(${execname} - PRIVATE - ${CLEANER_LIBS} - ) - -import_std_libs(${execname}) -executable_strip(${execname}) - diff --git a/src/tools/cleaner/main.cpp b/src/tools/cleaner/main.cpp deleted file mode 100644 index 729bdb760f..0000000000 --- a/src/tools/cleaner/main.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace Yuni; -using namespace Antares; - -#define SEP Yuni::IO::Separator - -static bool onProgress(uint) -{ - return true; -} - -class StudyFinderCleaner final : public Data::StudyFinder -{ -public: - StudyFinderCleaner() : listOnly(false), mrproper(false) - { - } - - void onStudyFound(const String& folder, Data::Version version) override - { - if ((int)version != (int)Data::versionLatest) - { - logs.warning() << "requires format upgrade, ignoring " << folder; - return; - } - - if (listOnly) - { - logs.info() << folder; - return; - } - - auto* cleaner = new Data::StudyCleaningInfos(folder); - cleaner->setCustomExcludeList(exclude); - cleaner->onProgress.bind(&onProgress); - if (cleaner->analyze()) - cleaner->performCleanup(); - delete cleaner; - - if (mrproper) - { - String path; - path << folder << SEP << "output"; - IO::Directory::Remove(path); - - path.clear(); - path << folder << SEP << "logs"; - IO::Directory::Remove(path); - } - } - -public: - bool listOnly; - bool mrproper; - Yuni::String exclude; -}; // class StudyFinderCleaner - -int main(int argc, char* argv[]) -{ - // locale - InitializeDefaultLocale(); - - Antares::logs.applicationName("cleaner"); - IntoUTF8ArgsTranslator toUTF8ArgsTranslator(argc, argv); - std::tie(argc, argv) = toUTF8ArgsTranslator.convert(); - String::Vector optInput; - bool optPrintOnly = false; - bool optMrProper = false; - - Yuni::String optExclude; - - // Command Line options - { - // Parser - GetOpt::Parser options; - // - options.addParagraph(String() << "Antares Study Cleaner v" << VersionToCString() << "\n"); - // Input - options.remainingArguments(optInput); - // Output - options.add(optInput, 'i', "input", "An input folder where to look for studies"); - // Exclude some files/folders - options.add(optExclude, - 'e', - "exclude", - "Colon-separated list of excluded files/folders to prevent from destruction. " - "Exemple : --exclude fileA:directoryB:fileC"); - - // Format - options.addFlag(optPrintOnly, ' ', "dry", "List the folder only and do nothing"); - - options.addFlag(optMrProper, ' ', "mrproper", "Suppress the outputs and logs files"); - - // Version - bool optVersion = false; - options.addFlag(optVersion, 'v', "version", "Print the version and exit"); - - if (options(argc, argv) == GetOpt::ReturnCode::error) - return options.errors() ? 1 : 0; - - if (optVersion) - { - PrintVersionToStdCout(); - return 0; - } - } - - // Load the local policy settings - LocalPolicy::Open(); - LocalPolicy::CheckRootPrefix(argv[0]); - - if (not optInput.empty()) - { - StudyFinderCleaner updater; - updater.listOnly = optPrintOnly; - updater.mrproper = optMrProper; - if (!optExclude.empty()) - { - updater.exclude = optExclude; - } - updater.lookup(optInput); - updater.wait(); - } - - logs.info() << "done."; - LocalPolicy::Close(); - return 0; -} diff --git a/src/tools/cleaner/win32/cleaner.ico b/src/tools/cleaner/win32/cleaner.ico deleted file mode 100644 index c132260904..0000000000 Binary files a/src/tools/cleaner/win32/cleaner.ico and /dev/null differ diff --git a/src/tools/cleaner/win32/cleaner.rc.cmake b/src/tools/cleaner/win32/cleaner.rc.cmake deleted file mode 100644 index 1412f7cf0b..0000000000 --- a/src/tools/cleaner/win32/cleaner.rc.cmake +++ /dev/null @@ -1,32 +0,0 @@ -// note that the icon used by the Explorer (i.e. the programs icon) is the -// first icon in the executable and the icons are sorted both by their order -// (Win9x) and by alphabetically (!) (NT), so put this icon first and give it -// a name starting with "a" -aaaaa ICON "@CMAKE_CURRENT_BINARY_DIR@/win32/cleaner.ico" - -1 VERSIONINFO -FILEVERSION @ANTARES_VERSION_HI@,@ANTARES_VERSION_LO@,@ANTARES_VERSION_REVISION@,0 -PRODUCTVERSION @ANTARES_VERSION_HI@,@ANTARES_VERSION_LO@,@ANTARES_VERSION_REVISION@,0 - -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - BEGIN - VALUE "CompanyName", "@ANTARES_PUBLISHER@" - VALUE "FileDescription", "Antares Study Cleaner v@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@" - VALUE "FileVersion", "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@" - VALUE "InternalName", "Antares Study Cleaner" - VALUE "LegalCopyright", "@ANTARES_PUBLISHER@" - VALUE "OriginalFilename", "antares-@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@-study-cleaner.exe" - VALUE "ProductName", "Antares Study Cleaner" - VALUE "ProductVersion", "@ANTARES_VERSION_HI@.@ANTARES_VERSION_LO@.@ANTARES_VERSION_REVISION@" - END - END - - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x809, 1200 - END -END - diff --git a/src/tools/config/CMakeLists.txt b/src/tools/config/CMakeLists.txt index f2d2a49add..f0c77a4e06 100644 --- a/src/tools/config/CMakeLists.txt +++ b/src/tools/config/CMakeLists.txt @@ -2,51 +2,49 @@ OMESSAGE("antares-config") - - # Le main -set(SRCS main.cpp) - +set(SRCS main.cpp) -if(WIN32) - FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/config.o") - CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/config.rc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/win32/config.rc") - FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/config.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/config.rc") -endif(WIN32) +if (WIN32) + FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/config.o") + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/config.rc.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/win32/config.rc") + FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/config.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") + SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/config.rc") +endif (WIN32) - -set(execname "antares-${ANTARES_PRG_VERSION}-config") +set(execname "antares-config") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-config DESTINATION bin) INSTALL(EXPORT antares-config - FILE antares-configConfig.cmake - DESTINATION cmake + FILE antares-configConfig.cmake + DESTINATION cmake ) set(CONFIG_LIBS - yuni-static-core - Antares::args_helper - ${CMAKE_THREADS_LIBS_INIT} + yuni-static-core + Antares::args_helper + ${CMAKE_THREADS_LIBS_INIT} ) # The new ant library target_include_directories(${execname} - PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/libs" - ) + PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/libs" +) target_link_libraries(${execname} - PRIVATE - ${CONFIG_LIBS} - Antares::array - Antares::sys - antares-core #ressource.h - ) + PRIVATE + ${CONFIG_LIBS} + Antares::array + Antares::sys + Antares::resources + Antares::locale + antares-core #ressource.h +) import_std_libs(${execname}) executable_strip(${execname}) diff --git a/src/tools/config/main.cpp b/src/tools/config/main.cpp index c4f34aecbc..0cb15eac90 100644 --- a/src/tools/config/main.cpp +++ b/src/tools/config/main.cpp @@ -1,38 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include #include + #include -#include -#include #include -#include + +#include +#include +#include +#include +#include #include using namespace Yuni; @@ -62,7 +58,9 @@ int main(int argc, char* argv[]) options.addFlag(optVersion, 'v', "version", "Print the version and exit"); if (options(argc, argv) == GetOpt::ReturnCode::error) + { return options.errors() ? EXIT_FAILURE : 0; + } if (optVersion) { diff --git a/src/tools/finder/CMakeLists.txt b/src/tools/finder/CMakeLists.txt index 7d58acaf2f..79868cab90 100644 --- a/src/tools/finder/CMakeLists.txt +++ b/src/tools/finder/CMakeLists.txt @@ -2,42 +2,41 @@ OMESSAGE("antares-study-finder") - - # Le main -set(SRCS main.cpp) +set(SRCS main.cpp) -if(WIN32) - FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.o") - CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.rc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/win32/finder.rc") - FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/finder.rc") -endif(WIN32) +if (WIN32) + FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.o") + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.rc.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/win32/finder.rc") + FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") + SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/finder.rc") +endif (WIN32) -set(execname "antares-${ANTARES_PRG_VERSION}-study-finder") +set(execname "antares-study-finder") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-study-finder DESTINATION bin) INSTALL(EXPORT antares-study-finder - FILE antares-study-finderConfig.cmake - DESTINATION cmake + FILE antares-study-finderConfig.cmake + DESTINATION cmake ) set(FINDER_LIBS - antares-core - yuni-static-core - Antares::args_helper - ${CMAKE_THREADS_LIBS_INIT} + antares-core + yuni-static-core + Antares::args_helper + Antares::locale + ${CMAKE_THREADS_LIBS_INIT} ) target_link_libraries(${execname} - PRIVATE - ${FINDER_LIBS} - PUBLIC - Antares::study - ) + PRIVATE + ${FINDER_LIBS} + PUBLIC + Antares::study +) import_std_libs(${execname}) executable_strip(${execname}) diff --git a/src/tools/finder/main.cpp b/src/tools/finder/main.cpp index 2b3e04c2b7..02ea7fdb7f 100644 --- a/src/tools/finder/main.cpp +++ b/src/tools/finder/main.cpp @@ -1,45 +1,42 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include #include + +#include #include +#include +#include +#include #include -#include -#include using namespace Yuni; using namespace Antares; -class MyStudyFinder : public Data::StudyFinder +class MyStudyFinder: public Data::StudyFinder { public: - MyStudyFinder() : extra(false), csv(false) + MyStudyFinder(): + extra(false), + csv(false) { } @@ -47,15 +44,19 @@ class MyStudyFinder : public Data::StudyFinder { } - void onStudyFound(const String& folder, Data::Version version) + void onStudyFound(const String& folder, const Data::StudyVersion& version) { std::cout << folder; if (extra) { if (csv) - std::cout << ";" << Data::VersionToCStr(version); + { + std::cout << ";" << version.toString(); + } else - std::cout << " (" << Data::VersionToCStr(version) << ')'; + { + std::cout << " (" << version.toString() << ')'; + } } std::cout << '\n'; } @@ -102,7 +103,9 @@ int main(int argc, char* argv[]) options.addFlag(optVersion, 'v', "version", "Print the version and exit"); if (options(argc, argv) == GetOpt::ReturnCode::error) + { return options.errors() ? 1 : 0; + } if (optVersion) { diff --git a/src/tools/kirchhoff-cbuilder/CMakeLists.txt b/src/tools/kirchhoff-cbuilder/CMakeLists.txt index 10a9963e73..69837b7b28 100644 --- a/src/tools/kirchhoff-cbuilder/CMakeLists.txt +++ b/src/tools/kirchhoff-cbuilder/CMakeLists.txt @@ -1,7 +1,7 @@ OMESSAGE("antares-kirchhoff-constraints-builder") # Le main -set(SRCS main.cpp) +set(SRCS main.cpp) # if(WIN32) # FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/finder.o") @@ -12,22 +12,31 @@ set(SRCS main.cpp) # endif(WIN32) -set(execname "antares-${ANTARES_PRG_VERSION}-kirchhoff-constraints-builder") +set(execname "antares-kirchhoff-constraints-builder") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-kirchhoff-constraints-builder DESTINATION bin) INSTALL(EXPORT antares-kirchhoff-constraints-builder - FILE antares-skirchhoff-constraints-builderConfig.cmake - DESTINATION cmake + FILE antares-skirchhoff-constraints-builderConfig.cmake + DESTINATION cmake ) set(KIRCHHOFF_CBUILDER_LIBS - yuni-static-core - ${CMAKE_THREADS_LIBS_INIT} + yuni-static-core + ${CMAKE_THREADS_LIBS_INIT} ) -target_link_libraries(${execname} PRIVATE antares-solver-constraints-builder Antares::sys) -target_link_libraries(${execname} PRIVATE ${KIRCHHOFF_CBUILDER_LIBS} ) +target_link_libraries(${execname} + PRIVATE + antares-solver-constraints-builder + Antares::sys + Antares::resources + Antares::locale +) +target_link_libraries(${execname} + PRIVATE + ${KIRCHHOFF_CBUILDER_LIBS} +) import_std_libs(${execname}) executable_strip(${execname}) diff --git a/src/tools/kirchhoff-cbuilder/kirchhoff-cbuilder.h b/src/tools/kirchhoff-cbuilder/kirchhoff-cbuilder.h index 380f37c074..e3afd8ab2b 100644 --- a/src/tools/kirchhoff-cbuilder/kirchhoff-cbuilder.h +++ b/src/tools/kirchhoff-cbuilder/kirchhoff-cbuilder.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2022 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __KIRCHHOFF_CBUILDER_H__ diff --git a/src/tools/kirchhoff-cbuilder/main.cpp b/src/tools/kirchhoff-cbuilder/main.cpp index d0e85837a6..7097917137 100644 --- a/src/tools/kirchhoff-cbuilder/main.cpp +++ b/src/tools/kirchhoff-cbuilder/main.cpp @@ -1,38 +1,32 @@ /* -** Copyright 2007-2022 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include -#include -#include -#include -#include #include -#include "../../solver/constraints-builder/cbuilder.h" +#include +#include +#include +#include +#include +#include "antares/solver/constraints-builder/cbuilder.h" #include "kirchhoff-cbuilder.h" @@ -52,7 +46,9 @@ int main(int argc, char* argv[]) std::string studyPath(argv[1]); std::string kirchhoffOptionPath; if (argc > 2) + { kirchhoffOptionPath = argv[2]; + } if (!initResources(argc, argv)) { @@ -69,7 +65,9 @@ int main(int argc, char* argv[]) } if (!runKirchhoffConstraints(study, studyPath, kirchhoffOptionPath)) + { return EXIT_FAILURE; + } return 0; } @@ -80,7 +78,7 @@ bool runKirchhoffConstraints(std::shared_ptr study, { study->areas.ensureDataIsInitialized(study->parameters, false); - CBuilder constraintBuilder(study); + CBuilder constraintBuilder(*study); logs.info() << "CBuilder created"; if (!constraintBuilder.completeFromStudy()) @@ -106,8 +104,8 @@ bool runKirchhoffConstraints(std::shared_ptr study, return false; } - auto bindingPath - = studyPath + Yuni::IO::Separator + "input" + Yuni::IO::Separator + "bindingconstraints"; + auto bindingPath = studyPath + Yuni::IO::Separator + "input" + Yuni::IO::Separator + + "bindingconstraints"; if (!study->bindingConstraints.saveToFolder(bindingPath)) { @@ -129,7 +127,9 @@ bool initResources(int argc, char* argv[]) InitializeDefaultLocale(); if (!LocalPolicy::Open()) + { return false; + } LocalPolicy::CheckRootPrefix(argv[0]); @@ -139,12 +139,15 @@ bool initResources(int argc, char* argv[]) bool initComponents(std::shared_ptr study, const std::string& studyPath) { - study->header.version - = Data::StudyHeader::ReadVersionFromFile(studyPath + Yuni::IO::Separator + "study.antares"); + study->header.version = Data::StudyHeader::tryToFindTheVersion(studyPath); + if (study->header.version == Data::StudyVersion::unknown()) + { + return false; + } study->folder = studyPath; study->folderInput = studyPath + Yuni::IO::Separator + "input"; - logs.info() << "Study version: " << study->header.version; + logs.info() << "Study version: " << study->header.version.toString(); Data::StudyLoadOptions options; options.loadOnlyNeeded = false; @@ -156,8 +159,8 @@ bool initComponents(std::shared_ptr study, const std::string& study } logs.info() << "Areas loaded."; - auto bindingPath - = studyPath + Yuni::IO::Separator + "input" + Yuni::IO::Separator + "bindingconstraints"; + auto bindingPath = studyPath + Yuni::IO::Separator + "input" + Yuni::IO::Separator + + "bindingconstraints"; if (!study->bindingConstraints.loadFromFolder(*study, options, bindingPath)) { diff --git a/src/tools/ts-generator/CMakeLists.txt b/src/tools/ts-generator/CMakeLists.txt new file mode 100644 index 0000000000..cea38ae0cd --- /dev/null +++ b/src/tools/ts-generator/CMakeLists.txt @@ -0,0 +1,28 @@ +set(SRCS + main.cpp +) + +set(execname "antares-ts-generator") +add_executable(${execname} ${SRCS}) +install(TARGETS ${execname} EXPORT antares-ts-generator DESTINATION bin) + +INSTALL(EXPORT ${execname} + FILE antares-ts-generatorConfig.cmake + DESTINATION cmake +) + +target_link_libraries(${execname} + PRIVATE + Antares::utils + antares-solver-ts-generator + Antares::study + Antares::checks +) + +target_include_directories(${execname} + PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" +) + +import_std_libs(${execname}) +executable_strip(${execname}) diff --git a/src/tools/ts-generator/main.cpp b/src/tools/ts-generator/main.cpp new file mode 100644 index 0000000000..b1fabf2ff7 --- /dev/null +++ b/src/tools/ts-generator/main.cpp @@ -0,0 +1,531 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Antares; +using namespace Antares::TSGenerator; + +namespace fs = std::filesystem; + +struct Settings +{ + std::string studyFolder; + + /// generate TS for all clusters if activated + bool allThermal = false; + /// generate TS for a list "area.cluster;area2.cluster2;" + std::string thermalListToGen = ""; + + /// generate TS for all links if activated + bool allLinks = false; + /// generate TS for a list "area.link;area2.link2;" + std::string linksListToGen = ""; +}; + +std::unique_ptr createTsGeneratorParser(Settings& settings) +{ + auto parser = std::make_unique(); + parser->addParagraph("Antares Time Series generator\n"); + + parser->addFlag(settings.allThermal, + ' ', + "all-thermal", + "Generate TS for all thermal clusters"); + parser->addFlag(settings.thermalListToGen, + ' ', + "thermal", + "Generate TS for a list of area IDs and thermal clusters IDs, " + "\nusage: --thermal=\"areaID.clusterID;area2ID.clusterID\""); + + parser->addFlag(settings.allLinks, ' ', "all-links", "Generate TS capacities for all links"); + parser->addFlag(settings.linksListToGen, + ' ', + "links", + "Generate TS capacities for a list of 2 area IDs, " + "usage: --links=\"areaID.area2ID;area3ID.area1ID\""); + + parser->remainingArguments(settings.studyFolder); + + return parser; +} + +std::vector getClustersToGen(Data::AreaList& areas, + const std::string& clustersToGen) +{ + std::vector clusters; + const auto ids = splitStringIntoPairs(clustersToGen, ';', '.'); + + for (const auto& [areaID, clusterID]: ids) + { + logs.info() << "Searching for area: " << areaID << " and cluster: " << clusterID; + + auto* area = areas.find(areaID); + if (!area) + { + logs.warning() << "Area not found: " << areaID; + continue; + } + + auto* cluster = area->thermal.list.findInAll(clusterID); + if (!cluster) + { + logs.warning() << "Cluster not found: " << clusterID; + continue; + } + + clusters.push_back(cluster); + } + + return clusters; +} + +// ===== New code for TS generation links ==================================== + +std::vector extractTargetAreas(fs::path sourceLinkDir) +{ + std::vector to_return; + fs::path pathToIni = sourceLinkDir / "properties.ini"; + IniFile ini; + ini.open(pathToIni); // gp : we should handle reading issues + for (auto* s = ini.firstSection; s; s = s->next) + { + std::string targetAreaName = transformNameIntoID(s->name); + to_return.push_back(targetAreaName); + } + return to_return; +} + +LinkPairs extractLinkNamesFromStudy(fs::path studyDir) +{ + LinkPairs to_return; + fs::path linksDir = studyDir / "input" / "links"; + for (const auto& item: fs::directory_iterator{linksDir}) + { + if (item.is_directory()) + { + std::string sourceAreaName = item.path().filename().generic_string(); + auto targetAreas = extractTargetAreas(item); + for (auto& targetAreaName: targetAreas) + { + auto linkPair = std::make_pair(sourceAreaName, targetAreaName); + to_return.push_back(linkPair); + } + } + } + return to_return; +} + +bool pairs_match(const LinkPair& p1, const LinkPair& p2) +{ + return (p1.first == p2.first && p1.second == p2.second) + || (p1.first == p2.second && p1.second == p2.first); +} + +const LinkPair* getMatchingPairInCollection(const LinkPair& pair, const LinkPairs& collection) +{ + for (const auto& p: collection) + { + if (pairs_match(pair, p)) + { + return &p; + } + } + return nullptr; +} + +LinkPairs extractLinkNamesFromCmdLine(const LinkPairs& allLinks, const std::string linksFromCmdLine) +{ + LinkPairs to_return; + LinkPairs pairsFromCmdLine = splitStringIntoPairs(linksFromCmdLine, ';', '.'); + for (auto& p: pairsFromCmdLine) + { + if (const auto* found_pair = getMatchingPairInCollection(p, allLinks); found_pair) + { + to_return.push_back(*found_pair); + } + else + { + logs.error() << "Link '" << p.first << "." << p.second << "' not found"; + } + } + return to_return; +} + +bool readLinkGeneralProperty(StudyParamsForLinkTS& params, + const Yuni::String& key, + const Yuni::String& value) +{ + if (key == "derated") + { + return value.to(params.derated); + } + if (key == "nbtimeserieslinks") + { + return value.to(params.nbLinkTStoGenerate); + } + if (key == "seed-tsgen-links") + { + unsigned int seed{0}; + if (!value.to(seed)) + { + return false; + } + params.random.reset(seed); + return true; + } + return true; // gp : should we return true here ? +} + +StudyParamsForLinkTS readGeneralParamsForLinksTS(fs::path studyDir) +{ + StudyParamsForLinkTS to_return; + fs::path pathToGeneraldata = studyDir / "settings" / "generaldata.ini"; + IniFile ini; + ini.open(pathToGeneraldata); // gp : we should handle reading issues + for (auto* section = ini.firstSection; section; section = section->next) + { + // Skipping sections useless in the current context + Yuni::String sectionName = section->name; + if (sectionName != "general" && sectionName != "seeds - Mersenne Twister") + { + continue; + } + + for (const IniFile::Property* p = section->firstProperty; p; p = p->next) + { + if (!readLinkGeneralProperty(to_return, p->key, p->value)) + { + logs.warning() << ini.filename() << ": reading value of '" << p->key + << "' went wrong"; + } + } + } + return to_return; +} + +std::vector CreateLinkList(const LinkPairs& linksFromCmdLine) +{ + std::vector to_return; + to_return.reserve(linksFromCmdLine.size()); + for (const auto& link_pair: linksFromCmdLine) + { + LinkTSgenerationParams params; + params.namesPair = link_pair; + to_return.push_back(std::move(params)); + } + return to_return; +} + +LinkTSgenerationParams* findLinkInList(const LinkPair& link_to_find, + std::vector& linkList) +{ + for (auto& link: linkList) + { + if (link.namesPair == link_to_find) + { + return &link; + } + } + return nullptr; +} + +bool readLinkIniProperty(LinkTSgenerationParams* link, + const Yuni::String& key, + const Yuni::String& value) +{ + if (key == "unitcount") + { + return value.to(link->unitCount); + } + + if (key == "nominalcapacity") + { + return value.to(link->nominalCapacity); + } + + if (key == "law.planned") + { + return value.to(link->plannedLaw); + } + + if (key == "law.forced") + { + return value.to(link->forcedLaw); + } + + if (key == "volatility.planned") + { + return value.to(link->plannedVolatility); + } + + if (key == "volatility.forced") + { + return value.to(link->forcedVolatility); + } + + if (key == "force-no-generation") + { + return value.to(link->forceNoGeneration); + } + return true; +} + +void readLinkIniProperties(LinkTSgenerationParams* link, IniFile::Section* section) +{ + for (const IniFile::Property* p = section->firstProperty; p; p = p->next) + { + if (!readLinkIniProperty(link, p->key, p->value)) + { + std::string linkName = link->namesPair.first + "." + link->namesPair.second; + logs.warning() << "Link '" << linkName << "' : reading value of '" << p->key + << "' went wrong"; + link->hasValidData = false; + } + } +} + +void readSourceAreaIniFile(fs::path pathToIni, + std::string sourceAreaName, + std::vector& linkList) +{ + IniFile ini; + ini.open(pathToIni); // gp : we should handle reading issues + for (auto* section = ini.firstSection; section; section = section->next) + { + std::string targetAreaName = transformNameIntoID(section->name); + const LinkPair processedLink = std::make_pair(sourceAreaName, targetAreaName); + if (auto* foundLink = findLinkInList(processedLink, linkList); foundLink) + { + readLinkIniProperties(foundLink, section); + } + } +} + +void readIniProperties(std::vector& linkList, fs::path toLinksDir) +{ + for (auto& link: linkList) + { + std::string sourceAreaName = link.namesPair.first; + fs::path pathToIni = toLinksDir / sourceAreaName / "properties.ini"; + readSourceAreaIniFile(pathToIni, sourceAreaName, linkList); + } +} + +bool readLinkPreproTimeSeries(LinkTSgenerationParams& link, fs::path sourceAreaDir) +{ + bool to_return = true; + const auto preproId = link.namesPair.first + "/" + link.namesPair.second; + link.prepro = std::make_unique(preproId, link.unitCount); + + auto preproFileRoot = sourceAreaDir / "prepro" / link.namesPair.second; + + auto preproFile = preproFileRoot; + preproFile += ".txt"; + if (fs::exists(preproFile)) + { + to_return = link.prepro->data.loadFromCSVFile( + preproFile.string(), + Data::PreproAvailability::preproAvailabilityMax, + DAYS_PER_YEAR) + && link.prepro->validate() && to_return; + } + + auto modulationFileDirect = preproFileRoot; + modulationFileDirect += "_mod_direct.txt"; + if (fs::exists(modulationFileDirect)) + { + to_return = link.modulationCapacityDirect.loadFromCSVFile(modulationFileDirect.string(), + 1, + HOURS_PER_YEAR) + && to_return; + } + + auto modulationFileIndirect = preproFileRoot; + modulationFileIndirect += "_mod_indirect.txt"; + if (fs::exists(modulationFileIndirect)) + { + to_return = link.modulationCapacityIndirect.loadFromCSVFile(modulationFileIndirect.string(), + 1, + HOURS_PER_YEAR) + && to_return; + } + // Makes possible a skip of TS generation when time comes + link.hasValidData = link.hasValidData && to_return; + return to_return; +} + +void readPreproTimeSeries(std::vector& linkList, fs::path toLinksDir) +{ + for (auto& link: linkList) + { + std::string sourceAreaName = link.namesPair.first; + fs::path sourceAreaDir = toLinksDir / sourceAreaName; + if (!readLinkPreproTimeSeries(link, sourceAreaDir)) + { + logs.warning() << "Could not load all prepro data for link '" << link.namesPair.first + << "." << link.namesPair.second << "'"; + } + } +} + +void readLinksSpecificTSparameters(std::vector& linkList, + fs::path studyFolder) +{ + fs::path toLinksDir = studyFolder / "input" / "links"; + readIniProperties(linkList, toLinksDir); + readPreproTimeSeries(linkList, toLinksDir); +} + +std::string DateAndTime() +{ + YString to_return; + unsigned int now = Yuni::DateTime::Now(); + Yuni::DateTime::TimestampToString(to_return, "%Y%m%d-%H%M", now); + return to_return.to(); +} + +// ============================================================================ + +int main(int argc, char* argv[]) +{ + logs.applicationName("ts-generator"); + + Settings settings; + + auto parser = createTsGeneratorParser(settings); + switch (auto ret = parser->operator()(argc, argv); ret) + { + using namespace Yuni::GetOpt; + case ReturnCode::error: + logs.error() << "Unknown arguments, aborting"; + return parser->errors(); + case ReturnCode::help: + // End the program + return 0; + default: + break; + } + + if (settings.allThermal && !settings.thermalListToGen.empty()) + { + logs.error() << "Conflicting options, either choose all thermal clusters or a list"; + return 1; + } + + if (settings.allLinks && !settings.linksListToGen.empty()) + { + logs.error() << "Conflicting options, either choose all links or a list"; + return 1; + } + + auto study = std::make_shared(true); + Data::StudyLoadOptions studyOptions; + studyOptions.prepareOutput = true; + + if (!study->loadFromFolder(settings.studyFolder, studyOptions)) + { + logs.error() << "Invalid study given to the generator"; + return 1; + } + + study->initializeRuntimeInfos(); + // Force the writing of generated TS into output/YYYYMMDD-HHSSeco/ts-generator/thermal[/mc-0] + study->parameters.timeSeriesToArchive |= Antares::Data::timeSeriesThermal; + + try + { + Antares::Check::checkMinStablePower(true, study->areas); + } + catch (Error::InvalidParametersForThermalClusters& ex) + { + Antares::logs.error() << ex.what(); + } + + Benchmarking::DurationCollector durationCollector; + + auto resultWriter = Solver::resultWriterFactory(Data::ResultFormat::legacyFilesDirectories, + study->folderOutput, + nullptr, + durationCollector); + + const auto thermalSavePath = fs::path("ts-generator") / "thermal"; + + // ============ THERMAL : Getting data for generating time-series ========= + std::vector clusters; + if (settings.allThermal) + { + clusters = TSGenerator::getAllClustersToGen(study->areas, true); + } + else if (!settings.thermalListToGen.empty()) + { + clusters = getClustersToGen(study->areas, settings.thermalListToGen); + } + + for (auto& c: clusters) + { + logs.debug() << c->id(); + } + + // ============ LINKS : Getting data for generating LINKS time-series ===== + auto allLinksPairs = extractLinkNamesFromStudy(settings.studyFolder); + auto linksFromCmdLine = extractLinkNamesFromCmdLine(allLinksPairs, settings.linksListToGen); + if (settings.allLinks) + { + linksFromCmdLine = allLinksPairs; + } + + StudyParamsForLinkTS generalParams = readGeneralParamsForLinksTS(settings.studyFolder); + + std::vector linkList = CreateLinkList(linksFromCmdLine); + readLinksSpecificTSparameters(linkList, settings.studyFolder); + + auto saveLinksTSpath = fs::path(settings.studyFolder) / "output" / DateAndTime(); + saveLinksTSpath /= "ts-generator"; + saveLinksTSpath /= "links"; + + // ============ TS Generation ============================================= + + bool ret = TSGenerator::generateThermalTimeSeries(*study, + clusters, + *resultWriter, + thermalSavePath.string()); + + ret = TSGenerator::generateLinkTimeSeries(linkList, generalParams, saveLinksTSpath.string()) + && ret; + + return !ret; // return 0 for success +} diff --git a/src/tools/updater/CMakeLists.txt b/src/tools/updater/CMakeLists.txt index 6fd814588a..c8d2e32210 100644 --- a/src/tools/updater/CMakeLists.txt +++ b/src/tools/updater/CMakeLists.txt @@ -15,7 +15,7 @@ if(WIN32) endif(WIN32) -set(execname "antares-${ANTARES_PRG_VERSION}-study-updater") +set(execname "antares-study-updater") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-study-updater DESTINATION bin) @@ -29,7 +29,9 @@ set(UPDATER_LIBS Antares::args_helper Antares::study Antares::sys + Antares::locale antares-core #version.h + Antares::locale ${CMAKE_THREADS_LIBS_INIT} ) diff --git a/src/tools/updater/main.cpp b/src/tools/updater/main.cpp index 4650493f7d..e1cc84944d 100644 --- a/src/tools/updater/main.cpp +++ b/src/tools/updater/main.cpp @@ -1,40 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include -#include #include + +#include #include -#include +#include +#include #include -#include +#include #include -#include +#include using namespace Yuni; using namespace Antares; @@ -44,14 +39,14 @@ static bool onProgress(uint) return true; } -class MyStudyFinder final : public Data::StudyFinder +class MyStudyFinder final: public Data::StudyFinder { public: - void onStudyFound(const String& folder, Data::Version version) override + void onStudyFound(const String& folder, const Data::StudyVersion& version) override { - if (version == Data::versionUnknown || version == Data::versionFutur) + if (version == Data::StudyVersion::unknown() || version > Data::StudyVersion::latest()) { - logs.info() << folder << " : version of study is too old, too new or unknown"; + logs.info() << folder << " : version of study is too new or unknown"; return; } @@ -61,15 +56,14 @@ class MyStudyFinder final : public Data::StudyFinder return; } - if ((int)Data::versionLatest == (int)version && (!removeUselessTimeseries)) + if (Data::StudyVersion::latest() == version && (!removeUselessTimeseries)) { logs.info() << folder << " : is up-to-date"; } else { - logs.notice() << "Upgrading " << folder << " (v" << Data::VersionToCStr(version) - << " to " << Data::VersionToCStr((Data::Version)Data::versionLatest) - << ")"; + logs.notice() << "Upgrading " << folder << " (v" << version.toString() << " to " + << Data::StudyVersion::latest().toString() << ")"; auto study = std::make_unique(); @@ -87,10 +81,14 @@ class MyStudyFinder final : public Data::StudyFinder if (study->loadFromFolder(folder, options)) { if (removeUselessTimeseries) + { study->removeTimeseriesIfTSGeneratorEnabled(); + } if (forceReadonly) + { study->parameters.readonly = true; + } logs.info() << "Saving..."; study->saveToFolder(folder); @@ -108,9 +106,11 @@ class MyStudyFinder final : public Data::StudyFinder if (cleanup) { auto* cleaner = new Data::StudyCleaningInfos(folder.c_str()); - cleaner->onProgress.bind(&onProgress); + cleaner->onProgress = &onProgress; if (cleaner->analyze()) + { cleaner->performCleanup(); + } delete cleaner; } @@ -159,7 +159,9 @@ std::string getMargin(int size) { std::string margin; for (int i = 0; i < size; i++) + { margin += " "; + } margin += " "; return margin; } @@ -185,12 +187,12 @@ int main(int argc, char* argv[]) GetOpt::Parser options; // General information - std::string updaterComment - = "\nFound studies are upgraded, unless dry run is enabled (-d | --dry).\n"; - updaterComment - += "Following options make other options useless when used in the same run :\n"; - updaterComment - += "(-h|--help), (-v|--version) and (-d | --dry), in that order of priority.\n"; + std::string updaterComment = "\nFound studies are upgraded, unless dry run is enabled (-d " + "| --dry).\n"; + updaterComment += "Following options make other options useless when used in the same run " + ":\n"; + updaterComment += "(-h|--help), (-v|--version) and (-d | --dry), in that order of " + "priority.\n"; updaterComment += "Thus they should be used alone.\n"; updaterComment += "If previous options are not used, other options have an action in " "addition to upgrade.\n"; @@ -235,15 +237,19 @@ int main(int argc, char* argv[]) 'd', "dry", "Only Lists the study folders which would be upgraded but do nothing"); - options.addFlag( - optForceReadonly, ' ', "force-readonly", "Force read-only mode for all studies found"); + options.addFlag(optForceReadonly, + ' ', + "force-readonly", + "Force read-only mode for all studies found"); // Version bool optVersion = false; options.addFlag(optVersion, 'v', "version", "Print the version and exit"); if (options(argc, argv) == GetOpt::ReturnCode::error) + { return options.errors() ? 1 : 0; + } if (optVersion) { diff --git a/src/tools/vacuum/CMakeLists.txt b/src/tools/vacuum/CMakeLists.txt index 34e4142e49..68d95a82bd 100644 --- a/src/tools/vacuum/CMakeLists.txt +++ b/src/tools/vacuum/CMakeLists.txt @@ -3,48 +3,48 @@ OMESSAGE("antares-vacuum") # Le main set(SRCS - main.cpp - modified-inode.h - modified-inode.cpp - antares-study.cpp - antares-study.h - io.h - io.cpp + main.cpp + modified-inode.h + modified-inode.cpp + antares-study.cpp + antares-study.h + io.h + io.cpp ) +if (WIN32) + FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/vacuum.o") + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/vacuum.rc.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/win32/vacuum.rc") + FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/vacuum.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") + SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/vacuum.rc") +endif (WIN32) -if(WIN32) - FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/vacuum.o") - CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/vacuum.rc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/win32/vacuum.rc") - FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/vacuum.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/vacuum.rc") -endif(WIN32) - -set(execname "antares-${ANTARES_PRG_VERSION}-vacuum") +set(execname "antares-vacuum") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-vacuum DESTINATION bin) INSTALL(EXPORT antares-vacuum - FILE antares-vacuumConfig.cmake - DESTINATION cmake + FILE antares-vacuumConfig.cmake + DESTINATION cmake ) set(VACUUM_LIBS - antares-fswalker - yuni-static-core - ${CMAKE_THREADS_LIBS_INIT} - Antares::args_helper - Antares::study + Antares::fswalker + yuni-static-core + ${CMAKE_THREADS_LIBS_INIT} + Antares::args_helper + Antares::study + Antares::locale ) target_link_libraries(${execname} - PRIVATE - ${VACUUM_LIBS} - antares-core #version.h - ) + PRIVATE + ${VACUUM_LIBS} + antares-core #version.h +) import_std_libs(${execname}) executable_strip(${execname}) diff --git a/src/tools/vacuum/antares-study.cpp b/src/tools/vacuum/antares-study.cpp index 278d77544b..aaa7a0dc04 100644 --- a/src/tools/vacuum/antares-study.cpp +++ b/src/tools/vacuum/antares-study.cpp @@ -1,35 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "antares-study.h" -#include -#include + #include #include + +#include +#include + #include "io.h" using namespace Yuni; @@ -42,10 +39,13 @@ enum traces = 0 }; -class UserData : private Yuni::NonCopyable +class UserData: private Yuni::NonCopyable { public: - UserData() : bytesDeleted(0), filesDeleted(0), foldersDeleted(0) + UserData(): + bytesDeleted(0), + filesDeleted(0), + foldersDeleted(0) { } @@ -59,12 +59,15 @@ class UserData : private Yuni::NonCopyable uint64_t foldersDeleted; }; -class AntaresStudyAnalyzerJob : public FSWalker::IJob +class AntaresStudyAnalyzerJob: public FSWalker::IJob { public: - AntaresStudyAnalyzerJob(const String& folder) : folder(folder), userdata(nullptr) + AntaresStudyAnalyzerJob(const String& folder): + folder(folder), + userdata(nullptr) { } + virtual ~AntaresStudyAnalyzerJob() { } @@ -97,16 +100,22 @@ bool AntaresStudyAnalyzerJob::shouldBeDestroyed() const } if (traces) + { DateTime::TimestampToString(text, "%a, %d %b %Y", header.dateLastSave); + } if (header.dateLastSave > dateLimit) { // the study has been saved recently if (traces) + { logs.info() << " - study status " << folder << ": modified recently " << text; + } return false; } if (traces) + { logs.info() << " - study status " << folder << ": last save too old " << text; + } // The study has been modified a long time ago, we have to check // if it has been used recently. First of all, we will check the logs @@ -121,8 +130,10 @@ bool AntaresStudyAnalyzerJob::shouldBeDestroyed() const { // There is at least one recent logfile. aborting if (traces) + { logs.info() << " - study status " << folder << ": at least one recent simulation"; + } return false; } } @@ -138,8 +149,10 @@ bool AntaresStudyAnalyzerJob::shouldBeDestroyed() const { // There is at least one recent logfile. aborting if (traces) + { logs.info() << " - study status " << folder << ": at least one recent simulation"; + } return false; } } @@ -148,15 +161,19 @@ bool AntaresStudyAnalyzerJob::shouldBeDestroyed() const return true; } -class FolderRemover : public FSWalker::IJob +class FolderRemover: public FSWalker::IJob { public: using Ptr = Yuni::Job::IJob::Ptr::Promote::Ptr; public: - FolderRemover(const String& folder) : folder(folder), userdata(nullptr), timeout(100) + FolderRemover(const String& folder): + folder(folder), + userdata(nullptr), + timeout(100) { } + virtual ~FolderRemover() { } @@ -194,7 +211,9 @@ class FolderRemover : public FSWalker::IJob if (not job->finished()) { if (suspend(timeout)) + { return; + } // it seems that we should wait a bit more longer to let // other thread work timeout = 400; @@ -205,7 +224,9 @@ class FolderRemover : public FSWalker::IJob // ok delete ! if (traces) + { logs.info() << " :: starting removal of " << folder; + } String::Vector foldersToDelete; uint64_t bytesDeleted = 0; @@ -221,7 +242,9 @@ class FolderRemover : public FSWalker::IJob bytesDeleted += i.size(); ++filesDeleted; if (not RemoveFile(i.filename(), i.size())) + { logs.error() << "impossible to delete " << i.filename(); + } } else { @@ -239,12 +262,16 @@ class FolderRemover : public FSWalker::IJob for (auto i = foldersToDelete.rbegin(); i != foldersToDelete.rend(); ++i) { if (not RemoveDirectoryIfEmpty(*i)) + { logs.error() << "impossible to delete directory " << *i; + } } // deletion of the root folder if (not RemoveDirectoryIfEmpty(folder)) + { logs.error() << "impossible to delete directory " << folder; + } } }; // class AntaresStudyAnalyzerJob @@ -252,7 +279,9 @@ class FolderRemover : public FSWalker::IJob void AntaresStudyAnalyzerJob::onExecute() { if (traces) + { logs.info() << " :: analyzing study " << folder; + } if (shouldBeDestroyed()) { logs.info() << "study delete " << folder; @@ -314,11 +343,15 @@ void AntaresStudyAnalyzerJob::onExecute() // dispatch all jobs foreach (auto& job, folderRemovalJob->dependencies) + { userdata->queue(job); + } // put in queue the last master job if (!dry) + { userdata->queue(folderRemovalJob); + } } } @@ -343,8 +376,11 @@ const char* AntaresStudy::caption() const return "antares study"; } -AntaresStudy::AntaresStudy(int64_t dateLimit) : - bytesDeleted(), filesDeleted(), foldersDeleted(), pDateLimit(dateLimit) +AntaresStudy::AntaresStudy(int64_t dateLimit): + bytesDeleted(), + filesDeleted(), + foldersDeleted(), + pDateLimit(dateLimit) { } @@ -363,10 +399,11 @@ void* AntaresStudy::userdataCreate(FSWalker::DispatchJobEvent& queue) void AntaresStudy::userdataDestroy(void* userdata) { - pMutex.lock(); - bytesDeleted += ((UserData*)userdata)->bytesDeleted; - filesDeleted += ((UserData*)userdata)->filesDeleted; - foldersDeleted += ((UserData*)userdata)->foldersDeleted; - pMutex.unlock(); + { + std::lock_guard lock(pMutex); + bytesDeleted += ((UserData*)userdata)->bytesDeleted; + filesDeleted += ((UserData*)userdata)->filesDeleted; + foldersDeleted += ((UserData*)userdata)->foldersDeleted; + } delete (UserData*)userdata; } diff --git a/src/tools/vacuum/antares-study.h b/src/tools/vacuum/antares-study.h index ff27cde76f..c3db0039f3 100644 --- a/src/tools/vacuum/antares-study.h +++ b/src/tools/vacuum/antares-study.h @@ -1,39 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_STUDY_H__ #define __ANTARES_STUDY_H__ -#include #include +#include -class AntaresStudy : public FSWalker::IExtension +class AntaresStudy: public FSWalker::IExtension { public: AntaresStudy(int64_t dateLimit); + virtual ~AntaresStudy() { } @@ -57,7 +52,7 @@ class AntaresStudy : public FSWalker::IExtension uint64_t foldersDeleted; private: - Yuni::Mutex pMutex; + std::mutex pMutex; int64_t pDateLimit; }; // class AntaresStudy diff --git a/src/tools/vacuum/io.cpp b/src/tools/vacuum/io.cpp index 8a5210fa45..3cb3ea06b0 100644 --- a/src/tools/vacuum/io.cpp +++ b/src/tools/vacuum/io.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "io.h" @@ -31,9 +25,9 @@ using namespace Yuni; /*extern*/ bool dry = true; -/*extern*/ Atomic::Int<> IOBytesDeleted = 0; -/*extern*/ Atomic::Int<> IOFilesDeleted = 0; -/*extern*/ Atomic::Int<> IOFoldersDeleted = 0; +/*extern*/ std::atomic IOBytesDeleted = 0; +/*extern*/ std::atomic IOFilesDeleted = 0; +/*extern*/ std::atomic IOFoldersDeleted = 0; /*extern*/ std::unordered_set inputFolders; @@ -42,7 +36,7 @@ bool RemoveFile(const String& filename, uint64_t size) if (dry || IO::errNone == IO::File::Delete(filename)) { ++IOFilesDeleted; - IOBytesDeleted += (Atomic::Int<>::Type)size; + IOBytesDeleted += size; return true; } return false; diff --git a/src/tools/vacuum/io.h b/src/tools/vacuum/io.h index cf4415105d..0389a68776 100644 --- a/src/tools/vacuum/io.h +++ b/src/tools/vacuum/io.h @@ -1,40 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_VACUUM_IO_H__ #define __ANTARES_VACUUM_IO_H__ -#include #include #ifndef YUNI_OS_WINDOWS #include #else -#include #include +#include #endif +#include #include //! Flag to determine whether we are in dry mode or not @@ -42,9 +36,9 @@ extern bool dry; //! Mutex for getting/setting statistics -extern Yuni::Atomic::Int<> IOBytesDeleted; -extern Yuni::Atomic::Int<> IOFilesDeleted; -extern Yuni::Atomic::Int<> IOFoldersDeleted; +extern std::atomic IOBytesDeleted; +extern std::atomic IOFilesDeleted; +extern std::atomic IOFoldersDeleted; //! All inputs folders, which can not be removed extern std::unordered_set inputFolders; diff --git a/src/tools/vacuum/main.cpp b/src/tools/vacuum/main.cpp index e88cc3ffe7..8f78afd038 100644 --- a/src/tools/vacuum/main.cpp +++ b/src/tools/vacuum/main.cpp @@ -1,46 +1,43 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include + #include #include -#include #include +#include #include -#include #include -#include -#include -#include +#include + +#include #include -#include -#include -#include "modified-inode.h" +#include +#include +#include "antares/antares/antares.h" + #include "antares-study.h" #include "io.h" +#include "modified-inode.h" using namespace Yuni; using namespace Antares; @@ -48,7 +45,7 @@ using namespace Antares; static inline double Round2ndPlace(double v) { v *= 100.; - v = Math::Trunc(v); + v = std::trunc(v); return v / 100.; } @@ -188,13 +185,15 @@ static void NotifyStatistics(const String& logprefix, namespace // anonymous { -class DirectoryCleanerJob : public Job::IJob +class DirectoryCleanerJob: public Job::IJob { public: - DirectoryCleanerJob(const String& directory, int64_t dateLimit) : - directory(directory), dateLimit(dateLimit) + DirectoryCleanerJob(const String& directory, int64_t dateLimit): + directory(directory), + dateLimit(dateLimit) { } + virtual ~DirectoryCleanerJob() { } @@ -290,7 +289,9 @@ int main(int argc, char** argv) options.addFlag(optVersion, 'v', "version", "Print the version and exit"); if (options(argc, argv) == GetOpt::ReturnCode::error) + { return options.errors() ? 42 : 0; + } if (optVersion) { @@ -299,7 +300,9 @@ int main(int argc, char** argv) } if (not optLogs.empty()) + { logs.logfile(optLogs); + } if (!optMaxDays) { @@ -308,7 +311,9 @@ int main(int argc, char** argv) } if (optDelete) + { dry = false; + } } logs.notice() << "Antares Vacuum v" << VersionToCString(); @@ -323,21 +328,29 @@ int main(int argc, char** argv) } if (dry) + { logs.info() << "dry run mode (nothing will de deleted)"; + } foreach (auto& input, optInput) + { inputFolders.insert(input); + } foreach (auto& path, optEachFolderIn) { IO::Directory::Info info(path); for (auto i = info.folder_begin(); i.valid(); ++i) + { inputFolders.insert(i.filename()); + } } optEachFolderIn.clear(); foreach (auto& input, inputFolders) + { logs.info() << "added directory " << input; + } else logs.warning() << "no directory to analyze"; // GO ! @@ -349,7 +362,9 @@ int main(int argc, char** argv) queueservice.maximumThreadCount(4); foreach (auto& input, inputFolders) + { queueservice += new DirectoryCleanerJob(input, dateLimit); + } queueservice.start(); queueservice.wait(Yuni::qseIdle); diff --git a/src/tools/vacuum/modified-inode.cpp b/src/tools/vacuum/modified-inode.cpp index 2c2f9f5472..3569fc698c 100644 --- a/src/tools/vacuum/modified-inode.cpp +++ b/src/tools/vacuum/modified-inode.cpp @@ -1,37 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include #include "modified-inode.h" + +#include + +#include #include #include + #include -#include -#include +#include "antares/antares/antares.h" + #include "io.h" using namespace Yuni; @@ -44,10 +42,13 @@ enum maxLogEntriesRetention = 1000, }; -class UserData : private Yuni::NonCopyable +class UserData: private Yuni::NonCopyable { public: - UserData() : bytesDeleted(0), filesDeleted(0), foldersDeleted(0) + UserData(): + bytesDeleted(0), + filesDeleted(0), + foldersDeleted(0) { } @@ -77,7 +78,9 @@ inline void UserData::pushToLogs() if (logsEntries.size() >= maxLogEntriesRetention) { foreach (auto& entry, logsEntries) + { logs.info() << entry; + } logsEntries.clear(); } } @@ -89,7 +92,9 @@ void UserData::syncBeforeRelease() // pushing logs foreach (auto& entry, logsEntries) + { logs.info() << entry; + } if (not dry && not pathsToDeleteIfEmpty.empty()) { @@ -109,10 +114,14 @@ void UserData::syncBeforeRelease() while (offset < path.size()) { if (!offset) + { break; + } folder.assign(path, offset); if (folder.empty()) + { break; + } if (not RemoveDirectoryIfEmpty(folder)) { @@ -123,7 +132,9 @@ void UserData::syncBeforeRelease() logs.info() << "deleted empty folder " << folder; ++folderRemovedCount; if (!offset) + { break; + } offset = path.rfind(IO::Separator, offset - 1); } } @@ -151,7 +162,9 @@ static void OnFileEvent(const String& filename, void* user) { if (not(modified < ((UserData*)user)->dateLimit)) + { return; + } if (not RemoveFile(filename, size)) { @@ -180,7 +193,9 @@ static void OnFileEvent(const String& filename, logentry.append(") ", 2); logentry << filename; if (size == 0) + { logentry.append(" (empty)", 8); + } else { logentry.append(" (", 2); @@ -226,15 +241,16 @@ void* ModifiedINode::userdataCreate(FSWalker::DispatchJobEvent&) void ModifiedINode::userdataDestroy(void* userdata) { - pQueue.unbind(); + pQueue = []([[maybe_unused]] FSWalker::IJob::Ptr job) {}; if (userdata) { - pMutex.lock(); - bytesDeleted += ((UserData*)userdata)->bytesDeleted; - filesDeleted += ((UserData*)userdata)->filesDeleted; - foldersDeleted += ((UserData*)userdata)->foldersDeleted; - pMutex.unlock(); + { + std::lock_guard lock(pMutex); + bytesDeleted += ((UserData*)userdata)->bytesDeleted; + filesDeleted += ((UserData*)userdata)->filesDeleted; + foldersDeleted += ((UserData*)userdata)->foldersDeleted; + } // destroying the user data ((UserData*)userdata)->syncBeforeRelease(); @@ -242,7 +258,11 @@ void ModifiedINode::userdataDestroy(void* userdata) } } -ModifiedINode::ModifiedINode(int64_t dateLimit) : - bytesDeleted(), filesDeleted(), foldersDeleted(), pDateLimit(dateLimit), pQueue() +ModifiedINode::ModifiedINode(int64_t dateLimit): + bytesDeleted(), + filesDeleted(), + foldersDeleted(), + pDateLimit(dateLimit), + pQueue() { } diff --git a/src/tools/vacuum/modified-inode.h b/src/tools/vacuum/modified-inode.h index ec62b93c42..8bb67d5875 100644 --- a/src/tools/vacuum/modified-inode.h +++ b/src/tools/vacuum/modified-inode.h @@ -1,39 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __MODIFIED_INODE_H__ #define __MODIFIED_INODE_H__ -#include #include +#include -class ModifiedINode : public FSWalker::IExtension +class ModifiedINode: public FSWalker::IExtension { public: ModifiedINode(int64_t dateLimit); + virtual ~ModifiedINode() { } @@ -52,7 +47,7 @@ class ModifiedINode : public FSWalker::IExtension uint64_t foldersDeleted; private: - Yuni::Mutex pMutex; + std::mutex pMutex; int64_t pDateLimit; FSWalker::DispatchJobEvent pQueue; diff --git a/src/tools/yby-aggregator/CMakeLists.txt b/src/tools/yby-aggregator/CMakeLists.txt index 0c60a5cc33..fc0f89442b 100644 --- a/src/tools/yby-aggregator/CMakeLists.txt +++ b/src/tools/yby-aggregator/CMakeLists.txt @@ -5,69 +5,66 @@ include(../../cmake/messages.cmake) OMESSAGE("antares-ybyaggregator") - - include(../../cmake/common-settings.cmake) - - # Le main set(SRCS - main.cpp - datafile.h - result.h - result.cpp - output.h - output.cpp - job.h - job.hxx - job.cpp - progress.h - progress.hxx - progress.cpp - ) + main.cpp + datafile.h + result.h + result.cpp + output.h + output.cpp + job.h + job.hxx + job.cpp + progress.h + progress.hxx + progress.cpp +) -if(WIN32 OR WIN64) - FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/ybyaggregator.o") - CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/ybyaggregator.rc.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/win32/ybyaggregator.rc") - FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/ybyaggregator.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") - SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/ybyaggregator.rc") -endif() +if (WIN32 OR WIN64) + FILE(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/win32/ybyaggregator.o") + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/win32/ybyaggregator.rc.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/win32/ybyaggregator.rc") + FILE(COPY "${CMAKE_CURRENT_SOURCE_DIR}/win32/ybyaggregator.ico" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/win32/") + SET(SRCS ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/win32/ybyaggregator.rc") +endif () -set(execname "antares-${ANTARES_PRG_VERSION}-ybyaggregator") +set(execname "antares-ybyaggregator") add_executable(${execname} ${SRCS}) install(TARGETS ${execname} EXPORT antares-ybyaggregator DESTINATION bin) INSTALL(EXPORT antares-ybyaggregator - FILE antares-ybyaggregatorConfig.cmake - DESTINATION cmake + FILE antares-ybyaggregatorConfig.cmake + DESTINATION cmake ) set(YBY_AGGREGATOR_LIBS - antares-core #version.h - Antares::args_helper - Antares::date - Antares::logs - yuni-static-core - Antares::sys - ${wxWidgets_LIBRARIES} ${CMAKE_THREADS_LIBS_INIT}) + antares-core #version.h + Antares::args_helper + Antares::date + Antares::logs + yuni-static-core + Antares::sys + Antares::locale + ${wxWidgets_LIBRARIES} ${CMAKE_THREADS_LIBS_INIT}) # The new ant library target_include_directories(${execname} - PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/libs" - ) + PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/libs" +) target_link_libraries(${execname} - PRIVATE - ${YBY_AGGREGATOR_LIBS} - PUBLIC - Antares::memory - Antares::utils - ) + PRIVATE + ${YBY_AGGREGATOR_LIBS} + antares-solver-ts-generator + Antares::memory + Antares::utils +) import_std_libs(${execname}) executable_strip(${execname}) diff --git a/src/tools/yby-aggregator/datafile.h b/src/tools/yby-aggregator/datafile.h index 85923ede72..42778a65c8 100644 --- a/src/tools/yby-aggregator/datafile.h +++ b/src/tools/yby-aggregator/datafile.h @@ -1,37 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_DATA_FILE_AGGREGATOR_DATA_FILE_H__ #define __STUDY_DATA_FILE_AGGREGATOR_DATA_FILE_H__ -#include -#include #include #include +#include +#include + class DataFile final { public: @@ -44,8 +39,10 @@ class DataFile final public: template - DataFile(const StringT& data, const StringT2& time, uint i) : - index(i), dataLevel(data), timeLevel(time) + DataFile(const StringT& data, const StringT2& time, uint i): + index(i), + dataLevel(data), + timeLevel(time) { } diff --git a/src/tools/yby-aggregator/job.cpp b/src/tools/yby-aggregator/job.cpp index 368c215f4b..0d841b21d8 100644 --- a/src/tools/yby-aggregator/job.cpp +++ b/src/tools/yby-aggregator/job.cpp @@ -1,51 +1,52 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "job.h" + +#include + #include + #include "progress.h" using namespace Yuni; using namespace Antares; /*extern*/ Job::QueueService queueService; -static Atomic::Int<> gNbJobs = 0; +static std::atomic gNbJobs = 0; #define SEP IO::Separator -Yuni::Mutex gResultsMutex; +std::mutex gResultsMutex; bool JobFileReader::RemainJobsToExecute() { return 0 != gNbJobs; } -JobFileReader::JobFileReader() : - pVariablesOn(nullptr), pDataOffset((uint)-1), pTmpResults(nullptr), pLineCount(0u) +JobFileReader::JobFileReader(): + pVariablesOn(nullptr), + pDataOffset((uint)-1), + pTmpResults(nullptr), + pLineCount(0u) { ++gNbJobs; } @@ -58,7 +59,9 @@ JobFileReader::~JobFileReader() assert(!(!output)); const uint nbVars = (uint)output->columns.size(); for (uint i = 0; i != nbVars; ++i) + { delete[] pTmpResults[i]; + } delete[] pTmpResults; } delete[] pVariablesOn; @@ -70,20 +73,30 @@ JobFileReader::~JobFileReader() void JobFileReader::onExecute() { if (!datafile || !output || !path || !output->canContinue()) + { return; + } if (!openCSVFile()) + { return; + } if (!prepareJumpTable()) + { return; + } if (pDataOffset == (uint)-1) { logs.error() << "invalid data offset"; return; } if (!readRawData()) + { return; + } if (!storeResults()) + { return; + } } bool JobFileReader::openCSVFile() @@ -121,7 +134,9 @@ bool JobFileReader::readRawData() assert(!pTmpResults); pTmpResults = new TemporaryColumnData[nbVars]; for (uint i = 0; i != nbVars; ++i) + { pTmpResults[i] = new CellData[maxRows]; + } // A buffer when dealing with rows on several file buffers CString<1024> line; @@ -140,9 +155,13 @@ bool JobFileReader::readRawData() { adapter.adapt(buffer.c_str() + offset, pos - offset); if (!adapter.empty()) + { readLine(adapter, nbLines); + } else + { logs.warning() << "Got an empty line at " << (pLineCount + 8) << ": " << pFilename; + } // Another line has been found ++nbLines; @@ -156,7 +175,9 @@ bool JobFileReader::readRawData() if (offset >= buffer.size()) { if (!pFile.read(buffer, buffer.chunkSize)) + { break; + } offset = 0; } else @@ -169,29 +190,39 @@ bool JobFileReader::readRawData() { line.append(buffer.c_str() + offset, buffer.size() - offset); if (!pFile.read(buffer, buffer.chunkSize)) + { break; + } pos = buffer.find('\n'); offset = 0; } while (pos == String::npos); // Adding the final chunk to the line currently read... if (!buffer.empty()) + { line.append(buffer.c_str(), pos); + } offset = pos + 1; // ... and analyzing it if (!line.empty()) + { readLine(line, nbLines); + } else + { logs.warning() << "Got an empty line at " << (pLineCount + 8) << "*: " << pFilename; + } // Another line has been found ++nbLines; // end-of-file if (!buffer) + { break; + } } } } while (true); @@ -239,7 +270,9 @@ void JobFileReader::readLine(const AnyString& line, uint y) String::Size pos = line.find('\t', offset); eol = (pos >= line.size()); if (eol) + { pos = line.size(); + } const uint mapping = pJumpTable[column]; if (mapping != (uint)-1) @@ -253,7 +286,9 @@ void JobFileReader::readLine(const AnyString& line, uint y) adapter.adapt(line.c_str() + offset, pos - offset); if (!adapter) + { pTmpResults[mapping][y][0] = '\0'; + } else { if (adapter.size() > maxSizePerCell - 1) @@ -265,13 +300,17 @@ void JobFileReader::readLine(const AnyString& line, uint y) else { for (uint x = 0; x != adapter.size(); ++x) + { pTmpResults[mapping][y][x] = adapter.at(x); + } pTmpResults[mapping][y][adapter.size()] = '\0'; } } } else + { logs.error() << "invalid column mapping"; + } } ++column; @@ -282,9 +321,11 @@ void JobFileReader::readLine(const AnyString& line, uint y) bool JobFileReader::storeResults() { if (!pLineCount) + { return false; + } - Yuni::MutexLocker locker(gResultsMutex); + std::lock_guard locker(gResultsMutex); // The total number of variables const uint nbVars = (uint)output->columns.size(); @@ -305,7 +346,9 @@ bool JobFileReader::storeResults() { // This variable may not have been found in the CSV file if (!pVariablesOn[v]) + { continue; + } ResultMatrix& var = allvars[v]; if (year >= var.width) @@ -319,9 +362,13 @@ bool JobFileReader::storeResults() // Allocate the memory for the result data if (Memory::Null(store.rows)) + { Memory::Allocate(store.rows, pLineCount); + } else + { logs.error() << "internal error"; + } // Copy store.height = pLineCount; @@ -340,7 +387,9 @@ bool JobFileReader::prepareJumpTable() { // Looking for the 5th line if (!pFile.read(buffer, buffer.chunkSize)) + { return false; + } String::Size offset = 0; for (uint i = 0; i != 4; ++i) @@ -378,7 +427,7 @@ bool JobFileReader::prepareJumpTable() const DataFile::ShortString& timeLevel = datafile->timeLevel; for (uint i = 0; i != list.size(); ++i) { - if (timeLevel == list[i]) + if (timeLevel.equals(list[i])) { startIndex = i + 1; break; @@ -393,7 +442,9 @@ bool JobFileReader::prepareJumpTable() pVariablesOn = new bool[output->columns.size()]; for (uint i = 0; i != output->columns.size(); ++i) + { pVariablesOn[i] = false; + } // Mapping resizeJumpTable((uint)list.size()); @@ -402,10 +453,14 @@ bool JobFileReader::prepareJumpTable() { String& entry = list[i]; if (!entry) + { continue; + } entry.trim(" \r"); if (!entry) + { continue; + } entry.toLower(); uint columnCount = (uint)output->columns.size(); @@ -425,7 +480,9 @@ bool JobFileReader::prepareJumpTable() } if (!jumpFound) + { return false; + } // Skip the next line ++pos; @@ -433,7 +490,9 @@ bool JobFileReader::prepareJumpTable() { pos = buffer.find('\n', pos); if (pos == String::npos) + { return false; + } ++pos; } diff --git a/src/tools/yby-aggregator/job.h b/src/tools/yby-aggregator/job.h index 9672a3b678..ada3263004 100644 --- a/src/tools/yby-aggregator/job.h +++ b/src/tools/yby-aggregator/job.h @@ -1,48 +1,45 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_JOB_AGGREGATOR_JOB_H__ #define __STUDY_JOB_AGGREGATOR_JOB_H__ +#include + #include #include +#include #include -#include "datafile.h" -#include "output.h" -#include "studydata.h" #include -#include -#include +#include "antares/solver/ts-generator/xcast/studydata.h" -class JobFileReader final : public Yuni::Job::IJob +#include "datafile.h" +#include "output.h" + +class JobFileReader final: public Yuni::Job::IJob { public: //! The most suitable smart pointer using Ptr = std::shared_ptr; + enum { maxRows = 8800, diff --git a/src/tools/yby-aggregator/job.hxx b/src/tools/yby-aggregator/job.hxx index 1344651de6..4e17ce3b59 100644 --- a/src/tools/yby-aggregator/job.hxx +++ b/src/tools/yby-aggregator/job.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_JOB_AGGREGATOR_JOB_HXX__ #define __STUDY_JOB_AGGREGATOR_JOB_HXX__ @@ -32,7 +26,9 @@ inline void JobFileReader::resizeJumpTable(uint newsize) pJumpTable.clear(); pJumpTable.resize(newsize); for (uint i = 0; i != newsize; ++i) + { pJumpTable[i] = (uint)-1; + } } #endif // __STUDY_JOB_AGGREGATOR_JOB_HXX__ diff --git a/src/tools/yby-aggregator/main.cpp b/src/tools/yby-aggregator/main.cpp index d44095d34e..31dd7c0cc3 100644 --- a/src/tools/yby-aggregator/main.cpp +++ b/src/tools/yby-aggregator/main.cpp @@ -1,51 +1,46 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include #include -#include -#include -#include -#include #include #include -#include #include +#include #include -#include + +#include +#include +#include #include -#include -#include "../../config.h" +#include +#include +#include +#include +#include "antares/config/config.h" +#include "antares/solver/ts-generator/xcast/studydata.h" -#include "output.h" #include "datafile.h" -#include "studydata.h" #include "job.h" +#include "output.h" #include "progress.h" using namespace Yuni; @@ -72,22 +67,30 @@ static bool DetermineOutputType(String& out, const String& original) { out.clear() << original << SEP << "economy"; if (IO::Directory::Exists(out)) + { return true; + } #ifndef YUNI_OS_WINDOWS // Before 3.8, the folder economy was named 'Economy' instead of 'economy' out.clear() << original << SEP << "Economy"; if (IO::Directory::Exists(out)) + { return true; + } #endif out.clear() << original << SEP << "adequacy"; if (IO::Directory::Exists(out)) + { return true; + } #ifndef YUNI_OS_WINDOWS out.clear() << original << SEP << "Adequacy"; // for compatibility reasons if (IO::Directory::Exists(out)) + { return true; + } #endif return false; } @@ -185,10 +188,14 @@ static void PrepareTheWork(const String::Vector& outputs, // The new output auto output = std::make_shared(info.directory(), columns); if (!output) + { continue; + } if (not FindOutputFolder(info)) + { continue; + } info.directory() << SEP << "mc-ind"; if (not IO::Directory::Exists(info.directory())) { @@ -207,7 +214,9 @@ static void PrepareTheWork(const String::Vector& outputs, ++Progress::Total; // if ((*i).size() < 5 || !(*i).startsWith("mc-i")) if ((*i).size() < 5) + { continue; + } folderName = *i; uint year; @@ -217,9 +226,13 @@ static void PrepareTheWork(const String::Vector& outputs, continue; } if (minYear > year) + { minYear = year; + } if (maxYear < year) + { maxYear = year; + } for (uint d = 0; d != dataFiles.size(); ++d) { @@ -367,11 +380,15 @@ static void ReadCommandLineOptions(int argc, char** argv) { IO::File::Stream pidfile(optPID, IO::OpenMode::write | IO::OpenMode::truncate); if (pidfile.opened()) + { pidfile << Yuni::ProcessID(); + } } if (optJobs < 1) + { optJobs = 1; + } queueService.maximumThreadCount(optJobs); } @@ -393,12 +410,18 @@ static void ReadCommandLineOptions(int argc, char** argv) String& areaname = optAreas[i]; areaname.trim(" \t\"'"); if (!areaname) + { continue; + } if (System::windows) + { newname.clear() << "areas\\" << areaname; + } else + { newname.clear() << "areas/" << areaname; + } logs.info() << "registered " << newname; studydata.push_back(std::make_shared(newname, index)); @@ -411,7 +434,9 @@ static void ReadCommandLineOptions(int argc, char** argv) String& linkfullname = optLinks[i]; linkfullname.trim(" \t\"'"); if (!linkfullname) + { continue; + } linkfullname.split(split, ","); if (split.size() != 2) { @@ -441,11 +466,15 @@ static void ReadCommandLineOptions(int argc, char** argv) optDatum.clear(); optTimes.clear(); if (dataFiles.empty()) + { return; + } // lower case for all columns for (uint i = 0; i != optColumns.size(); ++i) + { optColumns[i].toLower(); + } PrepareTheWork(optOutputs, dataFiles, studydata, optColumns); } @@ -459,15 +488,23 @@ static bool WriteAggregates() Output::Ptr output = *i; { if (!output->canContinue()) + { continue; + } const uint columnCount = (uint)output->columns.size(); if (!columnCount) + { continue; + } if (columnCount > 1) + { logs.info() << " checking " << output->path << " (" << columnCount << " variables)"; + } else + { logs.info() << " checking " << output->path << " (1 variable)"; + } } String mcvarfolder; @@ -486,7 +523,9 @@ static bool WriteAggregates() const StudyData::ShortString512& studyItemName = r->first; ResultsForAllDataLevels& alldatalevels = r->second; if (alldatalevels.empty()) + { continue; + } const ResultsForAllDataLevels::iterator tend = alldatalevels.end(); ResultsForAllDataLevels::iterator t = alldatalevels.begin(); @@ -495,7 +534,9 @@ static bool WriteAggregates() const DataFile::ShortString& dataLevelName = t->first; ResultsForAllTimeLevels& alltimelevels = t->second; if (alltimelevels.empty()) + { continue; + } const ResultsForAllTimeLevels::iterator avend = alltimelevels.end(); ResultsForAllTimeLevels::iterator av = alltimelevels.begin(); @@ -504,7 +545,9 @@ static bool WriteAggregates() const DataFile::ShortString& timeLevelName = av->first; ResultsAllVars& allvars = av->second; if (allvars.empty()) + { continue; + } if (output->columns.size() != allvars.size()) { @@ -522,7 +565,9 @@ static bool WriteAggregates() ResultMatrix& matrix = allvars[v]; if (!matrix.width) + { continue; + } uint requiredHeight = 0; for (uint y = 0; y != matrix.width; ++y) @@ -531,7 +576,9 @@ static bool WriteAggregates() if (column.height) { if (!requiredHeight) + { requiredHeight = column.height; + } else { if (column.height != requiredHeight) @@ -572,14 +619,18 @@ static bool WriteAggregates() << dataLevelName << '/' << timeLevelName << '/' << output->columns[v]; path << ".nodata"; if (!IO::File::CreateEmptyFile(path)) + { logs.error() << "I/O error: impossible to write " << path; + } } else { logs.info() << " writing " << path; logs.debug() << " (" << matrix.width << 'x' << requiredHeight << ")"; if (!matrix.saveToCSVFile(path)) + { logs.error() << "impossible to write " << path; + } // empty log entry logs.info(); } @@ -600,7 +651,9 @@ int main(int argc, char* argv[]) logs.applicationName("yby-aggregator"); if (not memory.initializeTemporaryFolder()) + { return EXIT_FAILURE; + } IntoUTF8ArgsTranslator toUTF8ArgsTranslator(argc, argv); std::tie(argc, argv) = toUTF8ArgsTranslator.convert(); @@ -625,7 +678,9 @@ int main(int argc, char* argv[]) // wait for all queues queueService.wait(Yuni::qseIdle); while (JobFileReader::RemainJobsToExecute()) + { SuspendMilliSeconds(170); + } progressBar.wait(); if (progressBar.completed()) diff --git a/src/tools/yby-aggregator/output.cpp b/src/tools/yby-aggregator/output.cpp index f0d66bb48e..22ef1b712b 100644 --- a/src/tools/yby-aggregator/output.cpp +++ b/src/tools/yby-aggregator/output.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "output.h" + #include using namespace Yuni; @@ -34,5 +29,7 @@ using namespace Antares; void Output::incrementError() { if (++errors == 100) + { logs.fatal() << "Too many errors for " << path; + } } diff --git a/src/tools/yby-aggregator/output.h b/src/tools/yby-aggregator/output.h index eb37359ba5..6f720fe713 100644 --- a/src/tools/yby-aggregator/output.h +++ b/src/tools/yby-aggregator/output.h @@ -1,36 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_OUTPUT_AGGREGATOR_OUTPUT_H__ #define __STUDY_OUTPUT_AGGREGATOR_OUTPUT_H__ -#include -#include -#include +#include #include +#include + +#include + #include "result.h" class Output final @@ -46,7 +42,9 @@ class Output final using Vector = std::vector; public: - Output(const YString& target, const YString::Vector& cols) : path(target), columns(cols) + Output(const YString& target, const YString::Vector& cols): + path(target), + columns(cols) { } @@ -69,7 +67,7 @@ class Output final //! All columns to extract const Yuni::String::Vector columns; //! The number of errors - Yuni::Atomic::Int<> errors; + std::atomic errors; //! Results ResultsForAllStudyItems results; diff --git a/src/tools/yby-aggregator/progress.cpp b/src/tools/yby-aggregator/progress.cpp index 6d3a4040df..b9406d7381 100644 --- a/src/tools/yby-aggregator/progress.cpp +++ b/src/tools/yby-aggregator/progress.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "progress.h" + #include using namespace Yuni; @@ -33,9 +28,12 @@ using namespace Antares; Progress progressBar; uint Progress::Total = 0; -Atomic::Int<> Progress::Current = 0; +std::atomic Progress::Current = 0; -Progress::Progress() : state(stReading), pCompleted(false), pLastPercent(0) +Progress::Progress(): + state(stReading), + pCompleted(false), + pLastPercent(0) { Current = 0; Total = 0; @@ -50,14 +48,18 @@ bool Progress::onInterval(uint) { // Do nothing if in silent mode if (state == stSilent) + { return true; + } const uint current = (uint)Current; const uint total = Total; uint remains = total - current; if (!total) + { return true; + } switch (state) { @@ -72,9 +74,13 @@ bool Progress::onInterval(uint) } if (remains == 1) + { logs.info() << "Running... (1 task remains)"; + } else + { logs.info() << "Running... (" << remains << " tasks remain)"; + } break; } case stWrite: diff --git a/src/tools/yby-aggregator/progress.h b/src/tools/yby-aggregator/progress.h index dfd3a1676c..835fd63a54 100644 --- a/src/tools/yby-aggregator/progress.h +++ b/src/tools/yby-aggregator/progress.h @@ -1,42 +1,38 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_JOB_AGGREGATOR_PROGRESS_H__ #define __STUDY_JOB_AGGREGATOR_PROGRESS_H__ -#include +#include + #include -#include + #include -class Progress final : public Yuni::Thread::Timer +class Progress final: public Yuni::Thread::Timer { public: //! The threading policy using ThreadingPolicy = Yuni::Thread::Timer::ThreadingPolicy; + //! Different states related to the progression enum State { @@ -48,7 +44,7 @@ class Progress final : public Yuni::Thread::Timer public: //! The number of jobs currently done - static Yuni::Atomic::Int<> Current; + static std::atomic Current; //! The total number of jobs to execute static uint Total; diff --git a/src/tools/yby-aggregator/progress.hxx b/src/tools/yby-aggregator/progress.hxx index a747636a16..6164449179 100644 --- a/src/tools/yby-aggregator/progress.hxx +++ b/src/tools/yby-aggregator/progress.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_JOB_AGGREGATOR_PROGRESS_HXX__ #define __STUDY_JOB_AGGREGATOR_PROGRESS_HXX__ diff --git a/src/tools/yby-aggregator/result.cpp b/src/tools/yby-aggregator/result.cpp index 3f44b61b1b..fa0fea177a 100644 --- a/src/tools/yby-aggregator/result.cpp +++ b/src/tools/yby-aggregator/result.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "result.h" + #include "progress.h" using namespace Yuni; @@ -44,7 +39,9 @@ void AppendToBuffer(StringT& out, const char* buffer) } // anonymous namespace -CellColumnData::CellColumnData() : rows(nullptr), height(0) +CellColumnData::CellColumnData(): + rows(nullptr), + height(0) { } @@ -56,11 +53,17 @@ CellColumnData::~CellColumnData() { } -ResultMatrix::ResultMatrix() : columns(nullptr), width(0), heightAfterAggregation(0) +ResultMatrix::ResultMatrix(): + columns(nullptr), + width(0), + heightAfterAggregation(0) { } -ResultMatrix::ResultMatrix(const ResultMatrix&) : columns(NULL), width(0), heightAfterAggregation(0) +ResultMatrix::ResultMatrix(const ResultMatrix&): + columns(nullptr), + width(0), + heightAfterAggregation(0) { } @@ -80,7 +83,9 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const { IO::File::Stream file; if (!file.openRW(filename)) + { return false; + } Progress::Total = heightAfterAggregation; String buffer; @@ -99,19 +104,25 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const { buffer << '\t'; for (uint i = 0; i < width; ++i) + { buffer << '\t' << "year"; + } buffer << '\n'; buffer << '\t'; for (uint i = 0; i < width; ++i) + { buffer << '\t' << (i + 1); + } buffer << '\n'; } for (uint r = 0; r != 1; ++r) { buffer << '\t'; for (uint i = 0; i < width; ++i) + { buffer << '\t'; + } buffer << '\n'; } } @@ -122,9 +133,12 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const { dataBufferHeight = 100 }; + CellData* dataBuffer[dataBufferHeight]; for (uint d = 0; d != dataBufferHeight; ++d) + { dataBuffer[d] = new CellData[width]; + } uint dataBufferOffset = 0; for (uint y = 0; y != heightAfterAggregation; ++y) @@ -139,8 +153,9 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const for (uint offset = 0; offset != maxH; ++offset) { assert(offset + y < columns[x].height); - memcpy( - dataBuffer[offset][x], columns[x].rows[offset + y], maxSizePerCell); + memcpy(dataBuffer[offset][x], + columns[x].rows[offset + y], + maxSizePerCell); } } else @@ -148,8 +163,9 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const for (uint offset = 0; offset != dataBufferHeight; ++offset) { assert(offset + y < columns[x].height); - memcpy( - dataBuffer[offset][x], columns[x].rows[offset + y], maxSizePerCell); + memcpy(dataBuffer[offset][x], + columns[x].rows[offset + y], + maxSizePerCell); } } } @@ -171,11 +187,15 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const buffer << '\n'; ++Progress::Current; if (++dataBufferOffset == dataBufferHeight) + { dataBufferOffset = 0; + } } for (uint d = 0; d != dataBufferHeight; ++d) + { delete[] dataBuffer[d]; + } } else { @@ -183,12 +203,16 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const { buffer << '\t' << (1 + y) << '\t'; if (columns[0].rows) + { AppendToBuffer(buffer, columns[0].rows[y]); + } for (uint x = 1; x < width; ++x) { buffer << '\t'; if (columns[x].rows) + { AppendToBuffer(buffer, columns[x].rows[y]); + } if (buffer.size() > 1024 * 1024 * 8) { @@ -202,6 +226,8 @@ bool ResultMatrix::saveToCSVFile(const String& filename) const } if (not buffer.empty()) + { file << buffer; + } return true; } diff --git a/src/tools/yby-aggregator/result.h b/src/tools/yby-aggregator/result.h index 08acbc0350..b2e2b2b1a8 100644 --- a/src/tools/yby-aggregator/result.h +++ b/src/tools/yby-aggregator/result.h @@ -1,36 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_RESULT_AGGREGATOR_RESULT_H__ #define __STUDY_RESULT_AGGREGATOR_RESULT_H__ +#include + #include #include -#include + #include +#include "antares/solver/ts-generator/xcast/studydata.h" + #include "datafile.h" #include "studydata.h" diff --git a/src/tools/yby-aggregator/studydata.h b/src/tools/yby-aggregator/studydata.h index 25406fae65..6a60912022 100644 --- a/src/tools/yby-aggregator/studydata.h +++ b/src/tools/yby-aggregator/studydata.h @@ -1,37 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __STUDY_STUDY_DATA_AGGREGATOR_STUDY_DATA_H__ #define __STUDY_STUDY_DATA_AGGREGATOR_STUDY_DATA_H__ -#include -#include #include #include +#include +#include + class StudyData final { public: @@ -46,7 +41,9 @@ class StudyData final public: template - StudyData(const StringT& n, uint i) : index(i), name(n) + StudyData(const StringT& n, uint i): + index(i), + name(n) { } diff --git a/src/tools/yby-aggregator/variable.h b/src/tools/yby-aggregator/variable.h index 71a73c018c..fd364cadb9 100644 --- a/src/tools/yby-aggregator/variable.h +++ b/src/tools/yby-aggregator/variable.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __YBY_AGGREGATOR_VARIABLE_H__ #define __YBY_AGGREGATOR_VARIABLE_H__ diff --git a/src/triplets/x64-linux-antares.cmake b/src/triplets/x64-linux-antares.cmake new file mode 100644 index 0000000000..63954c80c5 --- /dev/null +++ b/src/triplets/x64-linux-antares.cmake @@ -0,0 +1,5 @@ +set(VCPKG_TARGET_ARCHITECTURE x64) +set(VCPKG_CMAKE_SYSTEM_NAME Linux) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE static) + diff --git a/src/triplets/x64-linux-release.cmake b/src/triplets/x64-linux-release.cmake new file mode 100644 index 0000000000..d9eb98ddae --- /dev/null +++ b/src/triplets/x64-linux-release.cmake @@ -0,0 +1,7 @@ +set(VCPKG_TARGET_ARCHITECTURE x64) +set(VCPKG_CMAKE_SYSTEM_NAME Linux) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE static) + +# Avoid building debug artifacts +set(VCPKG_BUILD_TYPE release) diff --git a/src/triplets/x64-windows-antares.cmake b/src/triplets/x64-windows-antares.cmake new file mode 100644 index 0000000000..f2480f7012 --- /dev/null +++ b/src/triplets/x64-windows-antares.cmake @@ -0,0 +1,11 @@ +set(VCPKG_TARGET_ARCHITECTURE x64) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE dynamic) + +# Link zlib and minizip statically +list(APPEND STATIC_PORTS "zlib.*" "minizip.*") +foreach (STATIC_PORT IN LISTS STATIC_PORTS) + if(PORT MATCHES ${STATIC_PORT}) + set(VCPKG_LIBRARY_LINKAGE static) + endif() +endforeach () diff --git a/src/triplets/x64-windows-release.cmake b/src/triplets/x64-windows-release.cmake new file mode 100644 index 0000000000..7e4eb27f4d --- /dev/null +++ b/src/triplets/x64-windows-release.cmake @@ -0,0 +1,15 @@ +set(VCPKG_TARGET_ARCHITECTURE x64) + +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE dynamic) + +# Avoid building debug artifacts +set(VCPKG_BUILD_TYPE release) + +# Link zlib and minizip statically +list(APPEND STATIC_PORTS "zlib.*" "minizip.*") +foreach (STATIC_PORT IN LISTS STATIC_PORTS) + if(PORT MATCHES ${STATIC_PORT}) + set(VCPKG_LIBRARY_LINKAGE static) + endif() +endforeach () diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 0c8f846f96..8bb000564a 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -1,9 +1,4 @@ - -if (USE_PRECOMPILED_EXT AND UNIX) - set (wxWidgets_CONFIG_EXECUTABLE ${DEPS_INSTALL_DIR}/bin/wx-config) -endif() - #wxWidget required find_package(wxWidgets REQUIRED COMPONENTS net core base richtext propgrid aui adv html xml) include(${wxWidgets_USE_FILE}) diff --git a/src/ui/action/CMakeLists.txt b/src/ui/action/CMakeLists.txt index d69627811e..4e806f0500 100644 --- a/src/ui/action/CMakeLists.txt +++ b/src/ui/action/CMakeLists.txt @@ -132,13 +132,12 @@ target_link_libraries(antares-action Antares::result_writer #study.h Antares::date #parameters Antares::inifile #parameters - Antares::object Antares::study ) target_include_directories(antares-action - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include + PUBLIC + $ ) add_library(Antares::action ALIAS antares-action) diff --git a/src/ui/action/action.cpp b/src/ui/action/action.cpp index 60b0915589..c902bd346a 100644 --- a/src/ui/action/action.cpp +++ b/src/ui/action/action.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include -#include +#include "antares/antares/antares.h" using namespace Yuni; diff --git a/src/ui/action/behavior.cpp b/src/ui/action/behavior.cpp index 3caefb7c0e..915b4cb126 100644 --- a/src/ui/action/behavior.cpp +++ b/src/ui/action/behavior.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/action/context.cpp b/src/ui/action/context.cpp index 7e26fb20ed..2b28568b0b 100644 --- a/src/ui/action/context.cpp +++ b/src/ui/action/context.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/action/handler/antares-study/area/allocation-hydro-post.cpp b/src/ui/action/handler/antares-study/area/allocation-hydro-post.cpp index f36c8bd8d9..bf6885d3b1 100644 --- a/src/ui/action/handler/antares-study/area/allocation-hydro-post.cpp +++ b/src/ui/action/handler/antares-study/area/allocation-hydro-post.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "allocation-hydro-post.h" +#include namespace Antares { diff --git a/src/ui/action/handler/antares-study/area/allocation-hydro-post.h b/src/ui/action/handler/antares-study/area/allocation-hydro-post.h index 1305383c3a..175fa3562b 100644 --- a/src/ui/action/handler/antares-study/area/allocation-hydro-post.h +++ b/src/ui/action/handler/antares-study/area/allocation-hydro-post.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_ALLOCATION_HYDRO_POST_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_ALLOCATION_HYDRO_POST_H__ diff --git a/src/ui/action/handler/antares-study/area/allocation-hydro-post.hxx b/src/ui/action/handler/antares-study/area/allocation-hydro-post.hxx index a6ffe558c9..37b7b7cdba 100644 --- a/src/ui/action/handler/antares-study/area/allocation-hydro-post.hxx +++ b/src/ui/action/handler/antares-study/area/allocation-hydro-post.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_ALLOCATION_HYDRO_POST_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_ALLOCATION_HYDRO_POST_HXX__ diff --git a/src/ui/action/handler/antares-study/area/allocation-hydro.cpp b/src/ui/action/handler/antares-study/area/allocation-hydro.cpp index 338b1a1902..d29dca00da 100644 --- a/src/ui/action/handler/antares-study/area/allocation-hydro.cpp +++ b/src/ui/action/handler/antares-study/area/allocation-hydro.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "allocation-hydro.h" diff --git a/src/ui/action/handler/antares-study/area/allocation-hydro.h b/src/ui/action/handler/antares-study/area/allocation-hydro.h index ff49f00e22..80857b30ff 100644 --- a/src/ui/action/handler/antares-study/area/allocation-hydro.h +++ b/src/ui/action/handler/antares-study/area/allocation-hydro.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_ALLOCATION_HYDRO_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_ALLOCATION_HYDRO_H__ diff --git a/src/ui/action/handler/antares-study/area/color.cpp b/src/ui/action/handler/antares-study/area/color.cpp index 8f35b2e406..e8a150ecc5 100644 --- a/src/ui/action/handler/antares-study/area/color.cpp +++ b/src/ui/action/handler/antares-study/area/color.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "color.h" diff --git a/src/ui/action/handler/antares-study/area/color.h b/src/ui/action/handler/antares-study/area/color.h index 3b59eb21ba..2c21a51286 100644 --- a/src/ui/action/handler/antares-study/area/color.h +++ b/src/ui/action/handler/antares-study/area/color.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_COLOR_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_COLOR_H__ diff --git a/src/ui/action/handler/antares-study/area/correlation-post.cpp b/src/ui/action/handler/antares-study/area/correlation-post.cpp index 727a9c7a5f..543fc9b3af 100644 --- a/src/ui/action/handler/antares-study/area/correlation-post.cpp +++ b/src/ui/action/handler/antares-study/area/correlation-post.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "correlation-post.h" diff --git a/src/ui/action/handler/antares-study/area/correlation-post.h b/src/ui/action/handler/antares-study/area/correlation-post.h index ef832eade9..ef606d8fe6 100644 --- a/src/ui/action/handler/antares-study/area/correlation-post.h +++ b/src/ui/action/handler/antares-study/area/correlation-post.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CORRELATION_POST_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CORRELATION_POST_H__ diff --git a/src/ui/action/handler/antares-study/area/correlation-post.hxx b/src/ui/action/handler/antares-study/area/correlation-post.hxx index 2d9e831ab7..3dc40be91b 100644 --- a/src/ui/action/handler/antares-study/area/correlation-post.hxx +++ b/src/ui/action/handler/antares-study/area/correlation-post.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CORRELATION_POST_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CORRELATION_POST_HXX__ diff --git a/src/ui/action/handler/antares-study/area/correlation.cpp b/src/ui/action/handler/antares-study/area/correlation.cpp index c6c685c81f..3a31d05abb 100644 --- a/src/ui/action/handler/antares-study/area/correlation.cpp +++ b/src/ui/action/handler/antares-study/area/correlation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "correlation.h" diff --git a/src/ui/action/handler/antares-study/area/correlation.h b/src/ui/action/handler/antares-study/area/correlation.h index 08a6b77caa..f6c568744f 100644 --- a/src/ui/action/handler/antares-study/area/correlation.h +++ b/src/ui/action/handler/antares-study/area/correlation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CORRELATION_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CORRELATION_H__ diff --git a/src/ui/action/handler/antares-study/area/create.cpp b/src/ui/action/handler/antares-study/area/create.cpp index 0348c2d253..4b9bd41a68 100644 --- a/src/ui/action/handler/antares-study/area/create.cpp +++ b/src/ui/action/handler/antares-study/area/create.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -227,7 +221,7 @@ bool Create::performWL(Context& ctx) } } ctx.autoselectAreas.push_back(ctx.area); - return (ctx.area != NULL); + return (ctx.area); } void Create::createActionsForAStandardAreaCopy(Context& ctx, bool copyPosition) @@ -293,11 +287,9 @@ void Create::createActionsForAStandardAreaCopy(Context& ctx, bool copyPosition) auto* root = new RootNodePlant(pOriginalAreaName); // browsing each thermal cluster - auto end = area->thermal.list.end(); - for (auto i = area->thermal.list.begin(); i != end; ++i) - { - *root += StandardActionsToCopyThermalCluster(pOriginalAreaName, i->second->name()); - } + for (auto c : area->thermal.list.all()) + *root += StandardActionsToCopyThermalCluster(pOriginalAreaName, c->name()); + *this += root; } } diff --git a/src/ui/action/handler/antares-study/area/filtering.cpp b/src/ui/action/handler/antares-study/area/filtering.cpp index 2c7157deda..0113c78e71 100644 --- a/src/ui/action/handler/antares-study/area/filtering.cpp +++ b/src/ui/action/handler/antares-study/area/filtering.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "filtering.h" diff --git a/src/ui/action/handler/antares-study/area/filtering.h b/src/ui/action/handler/antares-study/area/filtering.h index 840977fe0c..6108f5ccbd 100644 --- a/src/ui/action/handler/antares-study/area/filtering.h +++ b/src/ui/action/handler/antares-study/area/filtering.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_FILTERING_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_FILTERING_H__ diff --git a/src/ui/action/handler/antares-study/area/misc-gen.cpp b/src/ui/action/handler/antares-study/area/misc-gen.cpp index 0394eb47c2..dfb7e975fa 100644 --- a/src/ui/action/handler/antares-study/area/misc-gen.cpp +++ b/src/ui/action/handler/antares-study/area/misc-gen.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "misc-gen.h" diff --git a/src/ui/action/handler/antares-study/area/misc-gen.h b/src/ui/action/handler/antares-study/area/misc-gen.h index da10675ed8..ba1c772c7a 100644 --- a/src/ui/action/handler/antares-study/area/misc-gen.h +++ b/src/ui/action/handler/antares-study/area/misc-gen.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_MISC_GEN_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_MISC_GEN_H__ diff --git a/src/ui/action/handler/antares-study/area/nodal-optimization.cpp b/src/ui/action/handler/antares-study/area/nodal-optimization.cpp index fb47e4c16e..b067361593 100644 --- a/src/ui/action/handler/antares-study/area/nodal-optimization.cpp +++ b/src/ui/action/handler/antares-study/area/nodal-optimization.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "nodal-optimization.h" diff --git a/src/ui/action/handler/antares-study/area/nodal-optimization.h b/src/ui/action/handler/antares-study/area/nodal-optimization.h index 94e363db18..5d131f8bf4 100644 --- a/src/ui/action/handler/antares-study/area/nodal-optimization.h +++ b/src/ui/action/handler/antares-study/area/nodal-optimization.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_NODAL_OPTIMIZATION_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_NODAL_OPTIMIZATION_H__ diff --git a/src/ui/action/handler/antares-study/area/position.cpp b/src/ui/action/handler/antares-study/area/position.cpp index 76fb683883..19b75abecf 100644 --- a/src/ui/action/handler/antares-study/area/position.cpp +++ b/src/ui/action/handler/antares-study/area/position.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "position.h" diff --git a/src/ui/action/handler/antares-study/area/position.h b/src/ui/action/handler/antares-study/area/position.h index 8767dfdb0b..44d324447a 100644 --- a/src/ui/action/handler/antares-study/area/position.h +++ b/src/ui/action/handler/antares-study/area/position.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_POSITION_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_POSITION_H__ diff --git a/src/ui/action/handler/antares-study/area/reserves.cpp b/src/ui/action/handler/antares-study/area/reserves.cpp index 015b3473fb..351bd4b2e5 100644 --- a/src/ui/action/handler/antares-study/area/reserves.cpp +++ b/src/ui/action/handler/antares-study/area/reserves.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "reserves.h" diff --git a/src/ui/action/handler/antares-study/area/reserves.h b/src/ui/action/handler/antares-study/area/reserves.h index da891cee89..7281413541 100644 --- a/src/ui/action/handler/antares-study/area/reserves.h +++ b/src/ui/action/handler/antares-study/area/reserves.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_RESERVES_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_RESERVES_H__ diff --git a/src/ui/action/handler/antares-study/area/timeseries.cpp b/src/ui/action/handler/antares-study/area/timeseries.cpp index a1070c0d4c..8d775229a8 100644 --- a/src/ui/action/handler/antares-study/area/timeseries.cpp +++ b/src/ui/action/handler/antares-study/area/timeseries.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "timeseries.h" @@ -137,42 +131,33 @@ bool DataTimeseries::performWL(Context& ctx) { case Data::timeSeriesLoad: { - ctx.area->load.series->timeSeries = source->load.series->timeSeries; - source->load.series->timeSeries.unloadFromMemory(); + ctx.area->load.series.timeSeries = source->load.series.timeSeries; + source->load.series.timeSeries.unloadFromMemory(); break; } case Data::timeSeriesSolar: { - ctx.area->solar.series->timeSeries = source->solar.series->timeSeries; - source->solar.series->timeSeries.unloadFromMemory(); + ctx.area->solar.series.timeSeries = source->solar.series.timeSeries; + source->solar.series.timeSeries.unloadFromMemory(); break; } case Data::timeSeriesWind: { - ctx.area->wind.series->timeSeries = source->wind.series->timeSeries; - source->wind.series->timeSeries.unloadFromMemory(); + ctx.area->wind.series.timeSeries = source->wind.series.timeSeries; + source->wind.series.timeSeries.unloadFromMemory(); break; } case Data::timeSeriesHydro: { - ctx.area->hydro.series->ror = source->hydro.series->ror; - ctx.area->hydro.series->storage = source->hydro.series->storage; - ctx.area->hydro.series->mingen = source->hydro.series->mingen; - - ctx.area->hydro.series->count = source->hydro.series->count; - - source->hydro.series->ror.unloadFromMemory(); - source->hydro.series->storage.unloadFromMemory(); - source->hydro.series->mingen.unloadFromMemory(); - + ctx.area->hydro.series->copyGenerationTS(*source->hydro.series); break; } case Data::timeSeriesThermal: { if (ctx.cluster && ctx.originalPlant && ctx.cluster != ctx.originalPlant) { - ctx.cluster->series->timeSeries = ctx.originalPlant->series->timeSeries; - ctx.originalPlant->series->timeSeries.unloadFromMemory(); + ctx.cluster->series.timeSeries = ctx.originalPlant->series.timeSeries; + ctx.originalPlant->series.timeSeries.unloadFromMemory(); } break; } diff --git a/src/ui/action/handler/antares-study/area/timeseries.h b/src/ui/action/handler/antares-study/area/timeseries.h index 0100e95986..acb9402be7 100644 --- a/src/ui/action/handler/antares-study/area/timeseries.h +++ b/src/ui/action/handler/antares-study/area/timeseries.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TIMESERIES_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TIMESERIES_H__ diff --git a/src/ui/action/handler/antares-study/area/ts-generator.cpp b/src/ui/action/handler/antares-study/area/ts-generator.cpp index 95c8e02482..842b6a2c50 100644 --- a/src/ui/action/handler/antares-study/area/ts-generator.cpp +++ b/src/ui/action/handler/antares-study/area/ts-generator.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "ts-generator.h" diff --git a/src/ui/action/handler/antares-study/area/ts-generator.h b/src/ui/action/handler/antares-study/area/ts-generator.h index a761128fe8..b8bd0fc8ea 100644 --- a/src/ui/action/handler/antares-study/area/ts-generator.h +++ b/src/ui/action/handler/antares-study/area/ts-generator.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TS_GENERATOR_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TS_GENERATOR_H__ diff --git a/src/ui/action/handler/antares-study/area/ts-node.cpp b/src/ui/action/handler/antares-study/area/ts-node.cpp index b9d3d81dfb..9f158878f7 100644 --- a/src/ui/action/handler/antares-study/area/ts-node.cpp +++ b/src/ui/action/handler/antares-study/area/ts-node.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "ts-node.h" @@ -110,7 +104,7 @@ bool NodeTimeseries::performWL(Context& ctx) case Data::timeSeriesThermal: if (ctx.cluster) { - ctx.cluster->series->timeSeries.reset(1, HOURS_PER_YEAR); + ctx.cluster->series.timeSeries.reset(1, HOURS_PER_YEAR); ctx.cluster->prepro->reset(); ctx.cluster->ecoInput.reset(); } diff --git a/src/ui/action/handler/antares-study/area/ts-node.h b/src/ui/action/handler/antares-study/area/ts-node.h index 94d332e5aa..19e0fe9a42 100644 --- a/src/ui/action/handler/antares-study/area/ts-node.h +++ b/src/ui/action/handler/antares-study/area/ts-node.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TS_NODE_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TS_NODE_H__ diff --git a/src/ui/action/handler/antares-study/area/ts-node.hxx b/src/ui/action/handler/antares-study/area/ts-node.hxx index e4ccdbcf08..eac1c0fb7f 100644 --- a/src/ui/action/handler/antares-study/area/ts-node.hxx +++ b/src/ui/action/handler/antares-study/area/ts-node.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TS_NODE_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_TS_NODE_HXX__ diff --git a/src/ui/action/handler/antares-study/constraint/comments.cpp b/src/ui/action/handler/antares-study/constraint/comments.cpp index 5fe38f0407..489a50a8f0 100644 --- a/src/ui/action/handler/antares-study/constraint/comments.cpp +++ b/src/ui/action/handler/antares-study/constraint/comments.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "comments.h" +#include "antares/utils/utils.h" namespace Antares { diff --git a/src/ui/action/handler/antares-study/constraint/comments.h b/src/ui/action/handler/antares-study/constraint/comments.h index bad0e94f45..4f61341737 100644 --- a/src/ui/action/handler/antares-study/constraint/comments.h +++ b/src/ui/action/handler/antares-study/constraint/comments.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_COMMENTS_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_COMMENTS_H__ diff --git a/src/ui/action/handler/antares-study/constraint/comments.hxx b/src/ui/action/handler/antares-study/constraint/comments.hxx index ec9b2a857d..5f611a8f81 100644 --- a/src/ui/action/handler/antares-study/constraint/comments.hxx +++ b/src/ui/action/handler/antares-study/constraint/comments.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_COMMENTS_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_COMMENTS_HXX__ diff --git a/src/ui/action/handler/antares-study/constraint/create.cpp b/src/ui/action/handler/antares-study/constraint/create.cpp index 288551dcba..fe223495e1 100644 --- a/src/ui/action/handler/antares-study/constraint/create.cpp +++ b/src/ui/action/handler/antares-study/constraint/create.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -34,6 +28,7 @@ #include "weights.h" #include "offsets.h" #include "enabled.h" +#include "antares/utils/utils.h" using namespace Yuni; @@ -205,7 +200,7 @@ bool Create::performWL(Context& ctx) // ctx.constraint->type(pType); } ctx.autoselectConstraints.push_back(ctx.constraint); - return (ctx.constraint != NULL); + return (ctx.constraint != nullptr); } void Create::createActionsForAStandardConstraintCopy(Context&) diff --git a/src/ui/action/handler/antares-study/constraint/data.cpp b/src/ui/action/handler/antares-study/constraint/data.cpp index 1639c4960d..13cb7e9fe0 100644 --- a/src/ui/action/handler/antares-study/constraint/data.cpp +++ b/src/ui/action/handler/antares-study/constraint/data.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "data.h" +#include namespace Antares { diff --git a/src/ui/action/handler/antares-study/constraint/data.h b/src/ui/action/handler/antares-study/constraint/data.h index 3490b67803..c20dfcbb72 100644 --- a/src/ui/action/handler/antares-study/constraint/data.h +++ b/src/ui/action/handler/antares-study/constraint/data.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_DATA_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_DATA_H__ diff --git a/src/ui/action/handler/antares-study/constraint/data.hxx b/src/ui/action/handler/antares-study/constraint/data.hxx index 81186fe7ac..c8dfcf3838 100644 --- a/src/ui/action/handler/antares-study/constraint/data.hxx +++ b/src/ui/action/handler/antares-study/constraint/data.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_DATA_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_DATA_HXX__ diff --git a/src/ui/action/handler/antares-study/constraint/enabled.cpp b/src/ui/action/handler/antares-study/constraint/enabled.cpp index 20a997ec80..8ea3a864a3 100644 --- a/src/ui/action/handler/antares-study/constraint/enabled.cpp +++ b/src/ui/action/handler/antares-study/constraint/enabled.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "enabled.h" +#include namespace Antares { diff --git a/src/ui/action/handler/antares-study/constraint/enabled.h b/src/ui/action/handler/antares-study/constraint/enabled.h index 025616a16c..6ebad92298 100644 --- a/src/ui/action/handler/antares-study/constraint/enabled.h +++ b/src/ui/action/handler/antares-study/constraint/enabled.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_ENABLED_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_ENABLED_H__ diff --git a/src/ui/action/handler/antares-study/constraint/enabled.hxx b/src/ui/action/handler/antares-study/constraint/enabled.hxx index 5a21c8594a..12e236117a 100644 --- a/src/ui/action/handler/antares-study/constraint/enabled.hxx +++ b/src/ui/action/handler/antares-study/constraint/enabled.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_ENABLED_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_ENABLED_HXX__ diff --git a/src/ui/action/handler/antares-study/constraint/offsets.cpp b/src/ui/action/handler/antares-study/constraint/offsets.cpp index 3c160d81cb..8bf90571ec 100644 --- a/src/ui/action/handler/antares-study/constraint/offsets.cpp +++ b/src/ui/action/handler/antares-study/constraint/offsets.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "offsets.h" +#include using namespace Yuni; @@ -38,7 +33,7 @@ namespace AntaresStudy namespace Constraint { Offsets::Offsets(const AnyString& name, Antares::Data::ConstraintName targetName) : - pOriginalConstraintName(name), targetName(targetName), pCurrentContext(NULL) + pOriginalConstraintName(name), targetName(targetName), pCurrentContext(nullptr) { pInfos.caption << "Offsets"; } @@ -103,15 +98,12 @@ bool Offsets::performWL(Context& ctx) if (source && source != ctx.constraint) { pCurrentContext = &ctx; - Bind tr; - if (!targetName.empty()) - { - tr.bind(this, &Offsets::toLower); - } - else - { - tr.bind(this, &Offsets::translate); - } + const std::function tr + = std::bind(targetName.empty() ? &Offsets::translate : &Offsets::toLower, + this, + std::placeholders::_1, + std::placeholders::_2); + ctx.constraint->copyOffsets(*ctx.study, *source, true, tr); pCurrentContext = nullptr; return true; diff --git a/src/ui/action/handler/antares-study/constraint/offsets.h b/src/ui/action/handler/antares-study/constraint/offsets.h index 3dfe671579..12992e1bec 100644 --- a/src/ui/action/handler/antares-study/constraint/offsets.h +++ b/src/ui/action/handler/antares-study/constraint/offsets.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_OFFSETS_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_OFFSETS_H__ diff --git a/src/ui/action/handler/antares-study/constraint/weights.cpp b/src/ui/action/handler/antares-study/constraint/weights.cpp index dc35745214..ad9691ace5 100644 --- a/src/ui/action/handler/antares-study/constraint/weights.cpp +++ b/src/ui/action/handler/antares-study/constraint/weights.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "weights.h" +#include "antares/utils/utils.h" using namespace Yuni; @@ -38,7 +33,7 @@ namespace AntaresStudy namespace Constraint { Weights::Weights(const AnyString& name, Antares::Data::ConstraintName targetName) : - pOriginalConstraintName(name), targetName(targetName), pCurrentContext(NULL) + pOriginalConstraintName(name), targetName(targetName), pCurrentContext(nullptr) { pInfos.caption << "Weights"; } @@ -103,15 +98,11 @@ bool Weights::performWL(Context& ctx) if (source && source != ctx.constraint) { pCurrentContext = &ctx; - Bind tr; - if (!targetName.empty()) - { - tr.bind(this, &Weights::toLower); - } - else - { - tr.bind(this, &Weights::translate); - } + const std::function tr + = std::bind(targetName.empty() ? &Weights::translate : &Weights::toLower, + this, + std::placeholders::_1, + std::placeholders::_2); ctx.constraint->copyWeights(*ctx.study, *source, true, tr); pCurrentContext = nullptr; return true; diff --git a/src/ui/action/handler/antares-study/constraint/weights.h b/src/ui/action/handler/antares-study/constraint/weights.h index 50630a0257..cee40bc50c 100644 --- a/src/ui/action/handler/antares-study/constraint/weights.h +++ b/src/ui/action/handler/antares-study/constraint/weights.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_WEIGHTS_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_WEIGHTS_H__ diff --git a/src/ui/action/handler/antares-study/link/comments.cpp b/src/ui/action/handler/antares-study/link/comments.cpp index 88a193e044..b6b98a3db7 100644 --- a/src/ui/action/handler/antares-study/link/comments.cpp +++ b/src/ui/action/handler/antares-study/link/comments.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "comments.h" +#include namespace Antares { diff --git a/src/ui/action/handler/antares-study/link/comments.h b/src/ui/action/handler/antares-study/link/comments.h index d6377f4bc3..adb4dd41c4 100644 --- a/src/ui/action/handler/antares-study/link/comments.h +++ b/src/ui/action/handler/antares-study/link/comments.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_COMMENTS_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_COMMENTS_H__ diff --git a/src/ui/action/handler/antares-study/link/comments.hxx b/src/ui/action/handler/antares-study/link/comments.hxx index 88b448dda2..e519ecb7f0 100644 --- a/src/ui/action/handler/antares-study/link/comments.hxx +++ b/src/ui/action/handler/antares-study/link/comments.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_COMMENTS_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_COMMENTS_HXX__ diff --git a/src/ui/action/handler/antares-study/link/copper-plate.cpp b/src/ui/action/handler/antares-study/link/copper-plate.cpp index 0f818a0b47..16296ced67 100644 --- a/src/ui/action/handler/antares-study/link/copper-plate.cpp +++ b/src/ui/action/handler/antares-study/link/copper-plate.cpp @@ -1,39 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "copper-plate.h" +#include -namespace Antares -{ -namespace Action -{ -namespace AntaresStudy -{ -namespace Link +namespace Antares::Action::AntaresStudy::Link { CopperPlate::CopperPlate(const AnyString& fromarea, const AnyString& toarea) : pOriginalFromAreaName(fromarea), pOriginalToAreaName(toarea) @@ -86,7 +75,7 @@ bool CopperPlate::performWL(Context& ctx) return false; } -} // namespace Link -} // namespace AntaresStudy -} // namespace Action -} // namespace Antares +} // namespace Antares::Action::AntaresStudy::Link + + + diff --git a/src/ui/action/handler/antares-study/link/copper-plate.h b/src/ui/action/handler/antares-study/link/copper-plate.h index 8a193333c9..ea01863d34 100644 --- a/src/ui/action/handler/antares-study/link/copper-plate.h +++ b/src/ui/action/handler/antares-study/link/copper-plate.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_COPPERPLATE_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_COPPERPLATE_H__ diff --git a/src/ui/action/handler/antares-study/link/create.cpp b/src/ui/action/handler/antares-study/link/create.cpp index c1148a2589..87d12281f6 100644 --- a/src/ui/action/handler/antares-study/link/create.cpp +++ b/src/ui/action/handler/antares-study/link/create.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -34,6 +28,7 @@ #include "copper-plate.h" #include "unload-data.h" #include "filtering.h" +#include using namespace Yuni; diff --git a/src/ui/action/handler/antares-study/link/filtering.cpp b/src/ui/action/handler/antares-study/link/filtering.cpp index bcca275da3..912ade560f 100644 --- a/src/ui/action/handler/antares-study/link/filtering.cpp +++ b/src/ui/action/handler/antares-study/link/filtering.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "filtering.h" +#include using namespace Yuni; diff --git a/src/ui/action/handler/antares-study/link/filtering.h b/src/ui/action/handler/antares-study/link/filtering.h index 20403e1638..8cecb2605b 100644 --- a/src/ui/action/handler/antares-study/link/filtering.h +++ b/src/ui/action/handler/antares-study/link/filtering.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_FILTERING_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_FILTERING_H__ diff --git a/src/ui/action/handler/antares-study/link/hurdles-cost.cpp b/src/ui/action/handler/antares-study/link/hurdles-cost.cpp index d50be1d4d3..dd87661ad6 100644 --- a/src/ui/action/handler/antares-study/link/hurdles-cost.cpp +++ b/src/ui/action/handler/antares-study/link/hurdles-cost.cpp @@ -1,40 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "hurdles-cost.h" +#include "antares/utils/utils.h" #include +#include -namespace Antares -{ -namespace Action -{ -namespace AntaresStudy -{ -namespace Link +namespace Antares::Action::AntaresStudy::Link { HurdlesCost::HurdlesCost(const AnyString& fromarea, const AnyString& toarea) : pOriginalFromAreaName(fromarea), pOriginalToAreaName(toarea) @@ -98,7 +88,4 @@ bool HurdlesCost::performWL(Context& ctx) return false; } -} // namespace Link -} // namespace AntaresStudy -} // namespace Action -} // namespace Antares +} // namespace Antares::Action::AntaresStudy::Link diff --git a/src/ui/action/handler/antares-study/link/hurdles-cost.h b/src/ui/action/handler/antares-study/link/hurdles-cost.h index c436ad8f06..34d2162a63 100644 --- a/src/ui/action/handler/antares-study/link/hurdles-cost.h +++ b/src/ui/action/handler/antares-study/link/hurdles-cost.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREAHURDLES_COST_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREAHURDLES_COST_H__ diff --git a/src/ui/action/handler/antares-study/link/impedances.cpp b/src/ui/action/handler/antares-study/link/impedances.cpp index 757ccb2231..52ee60bfc9 100644 --- a/src/ui/action/handler/antares-study/link/impedances.cpp +++ b/src/ui/action/handler/antares-study/link/impedances.cpp @@ -1,32 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "impedances.h" #include +#include namespace Antares { diff --git a/src/ui/action/handler/antares-study/link/impedances.h b/src/ui/action/handler/antares-study/link/impedances.h index 47a1d22c3e..96629c202b 100644 --- a/src/ui/action/handler/antares-study/link/impedances.h +++ b/src/ui/action/handler/antares-study/link/impedances.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_IMPEDANCES_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_IMPEDANCES_H__ diff --git a/src/ui/action/handler/antares-study/link/ntc.cpp b/src/ui/action/handler/antares-study/link/ntc.cpp index 772f7eae6e..6ed1a9dfb1 100644 --- a/src/ui/action/handler/antares-study/link/ntc.cpp +++ b/src/ui/action/handler/antares-study/link/ntc.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "ntc.h" -#include +#include namespace Antares { @@ -83,12 +77,12 @@ bool NTC::performWL(Context& ctx) // Direct capacities source->directCapacities.forceReload(true); ctx.link->directCapacities.forceReload(true); - ctx.link->directCapacities.pasteToColumn(0, source->directCapacities.entry[0]); + ctx.link->directCapacities.timeSeries.pasteToColumn(0, source->directCapacities.timeSeries.entry[0]); // Indirect capacities source->indirectCapacities.forceReload(true); ctx.link->indirectCapacities.forceReload(true); - ctx.link->indirectCapacities.pasteToColumn(0, source->indirectCapacities.entry[0]); + ctx.link->indirectCapacities.timeSeries.pasteToColumn(0, source->indirectCapacities.timeSeries.entry[0]); return true; } else diff --git a/src/ui/action/handler/antares-study/link/ntc.h b/src/ui/action/handler/antares-study/link/ntc.h index fe109e5cca..4183a1ae5c 100644 --- a/src/ui/action/handler/antares-study/link/ntc.h +++ b/src/ui/action/handler/antares-study/link/ntc.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_NTC_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_NTC_H__ diff --git a/src/ui/action/handler/antares-study/link/unload-data.cpp b/src/ui/action/handler/antares-study/link/unload-data.cpp index 0e00430948..21e99cddaf 100644 --- a/src/ui/action/handler/antares-study/link/unload-data.cpp +++ b/src/ui/action/handler/antares-study/link/unload-data.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "unload-data.h" +#include namespace Antares { diff --git a/src/ui/action/handler/antares-study/link/unload-data.h b/src/ui/action/handler/antares-study/link/unload-data.h index a5ad39f864..1d43a3a533 100644 --- a/src/ui/action/handler/antares-study/link/unload-data.h +++ b/src/ui/action/handler/antares-study/link/unload-data.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_UNLOAD_DATA_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_UNLOAD_DATA_H__ diff --git a/src/ui/action/handler/antares-study/link/unload-data.hxx b/src/ui/action/handler/antares-study/link/unload-data.hxx index 076a736ae6..00b5cb26b5 100644 --- a/src/ui/action/handler/antares-study/link/unload-data.hxx +++ b/src/ui/action/handler/antares-study/link/unload-data.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_UNLOAD_DATA_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_UNLOAD_DATA_HXX__ diff --git a/src/ui/action/handler/antares-study/thermal-cluster/common.cpp b/src/ui/action/handler/antares-study/thermal-cluster/common.cpp index 9f9e289b87..d4beef6631 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/common.cpp +++ b/src/ui/action/handler/antares-study/thermal-cluster/common.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "common.h" diff --git a/src/ui/action/handler/antares-study/thermal-cluster/common.h b/src/ui/action/handler/antares-study/thermal-cluster/common.h index 6fca3397d5..87121191a3 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/common.h +++ b/src/ui/action/handler/antares-study/thermal-cluster/common.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_THERMAL_PLANT_COMMON_H__ #define __ANTARES_LIBS_STUDY_ACTION_THERMAL_PLANT_COMMON_H__ diff --git a/src/ui/action/handler/antares-study/thermal-cluster/create.cpp b/src/ui/action/handler/antares-study/thermal-cluster/create.cpp index 07eb50f546..6a71b98626 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/create.cpp +++ b/src/ui/action/handler/antares-study/thermal-cluster/create.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "create.h" +#include "antares/utils/utils.h" using namespace Yuni; @@ -85,7 +80,7 @@ bool Create::prepareWL(Context& ctx) if (suffix == "" || pInfos.behavior == bhMerge) { TransformNameIntoID(pFuturPlantName, id); - clusterFound = area ? area->thermal.list.find(id) : nullptr; + clusterFound = area ? area->thermal.list.findInAll(id) : nullptr; if (clusterFound) { Data::AreaName::Size sepPos = id.find_last_of('-'); @@ -106,7 +101,7 @@ bool Create::prepareWL(Context& ctx) pFuturPlantName.clear() << pTargetPlantName << "-" << indx; id.clear(); TransformNameIntoID(pFuturPlantName, id); - clusterFound = area->thermal.list.find(id); + clusterFound = area->thermal.list.findInAll(id); } while (clusterFound); } } @@ -114,13 +109,13 @@ bool Create::prepareWL(Context& ctx) { pFuturPlantName += suffix; TransformNameIntoID(pFuturPlantName, id); - clusterFound = area ? area->thermal.list.find(id) : nullptr; + clusterFound = area ? area->thermal.list.findInAll(id) : nullptr; } } else { TransformNameIntoID(pFuturPlantName, id); - clusterFound = area ? area->thermal.list.find(id) : nullptr; + clusterFound = area ? area->thermal.list.findInAll(id) : nullptr; } pInfos.caption.clear() << "Plant " << pFuturPlantName; @@ -166,7 +161,7 @@ bool Create::performWL(Context& ctx) if (!source) return false; TransformNameIntoID(pOriginalPlantName, id); - ctx.originalPlant = source->thermal.list.find(id); + ctx.originalPlant = source->thermal.list.findInAll(id); if (!ctx.originalPlant) return false; @@ -174,22 +169,20 @@ bool Create::performWL(Context& ctx) id.clear(); TransformNameIntoID(pFuturPlantName, id); - ctx.cluster = ctx.area->thermal.list.find(id); + ctx.cluster = ctx.area->thermal.list.findInAll(id); if (!ctx.cluster) { ctx.cluster = new Data::ThermalCluster(ctx.area); ctx.cluster->setName(pFuturPlantName); ctx.cluster->reset(); - (ctx.area)->thermal.list.add(std::shared_ptr(ctx.cluster)); - (ctx.area)->thermal.list.rebuildIndex(); - (ctx.area)->thermal.prepareAreaWideIndexes(); + (ctx.area)->thermal.list.addToCompleteList(std::shared_ptr(ctx.cluster)); } else { if (pInfos.behavior == bhOverwrite) (ctx.cluster)->reset(); } - return (ctx.area != NULL); + return (ctx.area != nullptr); } return true; } diff --git a/src/ui/action/handler/antares-study/thermal-cluster/create.h b/src/ui/action/handler/antares-study/thermal-cluster/create.h index dab1991af7..7450447c23 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/create.h +++ b/src/ui/action/handler/antares-study/thermal-cluster/create.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_THERMAL_PLANT_CREATE_H__ #define __ANTARES_LIBS_STUDY_ACTION_THERMAL_PLANT_CREATE_H__ diff --git a/src/ui/action/handler/antares-study/thermal-cluster/create.hxx b/src/ui/action/handler/antares-study/thermal-cluster/create.hxx index ff5dcc528f..5a0131a36f 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/create.hxx +++ b/src/ui/action/handler/antares-study/thermal-cluster/create.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_THERMAL_PLANT_CREATE_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_THERMAL_PLANT_CREATE_HXX__ diff --git a/src/ui/action/handler/antares-study/thermal-cluster/root-node.cpp b/src/ui/action/handler/antares-study/thermal-cluster/root-node.cpp index ab183e7ba4..01b034da80 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/root-node.cpp +++ b/src/ui/action/handler/antares-study/thermal-cluster/root-node.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "root-node.h" @@ -86,7 +80,7 @@ bool RootNode::performWL(Context& ctx) { // bool forcePlantCreate = ctx.clusterForceCreate[pOriginalAreaName]; if (pInfos.behavior == bhOverwrite) - ctx.area->thermal.list.clear(); + ctx.area->thermal.list.clearAll(); return true; } return false; diff --git a/src/ui/action/handler/antares-study/thermal-cluster/root-node.h b/src/ui/action/handler/antares-study/thermal-cluster/root-node.h index d0f47f2489..fca1636888 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/root-node.h +++ b/src/ui/action/handler/antares-study/thermal-cluster/root-node.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_PLANT_ROOT_NODE_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_PLANT_ROOT_NODE_H__ diff --git a/src/ui/action/handler/antares-study/thermal-cluster/root-node.hxx b/src/ui/action/handler/antares-study/thermal-cluster/root-node.hxx index 3d6a496174..3ffeebf871 100644 --- a/src/ui/action/handler/antares-study/thermal-cluster/root-node.hxx +++ b/src/ui/action/handler/antares-study/thermal-cluster/root-node.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_PLANT_ROOT_NODE_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_PLANT_ROOT_NODE_HXX__ diff --git a/src/ui/action/include/action/action.h b/src/ui/action/include/action/action.h index 2bd12cadf2..1594e9626b 100644 --- a/src/ui/action/include/action/action.h +++ b/src/ui/action/include/action/action.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_ACTION_H__ #define __ANTARES_LIBS_STUDY_ACTION_ACTION_H__ diff --git a/src/ui/action/include/action/action.hxx b/src/ui/action/include/action/action.hxx index 2ffc5a0e7e..b336b6d530 100644 --- a/src/ui/action/include/action/action.hxx +++ b/src/ui/action/include/action/action.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_ACTION_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_ACTION_HXX__ diff --git a/src/ui/action/include/action/behavior.h b/src/ui/action/include/action/behavior.h index 159dc7ab4f..6087b80c51 100644 --- a/src/ui/action/include/action/behavior.h +++ b/src/ui/action/include/action/behavior.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_BEHAVIOR_H__ #define __ANTARES_LIBS_STUDY_ACTION_BEHAVIOR_H__ diff --git a/src/ui/action/include/action/context.h b/src/ui/action/include/action/context.h index deec4fde08..76fc2f4bb4 100644 --- a/src/ui/action/include/action/context.h +++ b/src/ui/action/include/action/context.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_CONTEXT_H__ #define __ANTARES_LIBS_STUDY_ACTION_CONTEXT_H__ diff --git a/src/ui/action/include/action/fwd.h b/src/ui/action/include/action/fwd.h index b659b45cd8..85622d414b 100644 --- a/src/ui/action/include/action/fwd.h +++ b/src/ui/action/include/action/fwd.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_FWD_H__ #define __ANTARES_LIBS_STUDY_ACTION_FWD_H__ diff --git a/src/ui/action/include/action/handler/antares-study/area/create.h b/src/ui/action/include/action/handler/antares-study/area/create.h index 5f85eda12a..9f97588b32 100644 --- a/src/ui/action/include/action/handler/antares-study/area/create.h +++ b/src/ui/action/include/action/handler/antares-study/area/create.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CREATE_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CREATE_H__ diff --git a/src/ui/action/include/action/handler/antares-study/area/create.hxx b/src/ui/action/include/action/handler/antares-study/area/create.hxx index 17b2a3bd80..53217ff05a 100644 --- a/src/ui/action/include/action/handler/antares-study/area/create.hxx +++ b/src/ui/action/include/action/handler/antares-study/area/create.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CREATE_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_AREA_CREATE_HXX__ diff --git a/src/ui/action/include/action/handler/antares-study/constraint/create.h b/src/ui/action/include/action/handler/antares-study/constraint/create.h index 789c900dcf..bf3640b2e4 100644 --- a/src/ui/action/include/action/handler/antares-study/constraint/create.h +++ b/src/ui/action/include/action/handler/antares-study/constraint/create.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_CREATE_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_CREATE_H__ diff --git a/src/ui/action/include/action/handler/antares-study/constraint/create.hxx b/src/ui/action/include/action/handler/antares-study/constraint/create.hxx index a2f1d7f95b..b8cea59f32 100644 --- a/src/ui/action/include/action/handler/antares-study/constraint/create.hxx +++ b/src/ui/action/include/action/handler/antares-study/constraint/create.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_CREATE_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_CONSTRAINT_CREATE_HXX__ diff --git a/src/ui/action/include/action/handler/antares-study/link/create.h b/src/ui/action/include/action/handler/antares-study/link/create.h index 721fea131e..62f1c4c19b 100644 --- a/src/ui/action/include/action/handler/antares-study/link/create.h +++ b/src/ui/action/include/action/handler/antares-study/link/create.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_CREATE_H__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_CREATE_H__ diff --git a/src/ui/action/include/action/handler/antares-study/link/create.hxx b/src/ui/action/include/action/handler/antares-study/link/create.hxx index a1ab14b205..51923821f4 100644 --- a/src/ui/action/include/action/handler/antares-study/link/create.hxx +++ b/src/ui/action/include/action/handler/antares-study/link/create.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_CREATE_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_HANDLER_ANTARES_LINK_CREATE_HXX__ diff --git a/src/ui/action/include/action/settings/decal-area-position.h b/src/ui/action/include/action/settings/decal-area-position.h index e104c5227b..e3f6e8da1f 100644 --- a/src/ui/action/include/action/settings/decal-area-position.h +++ b/src/ui/action/include/action/settings/decal-area-position.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_DECAL_AREA_POSITION_H__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_DECAL_AREA_POSITION_H__ diff --git a/src/ui/action/include/action/settings/decal-area-position.hxx b/src/ui/action/include/action/settings/decal-area-position.hxx index 371053c6ed..a8d671a924 100644 --- a/src/ui/action/include/action/settings/decal-area-position.hxx +++ b/src/ui/action/include/action/settings/decal-area-position.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_DECAL_AREA_POSITION_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_DECAL_AREA_POSITION_HXX__ diff --git a/src/ui/action/include/action/settings/suffix-for-area-names.h b/src/ui/action/include/action/settings/suffix-for-area-names.h index 46285a7b6a..d488d98dc4 100644 --- a/src/ui/action/include/action/settings/suffix-for-area-names.h +++ b/src/ui/action/include/action/settings/suffix-for-area-names.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXAREA_NAME_H__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXAREA_NAME_H__ diff --git a/src/ui/action/include/action/settings/suffix-for-area-names.hxx b/src/ui/action/include/action/settings/suffix-for-area-names.hxx index 9465eeda9c..da566c9ed0 100644 --- a/src/ui/action/include/action/settings/suffix-for-area-names.hxx +++ b/src/ui/action/include/action/settings/suffix-for-area-names.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXAREA_NAME_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXAREA_NAME_HXX__ diff --git a/src/ui/action/include/action/settings/suffix-for-cluster-names.h b/src/ui/action/include/action/settings/suffix-for-cluster-names.h index b56ba41cc5..b526d7ae78 100644 --- a/src/ui/action/include/action/settings/suffix-for-cluster-names.h +++ b/src/ui/action/include/action/settings/suffix-for-cluster-names.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIX_CLUSTER_NAME_H__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIX_CLUSTER_NAME_H__ diff --git a/src/ui/action/include/action/settings/suffix-for-cluster-names.hxx b/src/ui/action/include/action/settings/suffix-for-cluster-names.hxx index 5b8625b7f0..eb8683e2ea 100644 --- a/src/ui/action/include/action/settings/suffix-for-cluster-names.hxx +++ b/src/ui/action/include/action/settings/suffix-for-cluster-names.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIX_CLUSTER_NAME_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIX_CLUSTER_NAME_HXX__ diff --git a/src/ui/action/include/action/settings/suffix-for-constraint-names.h b/src/ui/action/include/action/settings/suffix-for-constraint-names.h index 233f759e1c..1d4d77c5a8 100644 --- a/src/ui/action/include/action/settings/suffix-for-constraint-names.h +++ b/src/ui/action/include/action/settings/suffix-for-constraint-names.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXCONSTRAINT_NAME_H__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXCONSTRAINT_NAME_H__ diff --git a/src/ui/action/include/action/settings/suffix-for-constraint-names.hxx b/src/ui/action/include/action/settings/suffix-for-constraint-names.hxx index bf3db605de..4df9930a6a 100644 --- a/src/ui/action/include/action/settings/suffix-for-constraint-names.hxx +++ b/src/ui/action/include/action/settings/suffix-for-constraint-names.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXCONSTRAINT_NAME_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_SETTINGS_SUFFIXCONSTRAINT_NAME_HXX__ diff --git a/src/ui/action/include/action/state.h b/src/ui/action/include/action/state.h index 56915b42aa..cc6e1c1fe6 100644 --- a/src/ui/action/include/action/state.h +++ b/src/ui/action/include/action/state.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_STATE_H__ #define __ANTARES_LIBS_STUDY_ACTION_STATE_H__ diff --git a/src/ui/action/include/action/text.h b/src/ui/action/include/action/text.h index 71b3e10170..40f52ad7bc 100644 --- a/src/ui/action/include/action/text.h +++ b/src/ui/action/include/action/text.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_TEXT_H__ #define __ANTARES_LIBS_STUDY_ACTION_TEXT_H__ diff --git a/src/ui/action/include/action/text.hxx b/src/ui/action/include/action/text.hxx index da5098a0c8..b2b16313a0 100644 --- a/src/ui/action/include/action/text.hxx +++ b/src/ui/action/include/action/text.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LIBS_STUDY_ACTION_TEXT_HXX__ #define __ANTARES_LIBS_STUDY_ACTION_TEXT_HXX__ diff --git a/src/ui/action/settings/decal-area-position.cpp b/src/ui/action/settings/decal-area-position.cpp index da7ca27c24..614a620c48 100644 --- a/src/ui/action/settings/decal-area-position.cpp +++ b/src/ui/action/settings/decal-area-position.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/action/settings/suffix-for-area-names.cpp b/src/ui/action/settings/suffix-for-area-names.cpp index 602c6f7d1d..a93d77cbab 100644 --- a/src/ui/action/settings/suffix-for-area-names.cpp +++ b/src/ui/action/settings/suffix-for-area-names.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/action/settings/suffix-for-cluster-names.cpp b/src/ui/action/settings/suffix-for-cluster-names.cpp index 8ef5a91ecb..3064e3152f 100644 --- a/src/ui/action/settings/suffix-for-cluster-names.cpp +++ b/src/ui/action/settings/suffix-for-cluster-names.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/action/settings/suffix-for-constraint-names.cpp b/src/ui/action/settings/suffix-for-constraint-names.cpp index df62a1adc6..be36dffdff 100644 --- a/src/ui/action/settings/suffix-for-constraint-names.cpp +++ b/src/ui/action/settings/suffix-for-constraint-names.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/action/state.cpp b/src/ui/action/state.cpp index 3f171c4785..e484613ba4 100644 --- a/src/ui/action/state.cpp +++ b/src/ui/action/state.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/common/CMakeLists.txt b/src/ui/common/CMakeLists.txt index 3425ec03e0..597413bc47 100644 --- a/src/ui/common/CMakeLists.txt +++ b/src/ui/common/CMakeLists.txt @@ -80,6 +80,7 @@ target_link_libraries(antares-ui-component-spotlight PRIVATE antares-core antares-ui-common + Antares::locator ) # Component panel @@ -93,8 +94,8 @@ set(SRC_COMPONENT_PANEL add_library(antares-ui-component-panel ${SRC_COMPONENT_PANEL}) target_include_directories( antares-ui-component-panel - PRIVATE - ${CMAKE_SOURCE_DIR}/libs + PRIVATE + $ ) target_link_libraries(antares-ui-component-panel PUBLIC diff --git a/src/ui/common/component/frame/frame.h b/src/ui/common/component/frame/frame.h index cbae25b51c..5390e43f1b 100644 --- a/src/ui/common/component/frame/frame.h +++ b/src/ui/common/component/frame/frame.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_COMPONENTS_FRAME_FRAME_H__ #define __ANTARES_COMMON_COMPONENTS_FRAME_FRAME_H__ diff --git a/src/ui/common/component/frame/local-frame.cpp b/src/ui/common/component/frame/local-frame.cpp index e8cb261b35..cf10aa4cc5 100644 --- a/src/ui/common/component/frame/local-frame.cpp +++ b/src/ui/common/component/frame/local-frame.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/common/component/frame/local-frame.h b/src/ui/common/component/frame/local-frame.h index da8e3f3fbf..9adf4e7250 100644 --- a/src/ui/common/component/frame/local-frame.h +++ b/src/ui/common/component/frame/local-frame.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_COMPONENTS_FRAME_LOCAL_FRAME_H__ #define __ANTARES_COMMON_COMPONENTS_FRAME_LOCAL_FRAME_H__ @@ -52,7 +46,7 @@ class WxLocalFrame : public wxFrame, public IFrame virtual ~WxLocalFrame(); - virtual bool Destroy(); + virtual bool Destroy() override; virtual bool excludeFromMenu() override; virtual void updateOpenWindowsMenu() override; diff --git a/src/ui/common/component/frame/registry.cpp b/src/ui/common/component/frame/registry.cpp index eb1d8d856d..e363f7dfe3 100644 --- a/src/ui/common/component/frame/registry.cpp +++ b/src/ui/common/component/frame/registry.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/common/component/frame/registry.h b/src/ui/common/component/frame/registry.h index 52d7ab9c65..cc3b9a30d4 100644 --- a/src/ui/common/component/frame/registry.h +++ b/src/ui/common/component/frame/registry.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_COMPONENTS_FRAME_REGISTRY_H__ #define __ANTARES_COMMON_COMPONENTS_FRAME_REGISTRY_H__ diff --git a/src/ui/common/component/panel.h b/src/ui/common/component/panel.h index 1b1b262c5a..5d94d02491 100644 --- a/src/ui/common/component/panel.h +++ b/src/ui/common/component/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_PANEL_H__ #define __ANTARES_COMMON_PANEL_H__ diff --git a/src/ui/common/component/panel/group.cpp b/src/ui/common/component/panel/group.cpp index 221508b21f..c0a02738b3 100644 --- a/src/ui/common/component/panel/group.cpp +++ b/src/ui/common/component/panel/group.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "group.h" diff --git a/src/ui/common/component/panel/group.h b/src/ui/common/component/panel/group.h index b440489f30..43327d157b 100644 --- a/src/ui/common/component/panel/group.h +++ b/src/ui/common/component/panel/group.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_COMPONENTS_PANEL_GROUP_H__ #define __ANTARES_COMMON_COMPONENTS_PANEL_GROUP_H__ diff --git a/src/ui/common/component/panel/panel.cpp b/src/ui/common/component/panel/panel.cpp index 5033b88019..03ff527c59 100644 --- a/src/ui/common/component/panel/panel.cpp +++ b/src/ui/common/component/panel/panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" @@ -46,9 +40,9 @@ Panel::Panel(wxWindow* parent) : { assert(parent && "invalid parent"); - Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(Panel::onInternalMotion), NULL, this); - Connect(GetId(), wxEVT_LEFT_DOWN, wxMouseEventHandler(Panel::onInternalMouseDown), NULL, this); - Connect(GetId(), wxEVT_LEFT_UP, wxMouseEventHandler(Panel::onInternalMouseUp), NULL, this); + Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(Panel::onInternalMotion), nullptr, this); + Connect(GetId(), wxEVT_LEFT_DOWN, wxMouseEventHandler(Panel::onInternalMouseDown), nullptr, this); + Connect(GetId(), wxEVT_LEFT_UP, wxMouseEventHandler(Panel::onInternalMouseUp), nullptr, this); } Panel::~Panel() diff --git a/src/ui/common/component/panel/panel.h b/src/ui/common/component/panel/panel.h index bae1f6ea4c..46c3a79978 100644 --- a/src/ui/common/component/panel/panel.h +++ b/src/ui/common/component/panel/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_COMPONENTS_PANEL_PANEL_H__ #define __ANTARES_COMMON_COMPONENTS_PANEL_PANEL_H__ diff --git a/src/ui/common/component/scrollbox/scrollbox.cpp b/src/ui/common/component/scrollbox/scrollbox.cpp index 734bb3d5c7..f3c707b38a 100644 --- a/src/ui/common/component/scrollbox/scrollbox.cpp +++ b/src/ui/common/component/scrollbox/scrollbox.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scrollbox.h" diff --git a/src/ui/common/component/scrollbox/scrollbox.h b/src/ui/common/component/scrollbox/scrollbox.h index 718e449683..03c7ce4ce1 100644 --- a/src/ui/common/component/scrollbox/scrollbox.h +++ b/src/ui/common/component/scrollbox/scrollbox.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_SCROLLBOX_H__ #define __ANTARES_TOOLBOX_COMPONENTS_SCROLLBOX_H__ diff --git a/src/ui/common/component/spotlight.h b/src/ui/common/component/spotlight.h index 0b4cce09a4..43c74af880 100644 --- a/src/ui/common/component/spotlight.h +++ b/src/ui/common/component/spotlight.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_H__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_H__ diff --git a/src/ui/common/component/spotlight/iitem.cpp b/src/ui/common/component/spotlight/iitem.cpp index b329ebe8e0..707393b8af 100644 --- a/src/ui/common/component/spotlight/iitem.cpp +++ b/src/ui/common/component/spotlight/iitem.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "spotlight.h" diff --git a/src/ui/common/component/spotlight/iitem.h b/src/ui/common/component/spotlight/iitem.h index 5dafc9b7ee..1dc088aa04 100644 --- a/src/ui/common/component/spotlight/iitem.h +++ b/src/ui/common/component/spotlight/iitem.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_IITEM_H__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_IITEM_H__ diff --git a/src/ui/common/component/spotlight/iitem.hxx b/src/ui/common/component/spotlight/iitem.hxx index 893f1af5a2..faab46d5f8 100644 --- a/src/ui/common/component/spotlight/iitem.hxx +++ b/src/ui/common/component/spotlight/iitem.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_IITEM_HXX__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_IITEM_HXX__ diff --git a/src/ui/common/component/spotlight/listbox-panel.cpp b/src/ui/common/component/spotlight/listbox-panel.cpp index 969d9672a3..5624e51d2a 100644 --- a/src/ui/common/component/spotlight/listbox-panel.cpp +++ b/src/ui/common/component/spotlight/listbox-panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "spotlight.h" @@ -222,7 +216,8 @@ void ListboxPanel::onDraw(wxPaintEvent&) { auto& item = *(items[i]); auto& group = item.group(); - if (!(!group) && group != pLastGroupName) + + if (!(!group) && YString(group) != pLastGroupName) pLastGroupName = group; } continue; @@ -234,7 +229,7 @@ void ListboxPanel::onDraw(wxPaintEvent&) // Draw of the group name if the flag is enabled if ((0 != (pFlags & Spotlight::optGroups))) { - if (!(!group) && group != pLastGroupName) + if (!(!group) && YString(group) != pLastGroupName) { // Drawing the new group bounds.x = 0; diff --git a/src/ui/common/component/spotlight/listbox-panel.h b/src/ui/common/component/spotlight/listbox-panel.h index dfb21959b1..415ebf822d 100644 --- a/src/ui/common/component/spotlight/listbox-panel.h +++ b/src/ui/common/component/spotlight/listbox-panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_COMPONENT_SPOTLIGHT_LISTBOX_PANEL_H__ #define __ANTARES_COMMON_COMPONENT_SPOTLIGHT_LISTBOX_PANEL_H__ diff --git a/src/ui/common/component/spotlight/mini-frame.cpp b/src/ui/common/component/spotlight/mini-frame.cpp index 94a88496c0..b9ca7b4253 100644 --- a/src/ui/common/component/spotlight/mini-frame.cpp +++ b/src/ui/common/component/spotlight/mini-frame.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "mini-frame.h" diff --git a/src/ui/common/component/spotlight/mini-frame.h b/src/ui/common/component/spotlight/mini-frame.h index ad00cd738e..d68667a764 100644 --- a/src/ui/common/component/spotlight/mini-frame.h +++ b/src/ui/common/component/spotlight/mini-frame.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_MINIFRAME_H__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_MINIFRAME_H__ diff --git a/src/ui/common/component/spotlight/null-provider.h b/src/ui/common/component/spotlight/null-provider.h index 5e7af0c266..a6085bfb7e 100644 --- a/src/ui/common/component/spotlight/null-provider.h +++ b/src/ui/common/component/spotlight/null-provider.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_NULL_PROVIDER_HXX__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_NULL_PROVIDER_HXX__ diff --git a/src/ui/common/component/spotlight/provider.h b/src/ui/common/component/spotlight/provider.h index f8dfc3b912..ef8c0a2e7a 100644 --- a/src/ui/common/component/spotlight/provider.h +++ b/src/ui/common/component/spotlight/provider.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_PROVIDER_HXX__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_PROVIDER_HXX__ diff --git a/src/ui/common/component/spotlight/search-png.hxx b/src/ui/common/component/spotlight/search-png.hxx index 05b51da1d3..619dc5ea71 100644 --- a/src/ui/common/component/spotlight/search-png.hxx +++ b/src/ui/common/component/spotlight/search-png.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ static const unsigned char search_png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, diff --git a/src/ui/common/component/spotlight/searchtoken.h b/src/ui/common/component/spotlight/searchtoken.h index 9a443a8fc5..c3e6194137 100644 --- a/src/ui/common/component/spotlight/searchtoken.h +++ b/src/ui/common/component/spotlight/searchtoken.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_SEARCH_TOKEN_HXX__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_SEARCH_TOKEN_HXX__ diff --git a/src/ui/common/component/spotlight/separator.cpp b/src/ui/common/component/spotlight/separator.cpp index c4671d95d2..113f21b96f 100644 --- a/src/ui/common/component/spotlight/separator.cpp +++ b/src/ui/common/component/spotlight/separator.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "spotlight.h" diff --git a/src/ui/common/component/spotlight/separator.h b/src/ui/common/component/spotlight/separator.h index 710773211b..6a5e213950 100644 --- a/src/ui/common/component/spotlight/separator.h +++ b/src/ui/common/component/spotlight/separator.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_SEPARATOR_H__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_SEPARATOR_H__ diff --git a/src/ui/common/component/spotlight/spotlight.cpp b/src/ui/common/component/spotlight/spotlight.cpp index fae03ffbb1..09e381034e 100644 --- a/src/ui/common/component/spotlight/spotlight.cpp +++ b/src/ui/common/component/spotlight/spotlight.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "spotlight.h" @@ -128,7 +122,7 @@ void Spotlight::createComponents(Spotlight* parent, bool input, bool results) wxDefaultPosition, wxDefaultSize, 0, - NULL, + nullptr, wxCB_READONLY); pLayerFilter->SetFont(wxFont(wxFontInfo().Bold())); pLayerFilter->AppendString("All"); @@ -435,9 +429,9 @@ void Spotlight::resizeParentWindow() parent->SetSize(parent->GetSize().GetWidth(), idealH); } - assert(parent->GetSizer() != NULL); + assert(parent->GetSizer()); parent->GetSizer()->Layout(); - assert(GetSizer() != NULL); + assert(GetSizer()); GetSizer()->Layout(); Dispatcher::GUI::Refresh(parent); } diff --git a/src/ui/common/component/spotlight/spotlight.h b/src/ui/common/component/spotlight/spotlight.h index 820e46b6b9..6a33d9bebd 100644 --- a/src/ui/common/component/spotlight/spotlight.h +++ b/src/ui/common/component/spotlight/spotlight.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_H__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_H__ diff --git a/src/ui/common/component/spotlight/spotlight.hxx b/src/ui/common/component/spotlight/spotlight.hxx index cb0c6de858..5e880f7903 100644 --- a/src/ui/common/component/spotlight/spotlight.hxx +++ b/src/ui/common/component/spotlight/spotlight.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_HXX__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_HXX__ diff --git a/src/ui/common/component/spotlight/text.cpp b/src/ui/common/component/spotlight/text.cpp index 291e99525b..a7dcb4c9c8 100644 --- a/src/ui/common/component/spotlight/text.cpp +++ b/src/ui/common/component/spotlight/text.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "spotlight.h" diff --git a/src/ui/common/component/spotlight/text.h b/src/ui/common/component/spotlight/text.h index 8bc92e1def..3c8e6507f6 100644 --- a/src/ui/common/component/spotlight/text.h +++ b/src/ui/common/component/spotlight/text.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_TEXT_H__ #define __ANTARES_UI_COMMON_COMPONENT_SPOTLIGHT_SPOTLIGHT_TEXT_H__ diff --git a/src/ui/common/dispatcher.h b/src/ui/common/dispatcher.h index ce085ac3ef..72453f14e0 100644 --- a/src/ui/common/dispatcher.h +++ b/src/ui/common/dispatcher.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_EVENT_H__ #define __ANTARES_COMMON_EVENT_H__ diff --git a/src/ui/common/dispatcher/action.cpp b/src/ui/common/dispatcher/action.cpp index ab03ec2f60..be721728be 100644 --- a/src/ui/common/dispatcher/action.cpp +++ b/src/ui/common/dispatcher/action.cpp @@ -1,30 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include #include #include #include @@ -50,7 +45,7 @@ using DispatcherServiceType = Yuni::Job::QueueService; static DispatcherServiceType gDispatcher; static LinkedList gGUIDispatcherList; -static Yuni::Mutex gGUIMutex; +static std::mutex gGUIMutex; class JobDelay final : public Yuni::Job::IJob { @@ -144,7 +139,7 @@ void Wait() bool Empty() { - Yuni::MutexLocker locker(Antares::Dispatcher::gGUIMutex); + std::lock_guard locker(Antares::Dispatcher::gGUIMutex); return Antares::Dispatcher::gGUIDispatcherList.empty(); } diff --git a/src/ui/common/dispatcher/action.h b/src/ui/common/dispatcher/action.h index c93011013e..85ef0bc9c7 100644 --- a/src/ui/common/dispatcher/action.h +++ b/src/ui/common/dispatcher/action.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_ACTION_ACTION_H__ #define __ANTARES_COMMON_ACTION_ACTION_H__ diff --git a/src/ui/common/dispatcher/action.hxx b/src/ui/common/dispatcher/action.hxx index 2697dbca2a..4381832981 100644 --- a/src/ui/common/dispatcher/action.hxx +++ b/src/ui/common/dispatcher/action.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_ACTION_ACTION_HXX__ #define __ANTARES_COMMON_ACTION_ACTION_HXX__ diff --git a/src/ui/common/dispatcher/dispatcher.h b/src/ui/common/dispatcher/dispatcher.h index 0f10e65e4b..46f723669d 100644 --- a/src/ui/common/dispatcher/dispatcher.h +++ b/src/ui/common/dispatcher/dispatcher.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_DISPATCHER_DISPATCHER_H__ #define __ANTARES_DISPATCHER_DISPATCHER_H__ diff --git a/src/ui/common/dispatcher/gui.cpp b/src/ui/common/dispatcher/gui.cpp index 1ba4cc4e56..cb134fe113 100644 --- a/src/ui/common/dispatcher/gui.cpp +++ b/src/ui/common/dispatcher/gui.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "gui.h" diff --git a/src/ui/common/dispatcher/gui.h b/src/ui/common/dispatcher/gui.h index 4ebc3b06cb..8086416288 100644 --- a/src/ui/common/dispatcher/gui.h +++ b/src/ui/common/dispatcher/gui.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_ACTION_GUI_H__ #define __ANTARES_TOOLBOX_ACTION_GUI_H__ diff --git a/src/ui/common/dispatcher/gui.hxx b/src/ui/common/dispatcher/gui.hxx index 48396ffd0c..413f7a5eb2 100644 --- a/src/ui/common/dispatcher/gui.hxx +++ b/src/ui/common/dispatcher/gui.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_ACTION_GUI_HXX__ #define __ANTARES_TOOLBOX_ACTION_GUI_HXX__ diff --git a/src/ui/common/dispatcher/settings.cpp b/src/ui/common/dispatcher/settings.cpp index 7dfd0c93c5..2686ac170c 100644 --- a/src/ui/common/dispatcher/settings.cpp +++ b/src/ui/common/dispatcher/settings.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "settings.h" diff --git a/src/ui/common/dispatcher/settings.h b/src/ui/common/dispatcher/settings.h index 6734385585..cdab218d35 100644 --- a/src/ui/common/dispatcher/settings.h +++ b/src/ui/common/dispatcher/settings.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_COMMON_ACTION_SETTINGS_H__ #define __ANTARES_COMMON_ACTION_SETTINGS_H__ diff --git a/src/ui/common/fwd.h b/src/ui/common/fwd.h index de790de897..9dd3023b95 100644 --- a/src/ui/common/fwd.h +++ b/src/ui/common/fwd.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FWD_H__ #define __ANTARES_TOOLBOX_FWD_H__ diff --git a/src/ui/common/lock.cpp b/src/ui/common/lock.cpp index b3f0bb649d..e41c76275d 100644 --- a/src/ui/common/lock.cpp +++ b/src/ui/common/lock.cpp @@ -1,39 +1,33 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "lock.h" -#include #include +#include namespace Antares { -static Yuni::Atomic::Int<32> gGUIFlushRefCount = 0; +static std::atomic gGUIFlushRefCount = 0; -static Yuni::Atomic::Int<32> GUIIsAboutToQuitFlag = false; +static std::atomic GUIIsAboutToQuitFlag = false; bool IsGUIAboutToQuit() { diff --git a/src/ui/common/lock.h b/src/ui/common/lock.h index 6e13e6c6b6..0070ee7bff 100644 --- a/src/ui/common/lock.h +++ b/src/ui/common/lock.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_UI_COMMON_LOCK_H__ #define __ANTARES_UI_COMMON_LOCK_H__ diff --git a/src/ui/common/wx-wrapper.cpp b/src/ui/common/wx-wrapper.cpp index ecf1a02c79..bfd2d1f16b 100644 --- a/src/ui/common/wx-wrapper.cpp +++ b/src/ui/common/wx-wrapper.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "wx-wrapper.h" diff --git a/src/ui/common/wx-wrapper.h b/src/ui/common/wx-wrapper.h index 3665586687..7cb3778a19 100644 --- a/src/ui/common/wx-wrapper.h +++ b/src/ui/common/wx-wrapper.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_WX_WIDGETS_H__ #define __ANTARES_TOOLBOX_WX_WIDGETS_H__ diff --git a/src/ui/common/wx-wrapper.hxx b/src/ui/common/wx-wrapper.hxx index e2a1187ffd..c1942c124e 100644 --- a/src/ui/common/wx-wrapper.hxx +++ b/src/ui/common/wx-wrapper.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_WX_WIDGETS_HXX__ #define __ANTARES_TOOLBOX_WX_WIDGETS_HXX__ diff --git a/src/ui/simulator/CMakeLists.txt b/src/ui/simulator/CMakeLists.txt index 4e048c02ce..36a8c431fa 100644 --- a/src/ui/simulator/CMakeLists.txt +++ b/src/ui/simulator/CMakeLists.txt @@ -1,6 +1,6 @@ #Define executable name -set(execname "antares-${ANTARES_PRG_VERSION}-ui-simulator") +set(execname "antares-ui-simulator") # WxCore include("cmake/wxcore.cmake") @@ -63,8 +63,6 @@ set(SRCS windows/simulation/panel.cpp windows/simulation/run.h windows/simulation/run.cpp - windows/cleaner.h - windows/cleaner.cpp windows/analyzer/analyzer.cpp windows/analyzer/analyzer.h windows/constraints-builder/constraintsbuilder.cpp @@ -149,6 +147,9 @@ set(ANTARES_LIBS Antares::date Antares::study Antares::action + Antares::resources + Antares::locale + Antares::locator yuni-static-core yuni-static-uuid model_antares diff --git a/src/ui/simulator/application/application.cpp b/src/ui/simulator/application/application.cpp index 83d8012f54..e05505fc49 100644 --- a/src/ui/simulator/application/application.cpp +++ b/src/ui/simulator/application/application.cpp @@ -1,44 +1,39 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include #include #include +#include "study.h" #include "application.h" #include "main.h" -#include "../config.h" +#include "antares/config/config.h" #include #include #include #include "../toolbox/resources.h" #include #include -#include +#include #include #include #include @@ -47,8 +42,8 @@ #include #include "study.h" #include -#include -#include +#include "log_cleaner.h" +#include #ifndef YUNI_OS_WINDOWS #include #endif @@ -71,7 +66,7 @@ static void detectStudyToLoadAtStartup() if (name == "study.antares") { String t; - IO::ExtractFilePath(t, Forms::StudyToLoadAtStartup); + IO::parent_path(t, Forms::StudyToLoadAtStartup); Forms::StudyToLoadAtStartup = t; } else @@ -80,7 +75,7 @@ static void detectStudyToLoadAtStartup() if (name == "info.antares-output") { String t; - IO::ExtractFilePath(t, Forms::StudyToLoadAtStartup); + IO::parent_path(t, Forms::StudyToLoadAtStartup); if (System::windows) Forms::StudyToLoadAtStartup.clear() << t << "\\..\\.."; else @@ -157,7 +152,7 @@ static void AbortProgram(int code) } else { - Benchmarking::NullDurationCollector duration_collector; + Benchmarking::DurationCollector duration_collector; auto resultWriter = Antares::Solver::resultWriterFactory( currentStudy->parameters.resultFormat, currentStudy->folderOutput, @@ -341,7 +336,7 @@ bool Application::OnInit() if (now - lasttime > 3600 * 24 * 20) { String path; - IO::ExtractFilePath(path, logs.logfile()); + IO::parent_path(path, logs.logfile()); logs.info() << "deleting old log files in " << path << "..."; PurgeLogFiles(path); } diff --git a/src/ui/simulator/application/application.h b/src/ui/simulator/application/application.h index 3aad30642d..f2be28302f 100644 --- a/src/ui/simulator/application/application.h +++ b/src/ui/simulator/application/application.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_H__ #define __ANTARES_APPLICATION_H__ diff --git a/src/ui/simulator/application/log_cleaner.cpp b/src/ui/simulator/application/log_cleaner.cpp new file mode 100644 index 0000000000..6174487c78 --- /dev/null +++ b/src/ui/simulator/application/log_cleaner.cpp @@ -0,0 +1,140 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ + +#include "log_cleaner.h" +#include "antares/antares/constants.h" +#include +#include +#include + +using namespace Yuni; + +namespace Antares +{ +static inline bool IsLeapYear(uint year) +{ + if (0 == year % 4) + { + if (0 == year % 100) + return (0 == (year % 400)); + return true; + } + return false; +} + +static bool SuitableForDeletion(const AnyString& name, DateTime::Timestamp now) +{ + auto offset = name.find('-'); + if (offset < name.size()) + { + ++offset; + auto afterDate = name.find('-', offset); + if (afterDate < name.size()) + { + auto afterTime = name.find('.', afterDate); + if (afterTime < name.size()) + { + if (afterTime <= afterDate or afterDate <= offset) + return false; + + AnyString date(name.c_str() + offset, afterDate - offset); + AnyString time(name.c_str() + afterDate + 1, afterTime - afterDate - 1); + if (date.size() != 8 or time.size() != 6) + return false; + + AnyString year(date, 0, 4); + AnyString month(date, 4, 2); + AnyString day(date, 6, 2); + AnyString hours(time, 0, 2); + AnyString minutes(time, 2, 2); + AnyString seconds(time, 4, 2); + seconds.trimLeft("0"); + minutes.trimLeft("0"); + hours.trimLeft("0"); + day.trimLeft("0"); + month.trimLeft("0"); + + DateTime::Timestamp timestamp = seconds.to() + minutes.to() * 60 + + hours.to() * 3600 + + (day.to() - 1) * 24 * 3600; + + uint y = year.to(); + if (!(y < 9999)) // 4 digits + { + y = 1970; + } + else + { + if (y < 1970) + y = 1970; + } + + for (uint i = 1970; i < y; ++i) + { + if (not IsLeapYear(i)) + timestamp += 365 * 24 * 3600; + else + timestamp += 366 * 24 * 3600; + } + + uint m = month.to(); + if (m < 12 and m) + { + for (uint i = 0; i != m - 1; ++i) + { + if (i == 1 and IsLeapYear(y)) + timestamp += 24 * 3600 * (Constants::daysPerMonth[i] + 1); + else + timestamp += 24 * 3600 * Constants::daysPerMonth[i]; + } + } + + if (timestamp < now) + return true; + } + } + } + return false; +} + +void PurgeLogFiles(const AnyString& path, uint retention) +{ + if (path.empty()) + return; + + auto now = DateTime::Now(); + now -= retention; + + IO::Directory::Info info(path); + + auto end = info.file_end(); + for (auto i = info.file_begin(); i != end; ++i) + { + auto& name = *i; + if (not name.startsWith("uisimulator-") or not name.endsWith(".log")) + continue; + + if (SuitableForDeletion(name, now)) + IO::File::Delete(i.filename()); + } +} + +} // namespace Antares diff --git a/src/ui/simulator/application/log_cleaner.h b/src/ui/simulator/application/log_cleaner.h new file mode 100644 index 0000000000..cbb5195c4b --- /dev/null +++ b/src/ui/simulator/application/log_cleaner.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ +#ifndef __ANTARES_LOGS_CLEANER_H__ +#define __ANTARES_LOGS_CLEANER_H__ + +#include +#include + +namespace Antares +{ +enum +{ + defaultRetentionTime = (60 * 60 * 24) * 31, +}; + +/*! +** \brief Purge all log files +*/ +void PurgeLogFiles(const AnyString& path, uint retention = defaultRetentionTime); + +} // namespace Antares + +#endif // __ANTARES_LOGS_CLEANER_H__ diff --git a/src/ui/simulator/application/main.h b/src/ui/simulator/application/main.h index ad3754555b..9c9f940eb0 100644 --- a/src/ui/simulator/application/main.h +++ b/src/ui/simulator/application/main.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MAIN_H__ #define __ANTARES_APPLICATION_MAIN_H__ diff --git a/src/ui/simulator/application/main/analyzer.cpp b/src/ui/simulator/application/main/analyzer.cpp index 1fd2dc1cf9..64a781b75b 100644 --- a/src/ui/simulator/application/main/analyzer.cpp +++ b/src/ui/simulator/application/main/analyzer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" @@ -34,6 +28,7 @@ #include #include "internal-ids.h" #include "antares/study/ui-runtimeinfos.h" +#include "application/study.h" using namespace Yuni; diff --git a/src/ui/simulator/application/main/build/economic-optimization.cpp b/src/ui/simulator/application/main/build/economic-optimization.cpp index 4256efcdca..f11c7865e2 100644 --- a/src/ui/simulator/application/main/build/economic-optimization.cpp +++ b/src/ui/simulator/application/main/build/economic-optimization.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -40,7 +34,7 @@ namespace Forms { void ApplWnd::createNBNodalOptimization() { - assert(NULL != pNotebook); + assert(pNotebook); // Create a standard page with an input selector std::pair page diff --git a/src/ui/simulator/application/main/build/hydro.cpp b/src/ui/simulator/application/main/build/hydro.cpp index da0aabadab..4c19db0760 100644 --- a/src/ui/simulator/application/main/build/hydro.cpp +++ b/src/ui/simulator/application/main/build/hydro.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" diff --git a/src/ui/simulator/application/main/build/load.cpp b/src/ui/simulator/application/main/build/load.cpp index 45ff6153a4..917279955b 100644 --- a/src/ui/simulator/application/main/build/load.cpp +++ b/src/ui/simulator/application/main/build/load.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -41,7 +35,7 @@ namespace Forms { void ApplWnd::createNBLoad() { - assert(NULL != pNotebook); + assert(pNotebook); // Create a standard page with an input selector std::pair page diff --git a/src/ui/simulator/application/main/build/notes.cpp b/src/ui/simulator/application/main/build/notes.cpp index 07f2adba66..fcca4f545b 100644 --- a/src/ui/simulator/application/main/build/notes.cpp +++ b/src/ui/simulator/application/main/build/notes.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -36,7 +30,7 @@ namespace Forms { void ApplWnd::createNBNotes() { - assert(NULL != pNotebook); + assert(pNotebook); pUserNotes = new Window::Notes(pNotebook); pNotebook->add(pUserNotes, wxT("notes"), wxT("User's Notes")); diff --git a/src/ui/simulator/application/main/build/scenario-builder.cpp b/src/ui/simulator/application/main/build/scenario-builder.cpp index 645792f9ca..350c1633f7 100644 --- a/src/ui/simulator/application/main/build/scenario-builder.cpp +++ b/src/ui/simulator/application/main/build/scenario-builder.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -41,6 +35,7 @@ #include "toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.h" #include "toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.h" #include "toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.h" +#include "toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h" #include "toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.h" using namespace Yuni; @@ -205,8 +200,8 @@ class solarScBuilderPageMaker final : public simpleScBuilderPageMaker } }; -// Hydro levels ... -class hydroLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker +// Hydro Initial levels ... +class hydroInitialLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker { using simpleScBuilderPageMaker::simpleScBuilderPageMaker; @@ -216,7 +211,22 @@ class hydroLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker } Notebook::Page* addPageToNotebook() override { - return notebook()->add(grid(), wxT("hydro levels"), wxT("Hydro Levels")); + return notebook()->add(grid(), wxT("hydro initial levels"), wxT("Hydro Initial Levels")); + } +}; + +// Hydro Final levels ... +class hydroFinalLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker +{ + using simpleScBuilderPageMaker::simpleScBuilderPageMaker; + + Renderer::ScBuilderRendererBase* getRenderer() override + { + return new_check_allocation(); + } + Notebook::Page* addPageToNotebook() override + { + return notebook()->add(grid(), wxT("hydro final levels"), wxT("Hydro Final Levels")); } }; @@ -372,9 +382,13 @@ void ApplWnd::createNBScenarioBuilder() pScenarioBuilderNotebook->addSeparator(); - hydroLevelsScBuilderPageMaker hydroLevelsSBpageMaker(scenarioBuilderPanel, + hydroInitialLevelsScBuilderPageMaker hydroInitialLevelsSBpageMaker(scenarioBuilderPanel, + pScenarioBuilderNotebook); + pageScBuilderHydroInitialLevels = hydroInitialLevelsSBpageMaker.createPage(); + + hydroFinalLevelsScBuilderPageMaker hydroFinalLevelsSBpageMaker(scenarioBuilderPanel, pScenarioBuilderNotebook); - pageScBuilderHydroLevels = hydroLevelsSBpageMaker.createPage(); + pageScBuilderHydroFinalLevels = hydroFinalLevelsSBpageMaker.createPage(); } void ApplWnd::createNBOutputViewer() diff --git a/src/ui/simulator/application/main/build/sets.cpp b/src/ui/simulator/application/main/build/sets.cpp index 1a8edefaf4..c6119f3d93 100644 --- a/src/ui/simulator/application/main/build/sets.cpp +++ b/src/ui/simulator/application/main/build/sets.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -36,7 +30,7 @@ namespace Forms { void ApplWnd::createNBSets() { - assert(NULL != pNotebook); + assert(pNotebook); pSets = new Window::Sets(pNotebook); pNotebook->add(pSets, wxT("sets"), wxT("")); diff --git a/src/ui/simulator/application/main/build/solar.cpp b/src/ui/simulator/application/main/build/solar.cpp index d74a0f7503..6c9f29cea1 100644 --- a/src/ui/simulator/application/main/build/solar.cpp +++ b/src/ui/simulator/application/main/build/solar.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -41,7 +35,7 @@ namespace Forms { void ApplWnd::createNBSolar() { - assert(NULL != pNotebook); + assert(pNotebook); // Create a standard page with an input selector std::pair page diff --git a/src/ui/simulator/application/main/build/standard-page.hxx b/src/ui/simulator/application/main/build/standard-page.hxx index 4ad731c356..d14941f653 100644 --- a/src/ui/simulator/application/main/build/standard-page.hxx +++ b/src/ui/simulator/application/main/build/standard-page.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef ANTARES_APPLICATION_MAIN_BUILD_STANDARD_PAGE_HXX__ #define ANTARES_APPLICATION_MAIN_BUILD_STANDARD_PAGE_HXX__ diff --git a/src/ui/simulator/application/main/build/wind.cpp b/src/ui/simulator/application/main/build/wind.cpp index 60dc2fac68..73dce91d73 100644 --- a/src/ui/simulator/application/main/build/wind.cpp +++ b/src/ui/simulator/application/main/build/wind.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -41,7 +35,7 @@ namespace Forms { void ApplWnd::createNBWind() { - assert(NULL != pNotebook); + assert(pNotebook); // Create a standard page with an input selector std::pair page diff --git a/src/ui/simulator/application/main/cleaner.cpp b/src/ui/simulator/application/main/cleaner.cpp deleted file mode 100644 index 65bc8083ba..0000000000 --- a/src/ui/simulator/application/main/cleaner.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "main.h" -#include "../../windows/cleaner.h" -#include "../study.h" - -namespace Antares -{ -namespace Forms -{ -void ApplWnd::evtOnCleanCurrentStudyFolder(wxCommandEvent&) -{ - auto study = GetCurrentStudy(); - if (!(!study)) - { - if (study->parameters.readonly) - { - logs.error() << "Impossible to perform a cleanup. The study is readonly."; - return; - } - if ((int)study->header.version != (int)Data::versionLatest) - { - // Logs - logs.error() << "Impossible to perform a cleanup. You must save (as) the study before, " - "in order to upgrade the structure of folder"; - return; - } - if (StudyHasBeenModified()) - { - // Logs - logs.error() << "You must save the changes first before cleaning the study folder."; - return; - } - - Forms::Disabler disabler(*this); - auto* dialog = new Window::StudyCleaner(this); - dialog->studyFolder(wxStringFromUTF8(study->folder)); - dialog->ShowModal(); - dialog->Destroy(); - } -} - -void ApplWnd::evtOnCleanStudyFolder(wxCommandEvent&) -{ - Forms::Disabler disabler(*this); - auto* dialog = new Window::StudyCleaner(this); - dialog->ShowModal(); - dialog->Destroy(); -} - -} // namespace Forms -} // namespace Antares diff --git a/src/ui/simulator/application/main/constraintsbuilder.cpp b/src/ui/simulator/application/main/constraintsbuilder.cpp index 552689c375..d103d6e16c 100644 --- a/src/ui/simulator/application/main/constraintsbuilder.cpp +++ b/src/ui/simulator/application/main/constraintsbuilder.cpp @@ -1,41 +1,36 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" -#include "../study.h" +#include "antares/study/study.h" #include "../../toolbox/execute/execute.h" #include "../../windows/message.h" #include "../../toolbox/jobs.h" #include #include "internal-ids.h" -#include "../../../../solver/constraints-builder/cbuilder.h" +#include "antares/solver/constraints-builder/cbuilder.h" #include #include "../wait.h" #include "antares/study/ui-runtimeinfos.h" +#include "application/study.h" #define SEP IO::Separator @@ -92,7 +87,7 @@ class JobBuildConstraints final : public Toolbox::Jobs::Job MemoryFlushLocker memoryLocker; // Constraint Generator - CBuilder exec(study); + CBuilder exec(*study); // assert(exec.loadFromINIFile(pFilename)); exec.completeFromStudy(); diff --git a/src/ui/simulator/application/main/create.cpp b/src/ui/simulator/application/main/create.cpp index 8f23eae5dd..03d3f57a71 100644 --- a/src/ui/simulator/application/main/create.cpp +++ b/src/ui/simulator/application/main/create.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" diff --git a/src/ui/simulator/application/main/disabler.h b/src/ui/simulator/application/main/disabler.h index a022a0f3dd..1b969898db 100644 --- a/src/ui/simulator/application/main/disabler.h +++ b/src/ui/simulator/application/main/disabler.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MAIN_DISABLER_H__ #define __ANTARES_APPLICATION_MAIN_DISABLER_H__ diff --git a/src/ui/simulator/application/main/drag-drop.hxx b/src/ui/simulator/application/main/drag-drop.hxx index e3f544d082..82da254b88 100644 --- a/src/ui/simulator/application/main/drag-drop.hxx +++ b/src/ui/simulator/application/main/drag-drop.hxx @@ -1,33 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" #include -#include "../study.h" +#include "antares/study/study.h" #include "../../toolbox/dispatcher/study.h" #include diff --git a/src/ui/simulator/application/main/events.cpp b/src/ui/simulator/application/main/events.cpp index 658b2d15fb..81ede0e060 100644 --- a/src/ui/simulator/application/main/events.cpp +++ b/src/ui/simulator/application/main/events.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" @@ -36,7 +30,7 @@ #include "../../toolbox/dispatcher/study.h" #include "../menus.h" -#include "../study.h" +#include "antares/study/study.h" // Windows #include diff --git a/src/ui/simulator/application/main/events.edit.cpp b/src/ui/simulator/application/main/events.edit.cpp index af07f5d82b..72b941b96e 100644 --- a/src/ui/simulator/application/main/events.edit.cpp +++ b/src/ui/simulator/application/main/events.edit.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" diff --git a/src/ui/simulator/application/main/events.file.cpp b/src/ui/simulator/application/main/events.file.cpp index 588379514a..2a26af4d17 100644 --- a/src/ui/simulator/application/main/events.file.cpp +++ b/src/ui/simulator/application/main/events.file.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" -#include "../study.h" +#include "antares/study/study.h" #include "../recentfiles.h" #include "../menus.h" #include "../../windows/saveas.h" diff --git a/src/ui/simulator/application/main/events.simulation.cpp b/src/ui/simulator/application/main/events.simulation.cpp index 81d86e7601..2e24dce0a3 100644 --- a/src/ui/simulator/application/main/events.simulation.cpp +++ b/src/ui/simulator/application/main/events.simulation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -31,11 +25,11 @@ #include "../../windows/analyzer/analyzer.h" #include "../../windows/constraints-builder/constraintsbuilder.h" #include "internal-data.h" -#include "../../config.h" +#include "antares/config/config.h" #include #include "../../toolbox/dispatcher/study.h" #include - +#include "application/study.h" using namespace Yuni; namespace Antares @@ -129,10 +123,10 @@ void ApplWnd::evtOnRunTSAnalyzerDelayed() logs.error() << "The study must be saved before launching the analyzer"; return; } - if (study.header.version != Data::versionLatest) + if (study.header.version != Data::StudyVersion::latest()) { logs.error() << "The study must be upgraded to the v" - << Data::VersionToCStr((Data::Version)Data::versionLatest) + << Data::StudyVersion::latest().toString() << " format before launching the analyzer"; return; } @@ -169,10 +163,10 @@ void ApplWnd::evtOnRunConstraintsBuilderDelayed() logs.error() << "The study must be saved before launching the constraints builder"; return; } - if (study.header.version != Data::versionLatest) + if (study.header.version != Data::StudyVersion::latest()) { logs.error() << "The study must be upgraded to the v" - << Data::VersionToCStr((Data::Version)Data::versionLatest) + << Data::StudyVersion::latest().toString() << " format before launching the constraints builder"; return; } diff --git a/src/ui/simulator/application/main/fwd.h b/src/ui/simulator/application/main/fwd.h index 134fdcaba6..fad04cfd75 100644 --- a/src/ui/simulator/application/main/fwd.h +++ b/src/ui/simulator/application/main/fwd.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FWD_H__ #define __ANTARES_FWD_H__ diff --git a/src/ui/simulator/application/main/help.cpp b/src/ui/simulator/application/main/help.cpp index a23809cb8c..aff7035790 100644 --- a/src/ui/simulator/application/main/help.cpp +++ b/src/ui/simulator/application/main/help.cpp @@ -1,36 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include #include #include "../main.h" #include "../menus.h" -#include "../study.h" -#include "../../../config.h" +#include "antares/study/study.h" +#include #include "../../toolbox/resources.h" #include "../../windows/aboutbox.h" #include "../../toolbox/dispatcher/study.h" diff --git a/src/ui/simulator/application/main/internal-data.cpp b/src/ui/simulator/application/main/internal-data.cpp index 5d980fd218..07a9788001 100644 --- a/src/ui/simulator/application/main/internal-data.cpp +++ b/src/ui/simulator/application/main/internal-data.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "internal-data.h" -#include +#include namespace Antares { @@ -38,7 +32,7 @@ MainFormData::MainFormData(ApplWnd& form) : wipEnabled(false), wipPanel(nullptr) void MainFormData::editCurrentLocation(const wxString& string) { - assert(pEditCurrentLocation != NULL); + assert(pEditCurrentLocation); pEditCurrentLocation->SetItemLabel(wxString(wxT("Current tab : ")) << string); } diff --git a/src/ui/simulator/application/main/internal-data.h b/src/ui/simulator/application/main/internal-data.h index cd45fc626b..7b08dbdf08 100644 --- a/src/ui/simulator/application/main/internal-data.h +++ b/src/ui/simulator/application/main/internal-data.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MAIN_INTERNAL_DATA_H__ #define __ANTARES_APPLICATION_MAIN_INTERNAL_DATA_H__ diff --git a/src/ui/simulator/application/main/internal-ids.h b/src/ui/simulator/application/main/internal-ids.h index 3d457a2032..33d8f6f764 100644 --- a/src/ui/simulator/application/main/internal-ids.h +++ b/src/ui/simulator/application/main/internal-ids.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MAIN_INTERNAL_IDS_H__ #define __ANTARES_APPLICATION_MAIN_INTERNAL_IDS_H__ diff --git a/src/ui/simulator/application/main/logs.cpp b/src/ui/simulator/application/main/logs.cpp index 39a45ea726..c2e47bd0a4 100644 --- a/src/ui/simulator/application/main/logs.cpp +++ b/src/ui/simulator/application/main/logs.cpp @@ -1,39 +1,34 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include #include "../main.h" #include "../../windows/studylogs.h" -#include "../../../config.h" +#include #include #include #include #include "../../windows/message.h" #include "../../toolbox/components/htmllistbox/item/error.h" #include "internal-ids.h" +#include using namespace Yuni; @@ -53,9 +48,9 @@ class LogInfo final using WaitingLogEntries = std::vector; WaitingLogEntries waitingLogEntry; -Yuni::Mutex logMutex; +std::mutex logMutex; -Yuni::Atomic::Int<> logUpdateCount; +std::atomic logUpdateCount; class LogFlusherTimer final : public wxTimer { @@ -177,7 +172,7 @@ void ApplWnd::destroyLogs() if (pLogFlusherTimer) { wxTimer* timer = pLogFlusherTimer; - pLogFlusherTimer = NULL; + pLogFlusherTimer = nullptr; delete timer; } } @@ -201,7 +196,7 @@ void ApplWnd::destroyLogsViewer() if (pWndLogs) { pWndLogs->Destroy(); - pWndLogs = NULL; + pWndLogs = nullptr; } } @@ -211,9 +206,9 @@ void ApplWnd::connectLogCallback() logs.callback.connect(this, &ApplWnd::onLogMessageDeferred); } -void ApplWnd::onLogMessageDeferred(int level, const String& message) +void ApplWnd::onLogMessageDeferred(int level, const std::string& message) { - if (not message.empty() and message.first() != '[') + if (not message.empty() && message.front() != '[') { // wxLogError(), like wxLogWarning(), are routine with // variadic parameters, like the standard printf. diff --git a/src/ui/simulator/application/main/main.cpp b/src/ui/simulator/application/main/main.cpp index d4cca35472..3b321e6c12 100644 --- a/src/ui/simulator/application/main/main.cpp +++ b/src/ui/simulator/application/main/main.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" @@ -66,6 +60,7 @@ #include "../wait.h" #include "../../windows/options/advanced/advanced.h" +#include "application/study.h" using namespace Yuni; @@ -89,7 +84,6 @@ EVT_MENU(mnIDNew, ApplWnd::evtOnNewStudy) EVT_MENU(mnIDOpen, ApplWnd::evtOnOpenStudy) EVT_AUITOOLBAR_TOOL_DROPDOWN(mnIDOpen, ApplWnd::evtOnDropDownRecents) EVT_MENU(mnIDClose, ApplWnd::evtOnCloseStudy) -EVT_MENU(mnIDCleanOpenedStudyFolder, ApplWnd::evtOnCleanCurrentStudyFolder) EVT_MENU(mnIDOpenExplorer, ApplWnd::evtOnOpenStudyFolderInExplorer) EVT_MENU(mnUpdateInterfaceAfterLoadingAStudy, ApplWnd::evtOnUpdateInterfaceAfterLoadedStudy) @@ -146,8 +140,6 @@ EVT_MENU(mnIDRunTheSimulation, ApplWnd::evtOnRunSimulation) EVT_MENU(mnIDRunTheTSGenerators, ApplWnd::evtOnRunTSGenerators) EVT_MENU(mnIDRunTheTSAnalyzer, ApplWnd::evtOnRunTSAnalyzer) EVT_MENU(mnIDRunTheConstraintsBuilder, ApplWnd::evtOnRunConstraintsBuilder) -// Tools -EVT_MENU(mnIDCleanAStudyFolder, ApplWnd::evtOnCleanStudyFolder) // Options EVT_MENU(mnIDOptionTempFolder, ApplWnd::evtOnOptionsTempFolder) @@ -809,7 +801,7 @@ void ApplWnd::title(const wxString& s) wxString t; if (StudyHasBeenModified()) t << wxT("* "); - t << (s.IsEmpty() ? wxT("") : s) << wxT(" - Antares Simulator") + t << (s.IsEmpty() ? wxString(wxT("")) : s) << wxT(" - Antares Simulator") #ifndef NDEBUG << wxT(" - DEVELOPER PREVIEW") #endif diff --git a/src/ui/simulator/application/main/main.h b/src/ui/simulator/application/main/main.h index a870f91fb2..0b1f9dd8bb 100644 --- a/src/ui/simulator/application/main/main.h +++ b/src/ui/simulator/application/main/main.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MAIN_MAIN_H__ #define __ANTARES_APPLICATION_MAIN_MAIN_H__ @@ -35,7 +29,7 @@ #include "../../toolbox/components/map/settings.h" #include #include "fwd.h" -#include "config.h" +#include "antares/config/config.h" #include #include #include @@ -584,17 +578,13 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent void internalFrameClose(); - void evtOnCleanCurrentStudyFolder(wxCommandEvent& evt); - - void evtOnCleanStudyFolder(wxCommandEvent& evt); - void evtLaunchAnalyzer(wxCommandEvent& evt); void evtLaunchConstraintsBuilder(wxCommandEvent& evt); void onMouseMoved(wxMouseEvent& evt); - void onLogMessageDeferred(int level, const Yuni::String& message); + void onLogMessageDeferred(int level, const std::string& message); void onLogMessage(wxCommandEvent& evt); void onStudyLoaded(); @@ -703,7 +693,8 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent Component::Notebook::Page* pageScBuilderSolar; Component::Notebook::Page* pageScBuilderNTC; Component::Notebook::Page* pageScBuilderRenewable; - Component::Notebook::Page* pageScBuilderHydroLevels; + Component::Notebook::Page* pageScBuilderHydroInitialLevels; + Component::Notebook::Page* pageScBuilderHydroFinalLevels; //! A context menu for the map wxMenu* pMapContextMenu; diff --git a/src/ui/simulator/application/main/main.hxx b/src/ui/simulator/application/main/main.hxx index 50c09b051f..bcf6f14761 100644 --- a/src/ui/simulator/application/main/main.hxx +++ b/src/ui/simulator/application/main/main.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MAIN_MAIN_HXX__ #define __ANTARES_APPLICATION_MAIN_MAIN_HXX__ diff --git a/src/ui/simulator/application/main/menu.cpp b/src/ui/simulator/application/main/menu.cpp index 86b118f4f6..26dbbd1d56 100644 --- a/src/ui/simulator/application/main/menu.cpp +++ b/src/ui/simulator/application/main/menu.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -33,15 +27,15 @@ #include "../../toolbox/resources.h" #include "internal-data.h" #include "internal-ids.h" -#include "../../../../config.h" -#include +#include +#include "antares/antares/antares.h" #include +#include "application/study.h" using namespace Yuni; -namespace Antares -{ -namespace Forms + +namespace Antares::Forms { wxMenuBar* ApplWnd::createMenu() { @@ -763,5 +757,5 @@ void ApplWnd::evtOnViewNodalOptimization(wxCommandEvent&) pNotebook->select(wxT("nodal")); } -} // namespace Forms -} // namespace Antares +} // namespace Antares::Forms + diff --git a/src/ui/simulator/application/main/notes.cpp b/src/ui/simulator/application/main/notes.cpp index 389e6aa1de..60e2c17c08 100644 --- a/src/ui/simulator/application/main/notes.cpp +++ b/src/ui/simulator/application/main/notes.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" @@ -37,25 +31,25 @@ namespace Forms { void ApplWnd::loadUserNotes() { - assert(NULL != pUserNotes); + assert(pUserNotes); pUserNotes->loadFromStudy(); } void ApplWnd::saveUserNotes() { - assert(NULL != pUserNotes); + assert(pUserNotes); pUserNotes->saveToStudy(); } void ApplWnd::loadSets() { - assert(NULL != pSets); + assert(pSets); pSets->loadFromStudy(); } void ApplWnd::saveSets() { - assert(NULL != pSets); + assert(pSets); pSets->saveToStudy(); } diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index 32ee3dbcdc..3b8fc01098 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../main.h" -#include "../study.h" +#include "antares/study/study.h" #include "../../windows/options/temp-folder/temp-folder.h" #include "../../windows/options/geographic-trimming/geographic-trimming.h" #include "../../windows/options/select-output/select-output.h" @@ -79,7 +73,7 @@ void ApplWnd::evtOnOptionsDistricts(wxCommandEvent&) Forms::Disabler disabler(*this); if (CurrentStudyIsValid()) { - assert(NULL != pNotebook); + assert(pNotebook); pNotebook->select("sets"); } } diff --git a/src/ui/simulator/application/main/paste-from-clipboard.cpp b/src/ui/simulator/application/main/paste-from-clipboard.cpp index a8fce58ee5..c48e2f816d 100644 --- a/src/ui/simulator/application/main/paste-from-clipboard.cpp +++ b/src/ui/simulator/application/main/paste-from-clipboard.cpp @@ -1,36 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" // Map #include "../../toolbox/clipboard/clipboard.h" -#include "../study.h" +#include "antares/study/study.h" #include "../../toolbox/ext-source/handler.h" +#include "application/study.h" using namespace Yuni; diff --git a/src/ui/simulator/application/main/refresh.cpp b/src/ui/simulator/application/main/refresh.cpp index fd07e11408..88c36a57cb 100644 --- a/src/ui/simulator/application/main/refresh.cpp +++ b/src/ui/simulator/application/main/refresh.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" -#include "../study.h" +#include "antares/study/study.h" #include "../menus.h" #include #include @@ -34,6 +28,7 @@ #include "../../../common/lock.h" #include #include "internal-ids.h" +#include "application/study.h" using namespace Yuni; @@ -41,9 +36,9 @@ namespace Antares { namespace Forms { -struct CompareByStudyMode final +struct CompareBySimulationMode final { - bool operator()(const Data::StudyMode a, const Data::StudyMode b) const + bool operator()(const Data::SimulationMode a, const Data::SimulationMode b) const { return b < a; } @@ -117,14 +112,14 @@ void ApplWnd::refreshMenuOutput() // NOTE : in some rare cases, it may happen that two simulations have the // same timestamp - using StudyModeT = Data::StudyMode; + using SimulationModeT = Data::SimulationMode; using TemporalMap = std::map; - using Map = std::map; + using Map = std::map; // Getting the list of all available outputs const Data::Output::List& list = ListOfOutputsForTheCurrentStudy; - // The last study mode - Data::StudyMode lastMode = Data::stdmUnknown; + // The last simulation mode + Data::SimulationMode lastMode = Data::SimulationMode::Unknown; // Informations about the outputs Map map; @@ -219,7 +214,7 @@ void ApplWnd::refreshMenuOutput() #ifndef YUNI_OS_WINDOWS (!more ? "images/16x16/minibullet_sel.png" : "images/16x16/minibullet.png"), #else - (((*i)->mode == Data::stdmEconomy) ? "images/misc/economy.png" + (((*i)->mode == Data::SimulationMode::Economy) ? "images/misc/economy.png" : "images/misc/adequacy.png"), #endif s, @@ -273,14 +268,14 @@ void ApplWnd::refreshMenuOutput() // AppendTooManyItems(menu, more); more = 0; } - // if (lastMode != Data::stdmUnknown) + // if (lastMode != Data::SimulationMode::Unknown) // Menu::CreateEmptyItem(menu); lastMode = (*i)->mode; - if (lastMode == Data::stdmUnknown) - lastMode = Data::stdmEconomy; + if (lastMode == Data::SimulationMode::Unknown) + lastMode = Data::SimulationMode::Economy; Menu::CreateGroupItem(menu, - wxStringFromUTF8(StudyModeToCString(lastMode)), + wxStringFromUTF8(SimulationModeToCString(lastMode)), "images/16x16/empty.png"); total = 0; } @@ -308,7 +303,7 @@ void ApplWnd::refreshMenuOutput() #ifndef YUNI_OS_WINDOWS "images/16x16/minibullet.png", #else - (((*i)->mode == Data::stdmEconomy) + (((*i)->mode == Data::SimulationMode::Economy) ? "images/misc/economy.png" : "images/misc/adequacy.png"), #endif @@ -320,7 +315,7 @@ void ApplWnd::refreshMenuOutput() it->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(Forms::ApplWnd::evtOnOpenOutputInExplorer), - NULL, + nullptr, parentForm); } } diff --git a/src/ui/simulator/application/main/statusbar.cpp b/src/ui/simulator/application/main/statusbar.cpp index 3b6bb02e09..a12dd4a290 100644 --- a/src/ui/simulator/application/main/statusbar.cpp +++ b/src/ui/simulator/application/main/statusbar.cpp @@ -1,34 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include #include "main.h" #include "../../windows/version.h" -#include "../study.h" +#include "antares/study/study.h" // Datagrid #include "../../toolbox/components/datagrid/component.h" #include "../../toolbox/components/datagrid/gridhelper.h" diff --git a/src/ui/simulator/application/main/wip.cpp b/src/ui/simulator/application/main/wip.cpp index bcd6f0efab..b40ddb7ea5 100644 --- a/src/ui/simulator/application/main/wip.cpp +++ b/src/ui/simulator/application/main/wip.cpp @@ -1,36 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "main.h" #include -#include "../study.h" +#include "antares/study/study.h" #include #include #include "internal-data.h" +#include "application/study.h" using namespace Yuni; diff --git a/src/ui/simulator/application/menus.cpp b/src/ui/simulator/application/menus.cpp index 5d21e029a2..417f8e35a2 100644 --- a/src/ui/simulator/application/menus.cpp +++ b/src/ui/simulator/application/menus.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/application/menus.h b/src/ui/simulator/application/menus.h index 7f639b9b05..df709b51b2 100644 --- a/src/ui/simulator/application/menus.h +++ b/src/ui/simulator/application/menus.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_FORMS_MENU_H__ #define __ANTARES_FORMS_MENU_H__ diff --git a/src/ui/simulator/application/recentfiles.cpp b/src/ui/simulator/application/recentfiles.cpp index 37bae37dfb..2e58450fc4 100644 --- a/src/ui/simulator/application/recentfiles.cpp +++ b/src/ui/simulator/application/recentfiles.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/application/recentfiles.h b/src/ui/simulator/application/recentfiles.h index e2808e9f5d..b0e4fbe718 100644 --- a/src/ui/simulator/application/recentfiles.h +++ b/src/ui/simulator/application/recentfiles.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_RECENT_FILES_H__ #define __ANTARES_APPLICATION_RECENT_FILES_H__ diff --git a/src/ui/simulator/application/study.cpp b/src/ui/simulator/application/study.cpp index bb51370a2b..c71e4de6ca 100644 --- a/src/ui/simulator/application/study.cpp +++ b/src/ui/simulator/application/study.cpp @@ -1,30 +1,24 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "study.h" +#include "antares/study/study.h" #include #include #include @@ -35,7 +29,7 @@ #include "../toolbox/components/map/component.h" #include "../toolbox/components/mainpanel.h" #include "../toolbox/jobs.h" -#include + #include "../toolbox/execute/execute.h" #include "../windows/message.h" #include @@ -55,6 +49,9 @@ #include "main/internal-data.h" #include "antares/study/ui-runtimeinfos.h" +#include "antares/utils/utils.h" + +#include using namespace Yuni; @@ -67,7 +64,7 @@ String LastPathForOpeningAFile; wxString gLastOpenedStudyFolder; //! Ref counter to allow memory flush -Atomic::Int<32> gMemoryFlushRefCount = 0; +std::atomic gMemoryFlushRefCount = 0; Event OnStudyClosed; Event OnStudyLoaded; @@ -570,13 +567,17 @@ void MarkTheStudyAsModified(const Data::Study::Ptr& study) if (!(!study) and study == GetCurrentStudy()) MarkTheStudyAsModified(); } - void MarkTheStudyAsModified() { auto study = GetCurrentStudy(); if (!(!study)) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" +#pragma GCC diagnostic ignored "-Wvolatile" ++gInMemoryRevisionIncrement; +#pragma GCC diagnostic pop +#pragma GCC diagnostic pop if (!gStudyHasBeenModified) { gStudyHasBeenModified = true; @@ -776,7 +777,7 @@ SaveResult SaveStudy() bool shouldInvalidateStudy = false; // Detection for old format - if (study.header.version != Data::versionLatest) + if (study.header.version != Data::StudyVersion::latest()) { Window::Message message( &mainFrm, @@ -784,9 +785,9 @@ SaveResult SaveStudy() wxT("The study was saved with a previous version of Antares"), wxString() << wxT("You can choose either to upgrade the study folder or to save it\n") << wxT("into a new folder.\n\nCurrent version of Antares : ") - << wxStringFromUTF8(Data::VersionToCStr((Data::Version)Data::versionLatest)) + << Data::StudyVersion::latest().toString() << wxT("\nFormat version of the study : ") - << wxStringFromUTF8(Data::VersionToCStr((Data::Version)study.header.version)), + << study.header.version.toString(), "images/misc/save.png"); message.add(Window::Message::btnUpgrade); message.add(Window::Message::btnSaveAs, false, 15); @@ -997,18 +998,18 @@ void OpenStudyFromFolder(wxString folder) // Getting the version of the study String studyfolder; wxStringToString(folder, studyfolder); - auto version = Data::StudyTryToFindTheVersion(studyfolder); + auto version = Data::StudyHeader::tryToFindTheVersion(studyfolder); - if (version == Data::versionUnknown) + if (version == Data::StudyVersion::unknown()) { logs.error() << studyfolder << ": it does not seem a valid study"; return; } - if ((uint)version > (uint)Data::versionLatest) + if (version > Data::StudyVersion::latest()) { logs.error() << "A more recent version of Antares is required to open `" << studyfolder - << "` (" << Data::VersionToCStr(version) << ')'; + << "` (" << version.toString() << ')'; return; } @@ -1278,8 +1279,14 @@ void RefreshListOfOutputsForTheCurrentStudy() if (IsGUIAboutToQuit()) return; - auto study = GetCurrentStudy(); - Data::Output::RetrieveListFromStudy(ListOfOutputsForTheCurrentStudy, study); + if (auto study = GetCurrentStudy(); CurrentStudyIsValid()) + { + Data::Output::RetrieveListFromStudy(ListOfOutputsForTheCurrentStudy, *study); + } + else + { + ListOfOutputsForTheCurrentStudy.clear(); + } auto* mainfrm = Forms::ApplWnd::Instance(); if (mainfrm) diff --git a/src/ui/simulator/application/study.h b/src/ui/simulator/application/study.h index a6d408d638..569de2e9e4 100644 --- a/src/ui/simulator/application/study.h +++ b/src/ui/simulator/application/study.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_STUDY_H__ #define __ANTARES_APPLICATION_STUDY_H__ @@ -33,7 +27,7 @@ #include #include #include -#include +#include #include "ui/simulator/toolbox/components/map/settings.h" diff --git a/src/ui/simulator/application/wait.cpp b/src/ui/simulator/application/wait.cpp index 6a83db16a2..70a6498079 100644 --- a/src/ui/simulator/application/wait.cpp +++ b/src/ui/simulator/application/wait.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/application/wait.h b/src/ui/simulator/application/wait.h index 0223c670bc..014b433a95 100644 --- a/src/ui/simulator/application/wait.h +++ b/src/ui/simulator/application/wait.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_PLEASE_WAIT_H__ #define __ANTARES_APPLICATION_PLEASE_WAIT_H__ diff --git a/src/ui/simulator/cmake/application.cmake b/src/ui/simulator/cmake/application.cmake index 012acba2fb..685cd0d9b3 100644 --- a/src/ui/simulator/cmake/application.cmake +++ b/src/ui/simulator/cmake/application.cmake @@ -8,7 +8,6 @@ SET(SRC_APPLICATION application/menus.h application/menus.cpp application/main/fwd.h - application/main/cleaner.cpp application/main/events.cpp application/main/events.file.cpp application/main/events.edit.cpp @@ -51,6 +50,8 @@ SET(SRC_APPLICATION # Application application/application.h application/application.cpp + application/log_cleaner.h + application/log_cleaner.cpp application/study.h application/study.cpp @@ -74,5 +75,10 @@ target_link_libraries(antares-ui-application Antares::args_helper Antares::sys Antares::study + Antares::resources + Antares::locator + Antares::locale + Antares::application + antares-solver-constraints-builder ) diff --git a/src/ui/simulator/cmake/components-button.cmake b/src/ui/simulator/cmake/components-button.cmake index 635ec89f94..5d3a8499fc 100644 --- a/src/ui/simulator/cmake/components-button.cmake +++ b/src/ui/simulator/cmake/components-button.cmake @@ -16,4 +16,4 @@ add_library(antares-ui-component-button target_link_libraries(antares-ui-component-button PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-component-button PRIVATE antares-core antares-ui-common) +target_link_libraries(antares-ui-component-button PRIVATE antares-core antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/components-htmllistbox.cmake b/src/ui/simulator/cmake/components-htmllistbox.cmake index bf49adf620..1bf7ad87f4 100644 --- a/src/ui/simulator/cmake/components-htmllistbox.cmake +++ b/src/ui/simulator/cmake/components-htmllistbox.cmake @@ -6,9 +6,10 @@ add_library(antares-ui-component-htmllistbox toolbox/components/htmllistbox/item/item.h toolbox/components/htmllistbox/item/item.hxx toolbox/components/htmllistbox/item/item.cpp - toolbox/components/htmllistbox/sort.h - toolbox/components/htmllistbox/item/info.h toolbox/components/htmllistbox/item/info.cpp - toolbox/components/htmllistbox/item/group.h toolbox/components/htmllistbox/item/group.cpp + toolbox/components/htmllistbox/item/info.h + toolbox/components/htmllistbox/item/info.cpp + toolbox/components/htmllistbox/item/group.h + toolbox/components/htmllistbox/item/group.cpp toolbox/components/htmllistbox/item/area.h toolbox/components/htmllistbox/item/area.cpp toolbox/components/htmllistbox/item/area.hxx @@ -26,21 +27,21 @@ add_library(antares-ui-component-htmllistbox toolbox/components/htmllistbox/datasource/datasource.h toolbox/components/htmllistbox/datasource/datasource.hxx - toolbox/components/htmllistbox/datasource/cluster-order.h - toolbox/components/htmllistbox/datasource/cluster-order.cpp + toolbox/components/htmllistbox/datasource/cluster-order.h + toolbox/components/htmllistbox/datasource/cluster-order.cpp toolbox/components/htmllistbox/datasource/thermal-cluster-order.h toolbox/components/htmllistbox/datasource/thermal-cluster-order.cpp toolbox/components/htmllistbox/datasource/renewable-cluster-order.h toolbox/components/htmllistbox/datasource/renewable-cluster-order.cpp - toolbox/components/htmllistbox/item/cluster-item.h - toolbox/components/htmllistbox/item/cluster-item.cpp - toolbox/components/htmllistbox/item/renewable-cluster-item.h - toolbox/components/htmllistbox/item/renewable-cluster-item.cpp - toolbox/components/htmllistbox/item/thermal-cluster-item.h - toolbox/components/htmllistbox/item/thermal-cluster-item.cpp + toolbox/components/htmllistbox/item/cluster-item.h + toolbox/components/htmllistbox/item/cluster-item.cpp + toolbox/components/htmllistbox/item/renewable-cluster-item.h + toolbox/components/htmllistbox/item/renewable-cluster-item.cpp + toolbox/components/htmllistbox/item/thermal-cluster-item.h + toolbox/components/htmllistbox/item/thermal-cluster-item.cpp ) target_link_libraries(antares-ui-component-htmllistbox PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-component-htmllistbox PRIVATE antares-core antares-ui-common) +target_link_libraries(antares-ui-component-htmllistbox PRIVATE antares-core antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/components-map.cmake b/src/ui/simulator/cmake/components-map.cmake index a9fd59e6c3..8a8f0616b9 100644 --- a/src/ui/simulator/cmake/components-map.cmake +++ b/src/ui/simulator/cmake/components-map.cmake @@ -54,4 +54,9 @@ add_library(antares-ui-component-map target_link_libraries(antares-ui-component-map PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-component-map PRIVATE antares-core antares-ui-common antares-ui-components) +target_link_libraries(antares-ui-component-map PRIVATE + antares-core antares-ui-common + antares-ui-components + Antares::resources + Antares::locator +) diff --git a/src/ui/simulator/cmake/components.cmake b/src/ui/simulator/cmake/components.cmake index 32a491b37e..0586928a48 100644 --- a/src/ui/simulator/cmake/components.cmake +++ b/src/ui/simulator/cmake/components.cmake @@ -92,6 +92,8 @@ SET(SRC_TOOLBOX_COM_DBGRID_RENDERERS toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.h toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.h toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.cpp + toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h + toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.cpp toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.h toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.cpp toolbox/components/datagrid/renderer/layers.cpp @@ -236,5 +238,8 @@ target_link_libraries(antares-ui-components PRIVATE antares-core antares-ui-common + Antares::resources + Antares::locator + antares-solver-constraints-builder ) diff --git a/src/ui/simulator/cmake/copy-paste.cmake b/src/ui/simulator/cmake/copy-paste.cmake index 6cdc66e179..c89f1cc5cd 100644 --- a/src/ui/simulator/cmake/copy-paste.cmake +++ b/src/ui/simulator/cmake/copy-paste.cmake @@ -23,4 +23,7 @@ add_Library(antares-ui-copy-paste ${SRC_UI_COPYPASTE}) target_link_libraries(antares-ui-copy-paste PRIVATE ${wxWidgets_LIBRARIES} antares-ui-common - Antares::action) + Antares::action + Antares::resources + Antares::locator +) diff --git a/src/ui/simulator/cmake/inputs.cmake b/src/ui/simulator/cmake/inputs.cmake index 79fc1ec8ab..f60f3923fb 100644 --- a/src/ui/simulator/cmake/inputs.cmake +++ b/src/ui/simulator/cmake/inputs.cmake @@ -19,4 +19,4 @@ add_Library(antares-ui-inputs ${SRC_UI_INPUTS}) target_link_libraries(antares-ui-inputs PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-inputs PRIVATE antares-core antares-ui-common) +target_link_libraries(antares-ui-inputs PRIVATE antares-core antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/jobs.cmake b/src/ui/simulator/cmake/jobs.cmake index e064a32c58..0fedaebf15 100644 --- a/src/ui/simulator/cmake/jobs.cmake +++ b/src/ui/simulator/cmake/jobs.cmake @@ -18,5 +18,5 @@ add_Library(antares-ui-jobs ${SRC_UI_JOBS}) target_link_libraries(antares-ui-jobs PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-jobs PRIVATE antares-ui-common) +target_link_libraries(antares-ui-jobs PRIVATE antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/messages.cmake b/src/ui/simulator/cmake/messages.cmake index c46617560a..89cdbef85a 100644 --- a/src/ui/simulator/cmake/messages.cmake +++ b/src/ui/simulator/cmake/messages.cmake @@ -19,5 +19,5 @@ add_Library(antares-ui-messages ${SRC_UI_MESSAGES}) target_link_libraries(antares-ui-messages PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-messages PRIVATE antares-core antares-ui-common) +target_link_libraries(antares-ui-messages PRIVATE antares-core antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/resources.cmake b/src/ui/simulator/cmake/resources.cmake index 7ade7e1a58..28a8889ee5 100644 --- a/src/ui/simulator/cmake/resources.cmake +++ b/src/ui/simulator/cmake/resources.cmake @@ -12,5 +12,5 @@ add_Library(antares-ui-resources ${SRC_UI_RESOURCES}) target_link_libraries(antares-ui-resources PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-resources PRIVATE antares-core antares-ui-common) +target_link_libraries(antares-ui-resources PRIVATE antares-core antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/toolbox-spotlight.cmake b/src/ui/simulator/cmake/toolbox-spotlight.cmake index b808f35bca..fca159a1e2 100644 --- a/src/ui/simulator/cmake/toolbox-spotlight.cmake +++ b/src/ui/simulator/cmake/toolbox-spotlight.cmake @@ -10,5 +10,5 @@ add_library(antares-ui-toolbox-spotlight target_link_libraries(antares-ui-toolbox-spotlight PRIVATE ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-toolbox-spotlight PRIVATE antares-ui-common) +target_link_libraries(antares-ui-toolbox-spotlight PRIVATE antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/windows-calendar.cmake b/src/ui/simulator/cmake/windows-calendar.cmake index de7b798187..b08cfd9e92 100644 --- a/src/ui/simulator/cmake/windows-calendar.cmake +++ b/src/ui/simulator/cmake/windows-calendar.cmake @@ -8,4 +8,4 @@ set(SRC_UI_WINDOWS_CALENDAR add_Library(antares-ui-windows-calendar ${SRC_UI_WINDOWS_CALENDAR}) target_link_libraries(antares-ui-windows-calendar PRIVATE ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-windows-calendar PRIVATE antares-ui-common) +target_link_libraries(antares-ui-windows-calendar PRIVATE antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/windows-inspector.cmake b/src/ui/simulator/cmake/windows-inspector.cmake index 59461eb7e2..d0e6d2f50b 100644 --- a/src/ui/simulator/cmake/windows-inspector.cmake +++ b/src/ui/simulator/cmake/windows-inspector.cmake @@ -25,6 +25,14 @@ SET(SRC_WINDOW_INSPECTOR add_library(antares-ui-windows-inspector ${SRC_WINDOW_INSPECTOR}) -target_link_libraries(antares-ui-windows-inspector PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-windows-inspector PRIVATE antares-ui-common) +target_link_libraries(antares-ui-windows-inspector + PUBLIC + ${wxWidgets_LIBRARIES}) +target_link_libraries(antares-ui-windows-inspector + PRIVATE + antares-ui-common + Antares::resources + Antares::locator + Antares::study +) diff --git a/src/ui/simulator/cmake/windows-options.cmake b/src/ui/simulator/cmake/windows-options.cmake index 3888a1e085..ab3a3a85d2 100644 --- a/src/ui/simulator/cmake/windows-options.cmake +++ b/src/ui/simulator/cmake/windows-options.cmake @@ -32,4 +32,6 @@ target_link_libraries(antares-ui-windows-options PRIVATE antares-ui-common Antares::sys + Antares::resources + Antares::locator ) \ No newline at end of file diff --git a/src/ui/simulator/cmake/windows-output.cmake b/src/ui/simulator/cmake/windows-output.cmake index d8171bd682..7495d2e8e9 100644 --- a/src/ui/simulator/cmake/windows-output.cmake +++ b/src/ui/simulator/cmake/windows-output.cmake @@ -43,6 +43,6 @@ add_Library(antares-ui-windows-output ${SRC_UI_OUTPUT_PROVIDERS}) target_link_libraries(antares-ui-windows-output PRIVATE ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-windows-output PRIVATE antares-ui-common) +target_link_libraries(antares-ui-windows-output PRIVATE antares-ui-common Antares::resources antares-solver-variable Antares::locator) diff --git a/src/ui/simulator/cmake/windows-startupwizard.cmake b/src/ui/simulator/cmake/windows-startupwizard.cmake index 94898ad1ec..680b5ce493 100644 --- a/src/ui/simulator/cmake/windows-startupwizard.cmake +++ b/src/ui/simulator/cmake/windows-startupwizard.cmake @@ -7,4 +7,4 @@ set(SRC_UI_WINDOWS_STARTUP_WIZARD add_Library(antares-ui-windows-startupwizard ${SRC_UI_WINDOWS_STARTUP_WIZARD}) target_link_libraries(antares-ui-windows-startupwizard PRIVATE ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-windows-startupwizard PRIVATE antares-ui-common) +target_link_libraries(antares-ui-windows-startupwizard PRIVATE antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/windows-studyparts.cmake b/src/ui/simulator/cmake/windows-studyparts.cmake index 5c41f039a4..e9a1ba823d 100644 --- a/src/ui/simulator/cmake/windows-studyparts.cmake +++ b/src/ui/simulator/cmake/windows-studyparts.cmake @@ -47,5 +47,5 @@ target_link_libraries(antares-ui-windows-studyparts ${wxWidgets_LIBRARIES} Antares::study ) -target_link_libraries(antares-ui-windows-studyparts PRIVATE antares-ui-common) +target_link_libraries(antares-ui-windows-studyparts PRIVATE antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/cmake/wxcore.cmake b/src/ui/simulator/cmake/wxcore.cmake index dcb9546cdb..4fbe420728 100644 --- a/src/ui/simulator/cmake/wxcore.cmake +++ b/src/ui/simulator/cmake/wxcore.cmake @@ -8,6 +8,6 @@ set(SRCTOOLBOX_CORE_WX ) add_Library(antares-ui-wxcore ${SRCTOOLBOX_CORE_WX}) target_link_libraries(antares-ui-wxcore PUBLIC ${wxWidgets_LIBRARIES}) -target_link_libraries(antares-ui-wxcore PRIVATE antares-ui-common) +target_link_libraries(antares-ui-wxcore PRIVATE antares-ui-common Antares::resources Antares::locator) diff --git a/src/ui/simulator/config.h b/src/ui/simulator/config.h index c96eae892d..01da6e8a66 100644 --- a/src/ui/simulator/config.h +++ b/src/ui/simulator/config.h @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_INTERFACE_CONFIG_H__ #define __ANTARES_INTERFACE_CONFIG_H__ -#include "../../config.h" +#include "antares/config/config.h" #endif // __ANTARES_INTERFACE_CONFIG_H__ diff --git a/src/ui/simulator/main.cpp b/src/ui/simulator/main.cpp index bf36e9564a..7fc62536dc 100644 --- a/src/ui/simulator/main.cpp +++ b/src/ui/simulator/main.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -33,7 +27,7 @@ #include #include #include -#include +#include #ifdef YUNI_OS_MSVC // WxWidgets Stuff diff --git a/src/ui/simulator/toolbox/clipboard/clipboard.cpp b/src/ui/simulator/toolbox/clipboard/clipboard.cpp index 8be58abed2..afd7c7f5dc 100644 --- a/src/ui/simulator/toolbox/clipboard/clipboard.cpp +++ b/src/ui/simulator/toolbox/clipboard/clipboard.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "clipboard.h" diff --git a/src/ui/simulator/toolbox/clipboard/clipboard.h b/src/ui/simulator/toolbox/clipboard/clipboard.h index 78397b6a19..8a49d42e31 100644 --- a/src/ui/simulator/toolbox/clipboard/clipboard.h +++ b/src/ui/simulator/toolbox/clipboard/clipboard.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_CLIPBOARD_CLIPBOARD_H__ #define __ANTARES_TOOLBOX_CLIPBOARD_CLIPBOARD_H__ diff --git a/src/ui/simulator/toolbox/components/button.h b/src/ui/simulator/toolbox/components/button.h index d6c416a468..ac74c318c0 100644 --- a/src/ui/simulator/toolbox/components/button.h +++ b/src/ui/simulator/toolbox/components/button.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_BUTTON_H__ #define __ANTARES_TOOLBOX_COMPONENTS_BUTTON_H__ diff --git a/src/ui/simulator/toolbox/components/button/button.cpp b/src/ui/simulator/toolbox/components/button/button.cpp index 968701b03f..9fbb2b9118 100644 --- a/src/ui/simulator/toolbox/components/button/button.cpp +++ b/src/ui/simulator/toolbox/components/button/button.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "button.h" @@ -164,7 +158,7 @@ void Button::loadIconFromResource(const char* filename) void Button::precalculateCoordinates() { // Assert - assert(this != NULL && "Button: this must not be null"); + assert(this != nullptr && "Button: this must not be null"); assert(iconMargin <= 128 && "Button: The margin seems suspicious"); if (pCaption.empty()) diff --git a/src/ui/simulator/toolbox/components/button/button.h b/src/ui/simulator/toolbox/components/button/button.h index a3b65a7176..047c8c2453 100644 --- a/src/ui/simulator/toolbox/components/button/button.h +++ b/src/ui/simulator/toolbox/components/button/button.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_BUTTON_BUTTON_H__ #define __ANTARES_TOOLBOX_COMPONENTS_BUTTON_BUTTON_H__ @@ -191,7 +185,7 @@ class Button final : public Panel virtual void onMouseLeave() override; //! Click up - virtual void onMouseUp(wxMouseEvent& evt); + virtual void onMouseUp(wxMouseEvent& evt) override; protected: //! Preload the Icon diff --git a/src/ui/simulator/toolbox/components/button/button.hxx b/src/ui/simulator/toolbox/components/button/button.hxx index 652681a3bc..ee18b04966 100644 --- a/src/ui/simulator/toolbox/components/button/button.hxx +++ b/src/ui/simulator/toolbox/components/button/button.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_BUTTON_BUTTON_HXX__ #define __ANTARES_TOOLBOX_COMPONENTS_BUTTON_BUTTON_HXX__ diff --git a/src/ui/simulator/toolbox/components/captionpanel.cpp b/src/ui/simulator/toolbox/components/captionpanel.cpp index 62ebb6843e..d45c023302 100644 --- a/src/ui/simulator/toolbox/components/captionpanel.cpp +++ b/src/ui/simulator/toolbox/components/captionpanel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "captionpanel.h" diff --git a/src/ui/simulator/toolbox/components/captionpanel.h b/src/ui/simulator/toolbox/components/captionpanel.h index 27a023987c..41e6c31aba 100644 --- a/src/ui/simulator/toolbox/components/captionpanel.h +++ b/src/ui/simulator/toolbox/components/captionpanel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_CAPTIONPANEL_H__ #define __ANTARES_TOOLBOX_COMPONENTS_CAPTIONPANEL_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/component.cpp b/src/ui/simulator/toolbox/components/datagrid/component.cpp index 7a2b6df99f..75f3196901 100644 --- a/src/ui/simulator/toolbox/components/datagrid/component.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/component.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -523,7 +517,7 @@ void InternalState::createAllInternalControls(const CreateOptions& flags) wxDefaultPosition, wxSize(-1, 22), 0, - NULL, + nullptr, wxCB_READONLY); pLayerFilter->SetFont(wxFont(wxFontInfo().Bold())); pLayerFilter->AppendString("All"); @@ -1017,7 +1011,7 @@ void Component::onLoadMatrix(void*) // Force a refresh forceRefresh(); // Last opened file - IO::ExtractFilePath(LastPathForOpeningAFile, stdFilename); + IO::parent_path(LastPathForOpeningAFile, stdFilename); if (pInternal->shouldMarkStudyModifiedWhenModifyingCell) MarkTheStudyAsModified(); @@ -1073,7 +1067,7 @@ void Component::onSaveMatrix(void*) // Exporting the matrix m.saveToCSVFile(stdFilename); // Last opened file - IO::ExtractFilePath(LastPathForOpeningAFile, stdFilename); + IO::parent_path(LastPathForOpeningAFile, stdFilename); } else dialog->Destroy(); diff --git a/src/ui/simulator/toolbox/components/datagrid/component.h b/src/ui/simulator/toolbox/components/datagrid/component.h index facd6a83e9..16ff0448aa 100644 --- a/src/ui/simulator/toolbox/components/datagrid/component.h +++ b/src/ui/simulator/toolbox/components/datagrid/component.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_COMPONENT_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_COMPONENT_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/dbgrid.cpp b/src/ui/simulator/toolbox/components/datagrid/dbgrid.cpp index dd10ccf3cc..dc8624172e 100644 --- a/src/ui/simulator/toolbox/components/datagrid/dbgrid.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/dbgrid.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "dbgrid.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/dbgrid.h b/src/ui/simulator/toolbox/components/datagrid/dbgrid.h index a7f32b98b8..e06cd2cf93 100644 --- a/src/ui/simulator/toolbox/components/datagrid/dbgrid.h +++ b/src/ui/simulator/toolbox/components/datagrid/dbgrid.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_DBGRID_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_DBGRID_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/default.h b/src/ui/simulator/toolbox/components/datagrid/default.h index f56a42676e..3b340add18 100644 --- a/src/ui/simulator/toolbox/components/datagrid/default.h +++ b/src/ui/simulator/toolbox/components/datagrid/default.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_DEFAULT_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_DEFAULT_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/any.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/any.h index 7510a44f45..eb641f8491 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/any.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/any.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_ALL_ANY_H__ #define __ANTARES_TOOLBOX_FILTER_ALL_ANY_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/columnindex.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/columnindex.h index 1a333aba0a..a907e38ed8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/columnindex.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/columnindex.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_COLUMN_INDEX_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_COLUMN_INDEX_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/day.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/day.h index 0014cca8f5..d03a30a8e1 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/day.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/day.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_DAY_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_DAY_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/dayyear.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/dayyear.h index 03c8957e76..b8b6c2c47b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/dayyear.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/dayyear.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_DAYYEAR_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_DAYYEAR_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/hour.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/hour.h index fe260a0ae6..98dd782d11 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/hour.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/hour.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_HOUR_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_HOUR_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/houryear.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/houryear.h index 8a7069c98e..9024612a70 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/houryear.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/houryear.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_ALL_HOUR_YEAR_H__ #define __ANTARES_TOOLBOX_FILTER_ALL_HOUR_YEAR_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/month.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/all/month.cpp index e0477c1823..f5994dd83b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/month.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/month.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "month.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/month.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/month.h index ffd15b5573..531aac4bf2 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/month.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/month.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_MONTH_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_MONTH_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/week.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/all/week.cpp index b3d4b4203c..40d4255189 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/week.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/week.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "week.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/week.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/week.h index 0caed18db8..9473050415 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/week.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/week.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_WEEK_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_WEEK_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/all/weekday.h b/src/ui/simulator/toolbox/components/datagrid/filter/all/weekday.h index 19780d297e..b57a2f22ea 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/all/weekday.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/all/weekday.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_WEEKDAY_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID_FILTER_ALL_WEEKDAY_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/component.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/component.cpp index a25ab49944..2fe6d2db66 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/component.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/component.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "component.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/component.h b/src/ui/simulator/toolbox/components/datagrid/filter/component.h index 3e31a1e652..47a5fae51f 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/component.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/component.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_COMPONENT_H__ #define __ANTARES_TOOLBOX_FILTER_COMPONENT_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/filter.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/filter.cpp index 145fe02137..79ba349e05 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/filter.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/filter.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "operator.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/filter.h b/src/ui/simulator/toolbox/components/datagrid/filter/filter.h index c5631fa69b..1b0627e991 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/filter.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/filter.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_FILTER_H__ #define __ANTARES_TOOLBOX_FILTER_FILTER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/input.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/input.cpp index 782177ec0e..3c9745254c 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/input.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/input.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "input.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/input.h b/src/ui/simulator/toolbox/components/datagrid/filter/input.h index 5fdc0b2c42..83660082e4 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/input.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/input.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_INPUT_H__ #define __ANTARES_TOOLBOX_FILTER_INPUT_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/operator.cpp index 35dd8c86ca..ef4d2e1997 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "operator.h" @@ -36,7 +30,7 @@ namespace Filter namespace Operator { AOperator::AOperator(AFilterBase* parent, const wxChar* name, const wxChar* caption) : - pParentFilter(parent), pName(name), pCaption(caption), pSizer(NULL) + pParentFilter(parent), pName(name), pCaption(caption), pSizer(nullptr) { parameters.push_back(Parameter(*this).presetInt()); } diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator.h index 526d34b39f..e316254bf4 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATION_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.cpp index 4615d2bead..d1968d7298 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "operator.list.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.h index e3b7b0a58c..3f71671ddb 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator.list.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_LIST_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_LIST_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/all.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/all.h index 90a6f50f94..b358494f38 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/all.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/all.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_ALL_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_ALL_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/equals.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/equals.h index 6690c7acff..79f34b7855 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/equals.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/equals.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_NOT_EQUALS_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_NOT_EQUALS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthan.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthan.h index 3b2b689d39..0f7ade60d4 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthan.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthan.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_GREATER_THAN_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_GREATER_THAN_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthanorequalsto.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthanorequalsto.h index e0b7d1c24e..a7ef308ccb 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthanorequalsto.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/greaterthanorequalsto.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_GREATER_THAN_OR_EQUALS_TO_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_GREATER_THAN_OR_EQUALS_TO_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthan.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthan.h index c3d144ddb5..d3063caa7b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthan.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthan.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_LESS_THAN_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_LESS_THAN_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthanorequalsto.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthanorequalsto.h index 747c616f59..32b3c26927 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthanorequalsto.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/lessthanorequalsto.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_LESS_THAN_OR_EQUALS_TO_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_LESS_THAN_OR_EQUALS_TO_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/modulo.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/modulo.h index fbde0158d3..96a9e561e0 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/modulo.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/modulo.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_MODULO_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_MODULO_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/operator/notequals.h b/src/ui/simulator/toolbox/components/datagrid/filter/operator/notequals.h index a9dec3192e..a9e0470a32 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/operator/notequals.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/operator/notequals.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_OPERATOR_EQUALS_H__ #define __ANTARES_TOOLBOX_FILTER_OPERATOR_EQUALS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.cpp index ea0256742d..1e6711a8ee 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "parameter.h" @@ -44,7 +38,7 @@ namespace Filter namespace Operator { Parameter::Parameter(AOperator& parent) : - pOperator(parent), dataType(DataType::dtNone), pSizer(NULL) + pOperator(parent), dataType(DataType::dtNone), pSizer(nullptr) { } @@ -56,7 +50,7 @@ Parameter::Parameter(const Parameter& copy) : dataType(copy.dataType), defaultValues(copy.defaultValues), value(copy.value), - pSizer(NULL) + pSizer(nullptr) { } @@ -76,7 +70,7 @@ Parameter& Parameter::operator=(const Parameter& copy) wxSizer* Parameter::sizer(wxWindow* parent) { - if (NULL == pSizer) + if (nullptr == pSizer) { pSizer = new wxBoxSizer(wxHORIZONTAL); @@ -101,7 +95,7 @@ wxSizer* Parameter::sizer(wxWindow* parent) ch->Connect(ch->GetId(), wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(Parameter::onListChanged), - NULL, + nullptr, this); break; } @@ -131,7 +125,7 @@ wxSizer* Parameter::sizer(wxWindow* parent) edit->Connect(edit->GetId(), wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(Parameter::onChange), - NULL, + nullptr, this); } } diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.h b/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.h index 6f27de2865..9d4edec367 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.h +++ b/src/ui/simulator/toolbox/components/datagrid/filter/parameter/parameter.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_FILTER_PARAMETER_H__ #define __ANTARES_TOOLBOX_FILTER_PARAMETER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/filter/static.cpp b/src/ui/simulator/toolbox/components/datagrid/filter/static.cpp index b1c2c720f8..b5f055a1ca 100644 --- a/src/ui/simulator/toolbox/components/datagrid/filter/static.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/filter/static.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "filter.h" @@ -69,7 +63,7 @@ struct ResultNewInstance using Type = AFilterBase*; static AFilterBase* Default() { - return NULL; + return nullptr; } static T* Value(Input* parent) { diff --git a/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp b/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp index 127bbfdceb..9b6d962f95 100644 --- a/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -277,7 +271,7 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider attr = pStyles[(uint)style]; } - assert(attr != NULL and "Invalid cell attribute"); + assert(attr &&"Invalid cell attribute"); attr->IncRef(); return attr; } diff --git a/src/ui/simulator/toolbox/components/datagrid/gridhelper.h b/src/ui/simulator/toolbox/components/datagrid/gridhelper.h index 16108c890f..ae76b93026 100644 --- a/src/ui/simulator/toolbox/components/datagrid/gridhelper.h +++ b/src/ui/simulator/toolbox/components/datagrid/gridhelper.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID__GRID_HELPER_H__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID__GRID_HELPER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/gridhelper.hxx b/src/ui/simulator/toolbox/components/datagrid/gridhelper.hxx index 23b47e2c58..1830a4b281 100644 --- a/src/ui/simulator/toolbox/components/datagrid/gridhelper.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/gridhelper.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_DATAGRID__GRID_HELPER_HXX__ #define __ANTARES_TOOLBOX_COMPONENTS_DATAGRID__GRID_HELPER_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/modifiers.hxx b/src/ui/simulator/toolbox/components/datagrid/modifiers.hxx index de31f26877..e3fa5b13eb 100644 --- a/src/ui/simulator/toolbox/components/datagrid/modifiers.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/modifiers.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_MODIFIERS_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_MODIFIERS_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer.cpp index 47acebe718..4e78cecb9c 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "renderer.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer.h index e3624fddf9..ce8d1dafb8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer.hxx index 91fd71b6cb..58edc786de 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "renderer.h" #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp index 32c5bbc4d5..ac7f54cb11 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "adequacy-patch-area-grid.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h b/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h index a0b2be5d11..81d4af2aa8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.cpp index b4930b90c8..7657e324dd 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "areas.h" @@ -114,7 +108,7 @@ void Areas::reloadDistributionLawsFromStudy(Data::TimeSeriesType ts) void Areas::resetStatus(Record::Status status, bool invalidateSize) { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); auto end = pRecord.array.end(); for (auto i = pRecord.array.begin(); i != end; ++i) { @@ -151,7 +145,7 @@ wxString Areas::columnCaption(int colIndx) const wxString Areas::rowCaption(int rowIndx) const { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (rowIndx < (int)pRecord.size()) return pRecord.array[rowIndx].wxAreaName; return wxEmptyString; @@ -159,7 +153,7 @@ wxString Areas::rowCaption(int rowIndx) const IRenderer::CellStyle Areas::cellStyle(int col, int row) const { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (row >= (int)pRecord.size()) return IRenderer::cellStyleError; const Record& record = pRecord.array[row]; @@ -195,7 +189,7 @@ wxColour Areas::cellTextColor(int, int) const wxString Areas::cellValue(int x, int y) const { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (y >= (int)pRecord.size()) return wxEmptyString; const Record& record = pRecord.array[y]; @@ -230,7 +224,7 @@ wxString Areas::cellValue(int x, int y) const double Areas::cellNumericValue(int x, int y) const { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (y >= (int)pRecord.size()) return IRenderer::cellStyleError; const Record& record = pRecord.array[y]; @@ -251,7 +245,7 @@ bool Areas::cellValue(int x, int y, const String& value) { if (x == 0) { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (y >= (int)pRecord.size()) return false; pOnBeforeUpdate(x, y); @@ -267,7 +261,7 @@ bool Areas::cellValue(int x, int y, const String& value) } if (x == 1) // distribution { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (y >= (int)pRecord.size()) return false; Record& record = pRecord.array[y]; @@ -284,7 +278,7 @@ bool Areas::cellValue(int x, int y, const String& value) } if (x == 2) // absolute { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (y >= (int)pRecord.size()) return false; Record& record = pRecord.array[y]; @@ -309,7 +303,7 @@ bool Areas::cellValue(int x, int y, const String& value) } if (x == 3) { - Yuni::MutexLocker locker(pRecord.mutex); + std::lock_guard locker(pRecord.mutex); if (y >= (int)pRecord.size()) return false; pOnBeforeUpdate(x, y); diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.h b/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.h index 9b305202ec..22e41882a8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/analyzer/areas.h @@ -1,34 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_CORRELATION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_CORRELATION_H__ #include "../../renderer.h" #include +#include #include #include #include @@ -76,7 +71,7 @@ class Areas final : public virtual Renderer::IRenderer } public: - mutable Yuni::Mutex mutex; + mutable std::mutex mutex; std::vector array; bool canRunAnalyzer; }; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area.cpp index bdf7f8107c..5a0fa032d1 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "area.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area.h index 7a69b7f3b6..6fbe45da15 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.cpp index 2d9c821c4a..8771a905f9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "common.areasummary.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.h index 170af053fd..d2313a4838 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/common.areasummary.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.cpp index a396f4dc92..d1bfaad18a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "creditmodulations.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.h index 4066a40fd8..97f2625a9f 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/creditmodulations.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_CREDITMODULATIONS_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_CREDITMODULATIONS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.cpp index 75fb6fb4cf..8f7835a381 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "dsm.h" @@ -64,7 +58,7 @@ wxString DSM::columnCaption(int colIndx) const void DSM::internalAreaChanged(Antares::Data::Area* area) { - this->matrix((area) ? &(area->reserves) : NULL); + this->matrix((area) ? &(area->reserves) : nullptr); Renderer::ARendererArea::internalAreaChanged(area); } diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.h index c5e4e65ac7..97d1b055c9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/dsm.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_DSM_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_DSM_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.cpp index dff1d879eb..edcb9cced0 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "allocation.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.h index c0bc98649d..582dd97e18 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydro/allocation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_HYDRO_ALLOCATION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_HYDRO_ALLOCATION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.cpp index 9c0d2c0bfb..d0863af5b3 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "hydromonthlypower.h" @@ -37,45 +31,45 @@ namespace Datagrid { namespace Renderer { -HydroMonthlyPower::HydroMonthlyPower(wxWindow* control, Toolbox::InputSelector::Area* notifier) : - MatrixAncestorType(control), Renderer::ARendererArea(control, notifier) +HydroMonthlyHours::HydroMonthlyHours(wxWindow* control, + Toolbox::InputSelector::Area* notifier, + HoursType type) : + MatrixAncestorType(control), Renderer::ARendererArea(control, notifier), hoursType(type) { } -HydroMonthlyPower::~HydroMonthlyPower() +HydroMonthlyHours::~HydroMonthlyHours() { destroyBoundEvents(); } -wxString HydroMonthlyPower::columnCaption(int colIndx) const +wxString HydroMonthlyHours::columnCaption(int colIndx) const { - switch (colIndx) + if (colIndx == 0 && hoursType == HoursType::Generation) { - case Data::PartHydro::genMaxP: - return wxT(" Generating Max Power \n (MW) "); - case Data::PartHydro::genMaxE: return wxT(" Generating Max Energy \n (Hours at Pmax) "); - case Data::PartHydro::pumpMaxP: - return wxT(" Pumping Max Power \n (MW) "); - case Data::PartHydro::pumpMaxE: - return wxT(" Pumping Max Energy \n (Hours at Pmax) "); - default: + } + else if (colIndx == 0 && hoursType == HoursType::Pumping) + { + return wxT(" Pumping Max Energy \n (Hours at Pmax) "); + } + else + { return wxEmptyString; } - return wxEmptyString; } -wxString HydroMonthlyPower::cellValue(int x, int y) const +wxString HydroMonthlyHours::cellValue(int x, int y) const { return MatrixAncestorType::cellValue(x, y); } -double HydroMonthlyPower::cellNumericValue(int x, int y) const +double HydroMonthlyHours::cellNumericValue(int x, int y) const { return MatrixAncestorType::cellNumericValue(x, y); } -bool HydroMonthlyPower::cellValue(int x, int y, const String& value) +bool HydroMonthlyHours::cellValue(int x, int y, const String& value) { double v; if (not value.to(v)) @@ -93,7 +87,7 @@ bool HydroMonthlyPower::cellValue(int x, int y, const String& value) return MatrixAncestorType::cellValue(x, y, String() << Math::Round(v, round)); } -void HydroMonthlyPower::internalAreaChanged(Antares::Data::Area* area) +void HydroMonthlyHours::internalAreaChanged(Antares::Data::Area* area) { // FIXME for some reasons, the variable study here is not properly initialized if (area && !study) @@ -101,67 +95,48 @@ void HydroMonthlyPower::internalAreaChanged(Antares::Data::Area* area) Data::PartHydro* pHydro = (area) ? &(area->hydro) : nullptr; Renderer::ARendererArea::internalAreaChanged(area); - if (pHydro) - MatrixAncestorType::matrix(&pHydro->maxPower); + if (pHydro && hoursType == HoursType::Generation) + MatrixAncestorType::matrix(&pHydro->dailyNbHoursAtGenPmax); + else if (pHydro && hoursType == HoursType::Pumping) + MatrixAncestorType::matrix(&pHydro->dailyNbHoursAtPumpPmax); else MatrixAncestorType::matrix(nullptr); } -IRenderer::CellStyle HydroMonthlyPower::cellStyle(int col, int row) const +IRenderer::CellStyle HydroMonthlyHours::cellStyle(int col, int row) const { - switch (col) + if (double MaxE = MatrixAncestorType::cellNumericValue(0, row); + col == 0 && (MaxE < 0. || MaxE > 24.)) { - case 0: - { - double genMaxP = MatrixAncestorType::cellNumericValue(0, row); - if (genMaxP < 0.) - return IRenderer::cellStyleError; - break; - } - case 1: - { - double genMaxE = MatrixAncestorType::cellNumericValue(1, row); - if (genMaxE < 0. || genMaxE > 24.) - return IRenderer::cellStyleError; - break; - } - case 2: - { - double PumpMaxP = MatrixAncestorType::cellNumericValue(2, row); - if (PumpMaxP < 0.) - return IRenderer::cellStyleError; - break; + return IRenderer::cellStyleError; } - case 3: + else { - double PumpMaxE = MatrixAncestorType::cellNumericValue(3, row); - if (PumpMaxE < 0. || PumpMaxE > 24.) - return IRenderer::cellStyleError; - break; + return IRenderer::cellStyleWithNumericCheck(col, row); } - } - return IRenderer::cellStyleWithNumericCheck(col, row); } -wxString HydroMonthlyPower::rowCaption(int row) const +wxString HydroMonthlyHours::rowCaption(int row) const { if (!study || row >= study->calendar.maxDaysInYear) return wxEmptyString; return wxStringFromUTF8(study->calendar.text.daysYear[row]); } -void HydroMonthlyPower::onStudyClosed() +void HydroMonthlyHours::onStudyClosed() { MatrixAncestorType::onStudyClosed(); Renderer::ARendererArea::onStudyClosed(); } -void HydroMonthlyPower::onStudyLoaded() +void HydroMonthlyHours::onStudyLoaded() { MatrixAncestorType::onStudyLoaded(); Renderer::ARendererArea::onStudyLoaded(); } +// Pump + } // namespace Renderer } // namespace Datagrid } // namespace Component diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.h index 9acd8213f2..987c625f06 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydromonthlypower.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_HYDRO_MONTHLY_POWER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_HYDRO_MONTHLY_POWER_H__ @@ -40,11 +34,17 @@ namespace Datagrid { namespace Renderer { -class HydroMonthlyPower final : public Renderer::Matrix, + +class HydroMonthlyHours final : public Renderer::Matrix, public Renderer::ARendererArea { public: using MatrixAncestorType = Renderer::Matrix; + enum class HoursType + { + Generation = 0, + Pumping + }; public: //! \name Constructor & Destructor @@ -52,20 +52,22 @@ class HydroMonthlyPower final : public Renderer::Matrix, /*! ** \brief Constructor */ - HydroMonthlyPower(wxWindow* control, Toolbox::InputSelector::Area* notifier); + HydroMonthlyHours(wxWindow* control, Toolbox::InputSelector::Area* notifier, HoursType type); //! Destructor - virtual ~HydroMonthlyPower(); + virtual ~HydroMonthlyHours(); //@} virtual int width() const { - return 4; + return 1; } virtual int height() const { return DAYS_PER_YEAR; } + HoursType hoursType; + virtual wxString columnCaption(int colIndx) const; virtual wxString rowCaption(int rowIndx) const; @@ -108,7 +110,7 @@ class HydroMonthlyPower final : public Renderer::Matrix, //! Event: the study has been loaded virtual void onStudyLoaded() override; -}; // class HydroMonthlyPower +}; // class HydroMonthlyHoursGen } // namespace Renderer } // namespace Datagrid diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.cpp index fbf0088fab..f2d0ebbabf 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "hydroprepro.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.h index caf8784067..d1d4c63aaa 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/hydroprepro.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_HYDROPREPRO_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_HYDROPREPRO_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.cpp index c0758817ca..8f82c2340a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "inflowpattern.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.h index 6c237cbcde..3c0ae8b13a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/inflowpattern.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_INFLOWPATTERN_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_INFLOWPATTERN_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.cpp index 0f8de81a04..c1749b27ae 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "misc.h" @@ -106,7 +100,7 @@ double Misc::cellNumericValue(int x, int y) const void Misc::internalAreaChanged(Antares::Data::Area* area) { - this->matrix((area) ? &(area->miscGen) : NULL); + this->matrix((area) ? &(area->miscGen) : nullptr); Renderer::ARendererArea::internalAreaChanged(area); } diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.h index 7042f57258..173c608c84 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/misc.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_MISC_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_MISC_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.cpp index 577b4c85bd..59b412c437 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "nodal-optimization.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.h index 0c62d53437..456e84c264 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/nodal-optimization.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_NODAL_OPTIMIZATION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_NODAL_OPTIMIZATION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.cpp index 59ff293c0c..ebfe851030 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "renewable.areasummary.h" @@ -51,7 +45,7 @@ RenewableClusterSummarySingleArea::~RenewableClusterSummarySingleArea() wxString RenewableClusterSummarySingleArea::rowCaption(int rowIndx) const { if (pArea) - return wxStringFromUTF8(pArea->renewable.list.byIndex[rowIndx]->name()); + return wxStringFromUTF8(pArea->renewable.list[rowIndx]->name()); return wxEmptyString; } @@ -70,8 +64,8 @@ wxString RenewableClusterSummarySingleArea::columnCaption(int colIndx) const wxString RenewableClusterSummarySingleArea::cellValue(int x, int y) const { - Data::RenewableCluster* cluster = (pArea and (uint) y < pArea->renewable.list.size()) - ? pArea->renewable.list.byIndex[y] + Data::RenewableCluster* cluster = (pArea and (uint) y < pArea->renewable.list.allClustersCount()) + ? pArea->renewable.list[y].get() : nullptr; switch (x) { @@ -89,8 +83,8 @@ wxString RenewableClusterSummarySingleArea::cellValue(int x, int y) const double RenewableClusterSummarySingleArea::cellNumericValue(int x, int y) const { - Data::RenewableCluster* cluster = (pArea and (uint) y < pArea->renewable.list.size()) - ? pArea->renewable.list.byIndex[y] + Data::RenewableCluster* cluster = (pArea and (uint) y < pArea->renewable.list.allClustersCount()) + ? pArea->renewable.list[y].get() : nullptr; // gp : do we wish to have the line empty if cluster disabled // if (!cluster->enabled) @@ -111,8 +105,8 @@ double RenewableClusterSummarySingleArea::cellNumericValue(int x, int y) const bool RenewableClusterSummarySingleArea::cellValue(int x, int y, const String& v) { - auto* cluster = (pArea and (uint) y < pArea->renewable.list.size()) - ? pArea->renewable.list.byIndex[y] + auto* cluster = (pArea and (uint) y < pArea->renewable.list.allClustersCount()) + ? pArea->renewable.list[y].get() : nullptr; if (cluster) diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.h index 9a891885a3..3d277891d8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/renewable.areasummary.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_RENEWABLE_SUMMARY_SINGLE_AREA_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_RENEWABLE_SUMMARY_SINGLE_AREA_H__ @@ -50,7 +44,7 @@ class RenewableClusterSummarySingleArea : public CommonClusterSummarySingleArea } virtual int height() const { - return (pArea) ? pArea->renewable.list.size() : 0; + return (pArea) ? pArea->renewable.list.allClustersCount() : 0; } virtual wxString columnCaption(int colIndx) const override; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.cpp index 6157ca24ce..2fbf5c380e 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "reservoirlevels.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.h index 7294668108..1e17ffc96b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/reservoirlevels.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_RESERVOIRLEVELS_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_RESERVOIRLEVELS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.cpp index c49cf595a0..15a233b38b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "thermal.areasummary.h" @@ -51,7 +45,7 @@ ThermalClusterSummarySingleArea::~ThermalClusterSummarySingleArea() wxString ThermalClusterSummarySingleArea::rowCaption(int rowIndx) const { if (pArea) - return wxStringFromUTF8(pArea->thermal.list.byIndex[rowIndx]->name()); + return wxStringFromUTF8(pArea->thermal.list[rowIndx]->name()); return wxEmptyString; } @@ -81,8 +75,8 @@ wxString ThermalClusterSummarySingleArea::columnCaption(int colIndx) const wxString ThermalClusterSummarySingleArea::cellValue(int x, int y) const { - Data::ThermalCluster* cluster = (pArea and (uint) y < pArea->thermal.list.size()) - ? pArea->thermal.list.byIndex[y] + Data::ThermalCluster* cluster = (pArea and (uint) y < pArea->thermal.list.allClustersCount()) + ? pArea->thermal.list[y].get() : nullptr; if (!cluster->enabled) return wxEmptyString; @@ -124,8 +118,8 @@ wxString ThermalClusterSummarySingleArea::cellValue(int x, int y) const double ThermalClusterSummarySingleArea::cellNumericValue(int x, int y) const { - Data::ThermalCluster* cluster = (pArea and (uint) y < pArea->thermal.list.size()) - ? pArea->thermal.list.byIndex[y] + Data::ThermalCluster* cluster = (pArea and (uint) y < pArea->thermal.list.allClustersCount()) + ? pArea->thermal.list[y].get() : nullptr; if (!cluster->enabled) return 0.; @@ -167,8 +161,8 @@ double ThermalClusterSummarySingleArea::cellNumericValue(int x, int y) const bool ThermalClusterSummarySingleArea::cellValue(int x, int y, const String& v) { - auto* cluster = (pArea and (uint) y < pArea->thermal.list.size()) - ? pArea->thermal.list.byIndex[y] + auto* cluster = (pArea and (uint) y < pArea->thermal.list.allClustersCount()) + ? pArea->thermal.list[y].get() : nullptr; if (cluster) diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.h index 277459598b..bb4bb0c3a5 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermal.areasummary.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_THERMAL_SUMMARY_SINGLE_AREA_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_THERMAL_SUMMARY_SINGLE_AREA_H__ @@ -50,7 +44,7 @@ class ThermalClusterSummarySingleArea : public CommonClusterSummarySingleArea } virtual int height() const override { - return (pArea) ? pArea->thermal.list.size() : 0; + return (pArea) ? pArea->thermal.list.allClustersCount() : 0; } virtual wxString columnCaption(int colIndx) const override; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.cpp index 1cd8945922..bf72ed3dc0 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "thermalmodulation.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.h index 55e1c5a10b..8d61013f29 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalmodulation.h @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_THERMAL_COMMON_MODULATION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_THERMAL_COMMON_MODULATION_H__ #include "../../../../input/thermal-cluster.h" #include "../matrix.h" -#include +#include namespace Antares { diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.cpp index 75220e49e2..4c39002613 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "thermalprepro.h" @@ -44,13 +38,13 @@ namespace Renderer ** ** MTBF: Mean Time Between Failure */ -static double MTBFForFO(Antares::Data::PreproThermal* preproThermal, int y) +static double MTBFForFO(Antares::Data::PreproAvailability* preproThermal, int y) { if (y >= 0 and y < DAYS_PER_YEAR and preproThermal) { auto& data = preproThermal->data; - double rate = data[Antares::Data::PreproThermal::foRate][y]; - double duration = data[Antares::Data::PreproThermal::foDuration][y]; + double rate = data[Antares::Data::PreproAvailability::foRate][y]; + double duration = data[Antares::Data::PreproAvailability::foDuration][y]; if (Math::Zero(rate)) return std::numeric_limits::infinity(); @@ -66,13 +60,13 @@ static double MTBFForFO(Antares::Data::PreproThermal* preproThermal, int y) ** ** MTBF: Mean Time Between Failure */ -static double MTBFForPO(Antares::Data::PreproThermal* preproThermal, int y) +static double MTBFForPO(Antares::Data::PreproAvailability* preproThermal, int y) { if (y >= 0 and y < DAYS_PER_YEAR and preproThermal) { auto& data = preproThermal->data; - double rate = data[Antares::Data::PreproThermal::poRate][y]; - double duration = data[Antares::Data::PreproThermal::poDuration][y]; + double rate = data[Antares::Data::PreproAvailability::poRate][y]; + double duration = data[Antares::Data::PreproAvailability::poDuration][y]; if (Math::Zero(rate)) return std::numeric_limits::infinity(); @@ -85,7 +79,7 @@ static double MTBFForPO(Antares::Data::PreproThermal* preproThermal, int y) ThermalClusterPrepro::ThermalClusterPrepro(wxWindow* control, Toolbox::InputSelector::ThermalCluster* notifier) : - MatrixAncestorType(control), pPreproThermal(nullptr) + MatrixAncestorType(control) { if (notifier) notifier->onThermalClusterChanged.connect( @@ -153,14 +147,14 @@ double ThermalClusterPrepro::cellNumericValue(int x, int y) const { if (x > 5) { - if (y >= 0 and y < DAYS_PER_YEAR and pPreproThermal) + if (y >= 0 and y < DAYS_PER_YEAR and pPreproAvailability) { switch (x) { case 6: - return MTBFForFO(pPreproThermal, y); + return MTBFForFO(pPreproAvailability, y); case 7: - return MTBFForPO(pPreproThermal, y); + return MTBFForPO(pPreproAvailability, y); } } return 0.; @@ -189,8 +183,8 @@ bool ThermalClusterPrepro::cellValue(int x, int y, const String& value) void ThermalClusterPrepro::internalThermalClusterChanged(Antares::Data::ThermalCluster* cluster) { pCluster = cluster; - pPreproThermal = (cluster) ? cluster->prepro : nullptr; - MatrixAncestorType::matrix((pPreproThermal) ? &pPreproThermal->data : nullptr); + pPreproAvailability = (cluster) ? cluster->prepro : nullptr; + MatrixAncestorType::matrix((pPreproAvailability) ? &pPreproAvailability->data : nullptr); onRefresh(); } @@ -208,14 +202,14 @@ IRenderer::CellStyle ThermalClusterPrepro::cellStyle(int col, int row) const // MTBF FO if (col == 6) { - double mtbf = MTBFForFO(pPreproThermal, row); + double mtbf = MTBFForFO(pPreproAvailability, row); if (Math::Zero(mtbf)) return IRenderer::cellStyleWarning; } // MTBF PO if (col == 7) { - double mtbf = MTBFForPO(pPreproThermal, row); + double mtbf = MTBFForPO(pPreproAvailability, row); if (Math::Zero(mtbf)) return IRenderer::cellStyleWarning; } diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.h index 197b9c9f63..60dd2231f0 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/thermalprepro.h @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_THERMALPREPRO_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_THERMALPREPRO_H__ #include "../../../../input/thermal-cluster.h" #include "../matrix.h" -#include +#include namespace Antares { @@ -110,7 +104,7 @@ class ThermalClusterPrepro : public Renderer::Matrix<> virtual void onStudyClosed() override; private: - Antares::Data::PreproThermal* pPreproThermal; + Antares::Data::PreproAvailability* pPreproAvailability = nullptr; Antares::Data::ThermalCluster* pCluster; }; // class ThermalClusterPrepro diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.cpp index 949677e7be..a1060c1b70 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "timeseries.h" @@ -360,7 +354,7 @@ void TimeSeriesThermalClusterFuelCost::onStudyClosed() void TimeSeriesThermalClusterFuelCost::internalThermalClusterChanged( Antares::Data::ThermalCluster* cluster) { - matrix((CurrentStudyIsValid() && cluster) ? &(cluster->ecoInput.fuelcost) : NULL); + matrix((CurrentStudyIsValid() && cluster) ? &(cluster->ecoInput.fuelcost) : nullptr); } // ---------------------- @@ -390,7 +384,7 @@ void TimeSeriesThermalClusterCO2Cost::onStudyClosed() void TimeSeriesThermalClusterCO2Cost::internalThermalClusterChanged( Antares::Data::ThermalCluster* cluster) { - matrix((CurrentStudyIsValid() && cluster) ? &(cluster->ecoInput.co2cost) : NULL); + matrix((CurrentStudyIsValid() && cluster) ? &(cluster->ecoInput.co2cost) : nullptr); } // ---------------------- diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.h index b9ed6f3576..16d0f1b7fd 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/timeseries.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_TIMESERIES_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_TIMESERIES_H__ @@ -42,10 +36,10 @@ namespace Datagrid { namespace Renderer { -class ATimeSeries : public Renderer::Matrix, public Renderer::ARendererArea +class ATimeSeries : public Renderer::Matrix, public Renderer::ARendererArea { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; public: ATimeSeries(wxWindow* control, Toolbox::InputSelector::Area* notifier); @@ -117,7 +111,7 @@ class ATimeSeries : public Renderer::Matrix, public Renderer::A class TimeSeriesLoad final : public ATimeSeries { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; public: TimeSeriesLoad(wxWindow* control, Toolbox::InputSelector::Area* notifier) : @@ -147,7 +141,7 @@ class TimeSeriesLoad final : public ATimeSeries protected: virtual void internalAreaChanged(Antares::Data::Area* area) { - matrix((area && CurrentStudyIsValid()) ? &(area->load.series->timeSeries) : NULL); + matrix((area && CurrentStudyIsValid()) ? &(area->load.series.timeSeries) : NULL); Renderer::ARendererArea::internalAreaChanged(area); } }; @@ -155,7 +149,7 @@ class TimeSeriesLoad final : public ATimeSeries class TimeSeriesSolar final : public ATimeSeries { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; public: TimeSeriesSolar(wxWindow* control, Toolbox::InputSelector::Area* notifier) : @@ -185,7 +179,7 @@ class TimeSeriesSolar final : public ATimeSeries protected: virtual void internalAreaChanged(Antares::Data::Area* area) { - matrix((area && CurrentStudyIsValid()) ? &(area->solar.series->timeSeries) : NULL); + matrix((area && CurrentStudyIsValid()) ? &(area->solar.series.timeSeries) : NULL); Renderer::ARendererArea::internalAreaChanged(area); } }; @@ -193,7 +187,7 @@ class TimeSeriesSolar final : public ATimeSeries class TimeSeriesWind final : public ATimeSeries { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; public: TimeSeriesWind(wxWindow* control, Toolbox::InputSelector::Area* notifier) : @@ -223,7 +217,7 @@ class TimeSeriesWind final : public ATimeSeries protected: virtual void internalAreaChanged(Antares::Data::Area* area) { - matrix((area && CurrentStudyIsValid()) ? &(area->wind.series->timeSeries) : NULL); + matrix((area && CurrentStudyIsValid()) ? &(area->wind.series.timeSeries) : NULL); Renderer::ARendererArea::internalAreaChanged(area); } }; @@ -231,7 +225,7 @@ class TimeSeriesWind final : public ATimeSeries class TimeSeriesHydroFatal final : public ATimeSeries { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; public: TimeSeriesHydroFatal(wxWindow* control, Toolbox::InputSelector::Area* notifier) : @@ -256,7 +250,7 @@ class TimeSeriesHydroFatal final : public ATimeSeries protected: virtual void internalAreaChanged(Antares::Data::Area* area) { - matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->ror) : NULL); + matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->ror.timeSeries) : NULL); Renderer::ARendererArea::internalAreaChanged(area); } }; @@ -264,7 +258,7 @@ class TimeSeriesHydroFatal final : public ATimeSeries class TimeSeriesHydroMod final : public ATimeSeries { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; public: TimeSeriesHydroMod(wxWindow* control, Toolbox::InputSelector::Area* notifier) : @@ -294,7 +288,7 @@ class TimeSeriesHydroMod final : public ATimeSeries protected: virtual void internalAreaChanged(Antares::Data::Area* area) { - matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->storage) : NULL); + matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->storage.timeSeries) : NULL); Renderer::ARendererArea::internalAreaChanged(area); } }; @@ -303,7 +297,7 @@ class TimeSeriesHydroMod final : public ATimeSeries class TimeSeriesHydroMinGen final : public ATimeSeries { public: - using AncestorType = Renderer::Matrix; + using AncestorType = Renderer::Matrix; TimeSeriesHydroMinGen(wxWindow* control, Toolbox::InputSelector::Area* notifier) : ATimeSeries(control, notifier) @@ -327,7 +321,71 @@ class TimeSeriesHydroMinGen final : public ATimeSeries private: void internalAreaChanged(Antares::Data::Area* area) override { - matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->mingen) : NULL); + matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->mingen.timeSeries) : NULL); + Renderer::ARendererArea::internalAreaChanged(area); + } +}; + +class TimeSeriesHydroMaxHourlyGenPower final : public ATimeSeries +{ +public: + using AncestorType = Renderer::Matrix; + + TimeSeriesHydroMaxHourlyGenPower(wxWindow* control, Toolbox::InputSelector::Area* notifier) : + ATimeSeries(control, notifier) + { + } + ~TimeSeriesHydroMaxHourlyGenPower() override + { + destroyBoundEvents(); + } + + Date::Precision precision() override + { + return Date::hourly; + } + + uint maxHeightResize() const override + { + return HOURS_PER_YEAR; + } + +private: + void internalAreaChanged(Antares::Data::Area* area) override + { + matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->maxHourlyGenPower.timeSeries) : NULL); + Renderer::ARendererArea::internalAreaChanged(area); + } +}; + +class TimeSeriesHydroMaxHourlyPumpPower final : public ATimeSeries +{ +public: + using AncestorType = Renderer::Matrix; + + TimeSeriesHydroMaxHourlyPumpPower(wxWindow* control, Toolbox::InputSelector::Area* notifier) : + ATimeSeries(control, notifier) + { + } + ~TimeSeriesHydroMaxHourlyPumpPower() override + { + destroyBoundEvents(); + } + + Date::Precision precision() override + { + return Date::hourly; + } + + uint maxHeightResize() const override + { + return HOURS_PER_YEAR; + } + +private: + void internalAreaChanged(Antares::Data::Area* area) override + { + matrix((area && CurrentStudyIsValid()) ? &(area->hydro.series->maxHourlyPumpPower.timeSeries) : NULL); Renderer::ARendererArea::internalAreaChanged(area); } }; @@ -419,7 +477,7 @@ class TimeSeriesThermalCluster final : public TimeSeriesCluster protected: void internalThermalClusterChanged(Antares::Data::ThermalCluster* cluster) { - matrix((CurrentStudyIsValid() && cluster) ? &(cluster->series->timeSeries) : NULL); + matrix((CurrentStudyIsValid() && cluster) ? &(cluster->series.timeSeries) : NULL); } void onStudyClosed() override; @@ -468,7 +526,7 @@ class TimeSeriesRenewableCluster final : public TimeSeriesCluster private: void internalRenewableClusterChanged(Antares::Data::RenewableCluster* cluster) { - matrix((CurrentStudyIsValid() && cluster) ? &(cluster->series->timeSeries) : NULL); + matrix((CurrentStudyIsValid() && cluster) ? &(cluster->series.timeSeries) : NULL); } void onStudyClosed() override; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.cpp index 6a39b90840..00f98378a8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "watervalues.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.h index 7ca9d2e7f0..9f6d463981 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/watervalues.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_WATERVALUES_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_WATERVALUES_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.h index 722d108f37..561b558b30 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_ALL_AREAS_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_ALL_AREAS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.hxx index c5632070e0..42ddb985e4 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-allareas.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_ALL_AREAS_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_ALL_AREAS_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.h index 3e532cea30..79e2ae465b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_COEFFICIENTS_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_COEFFICIENTS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.hxx index 193a069c5a..670670e95b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-coefficients.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.h index 1088d1235a..e12bc6f2f5 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_CONVERTION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_CONVERTION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.hxx index 0b3a4b7f4d..a57ab03716 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-conversion.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_CONVERTION_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_CONVERTION_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.h index 2890ed1296..d2ee215461 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_K_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_K_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.hxx index 30e9f27972..129feb3ebd 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-k.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.h b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.h index 4f1373490b..e181eb2a38 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_TRANSLATION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_TRANSLATION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.hxx index d59bd47042..8984c77928 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/area/xcast-translation.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_TRANSLATION_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_XCAST_TRANSLATION_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.cpp index 45b2a5b009..df10169ce6 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "data.h" @@ -117,7 +111,7 @@ Date::Precision Data::precision() } } -double Data::cellNumericValue(int x, int y) const +double Data::cellNumericValue(int x, [[maybe_unused]] int y) const { if (!(!study)) { @@ -185,7 +179,7 @@ IRenderer::CellStyle Data::cellStyle(int, int y) const return ((y % 2) ? IRenderer::cellStyleDefaultAlternate : IRenderer::cellStyleDefault); } -bool Data::cellValue(int x, int y, const String& value) +bool Data::cellValue(int x, [[maybe_unused]]int y, const String& value) { if (!study) return false; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.h b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.h index 648f079e4d..5f566c8391 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/data.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_BINDINGCONSTRAINT_DATA_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_BINDINGCONSTRAINT_DATA_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.cpp index 99d4e587b1..0aadb7db54 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.h b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.h index 317701100c..b292f2f38b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/offsets.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_BINDINGCONSTRAINT_OFFSET_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_BINDINGCONSTRAINT_OFFSET_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.cpp index 47f8d8dc39..00e636b88a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.h b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.h index 67230e3b5e..6546975cd1 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/bindingconstraint/weights.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_BINDINGCONSTRAINT_WEIGHT_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_BINDINGCONSTRAINT_WEIGHT_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/cell.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/cell.cpp index bb2e40ce76..dfe09e1e46 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/cell.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/cell.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "cell.h" @@ -56,7 +76,7 @@ bool Cell::isTSgeneratorOn() const // =================== // Blank cell // =================== -blankCell::blankCell() : Cell(timeSeriesCount /*arbitrary, not used here anyway */) +blankCell::blankCell() : Cell(timeSeriesLoad /*arbitrary, not used here anyway */) { } wxString blankCell::cellValue() const @@ -80,7 +100,7 @@ IRenderer::CellStyle blankCell::cellStyle() const // Inactive cell // ======================== inactiveCell::inactiveCell(wxString toPrintInCell) : - Cell(timeSeriesCount /*arbitrary, not used here anyway */), toBePrintedInCell_(toPrintInCell) + Cell(timeSeriesLoad /*arbitrary, not used here anyway */), toBePrintedInCell_(toPrintInCell) { } diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/cell.h b/src/ui/simulator/toolbox/components/datagrid/renderer/cell.h index 1477ec4b91..a9ddf24d80 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/cell.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/cell.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/column.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/column.cpp index be086a1e6d..b5577691d8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/column.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/column.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -162,7 +156,6 @@ ColumnNTC::ColumnNTC() : Column(timeSeriesTransmissionCapacities, " Links NTC new_check_allocation(tsKind_), new_check_allocation(wxT("-"))}; } - } // namespace Renderer } // namespace Datagrid } // namespace Component diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/column.h b/src/ui/simulator/toolbox/components/datagrid/renderer/column.h index 66118f94a3..45b7129a96 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/column.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/column.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once @@ -97,7 +91,6 @@ class ColumnNTC final : public Column ColumnNTC(); ~ColumnNTC() override = default; }; - } // namespace Renderer } // namespace Datagrid } // namespace Component diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/connection.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/connection.cpp index e9fc5595d1..69d8cb6a42 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/connection.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/connection.cpp @@ -1,35 +1,32 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "connection.h" -#include "../../../libs/antares/constants.h" +#include "antares/antares/constants.h" #include #include +//! The minimal allowed value for hurdle costs when not null +#define LINK_MINIMAL_HURDLE_COSTS_NOT_NULL 0.005 + using namespace Yuni; namespace Antares @@ -228,8 +225,8 @@ void connectionParameters::setMatrix(Data::AreaLink* link) { matrix(link ? &(link->parameters) : nullptr); - direct_ntc_ = link ? &(link->directCapacities) : nullptr; - indirect_ntc_ = link ? &(link->indirectCapacities) : nullptr; + direct_ntc_ = link ? &(link->directCapacities.timeSeries) : nullptr; + indirect_ntc_ = link ? &(link->indirectCapacities.timeSeries) : nullptr; } // =========================== @@ -274,7 +271,7 @@ connectionNTCdirect::connectionNTCdirect(wxWindow* parent, } void connectionNTCdirect::setMatrix(Data::AreaLink* link) { - matrix(link ? &(link->directCapacities) : nullptr); + matrix(link ? &(link->directCapacities.timeSeries) : nullptr); mLoopFlowData = link ? &(link->parameters[Data::fhlLoopFlow]) : nullptr; } @@ -294,7 +291,7 @@ connectionNTCindirect::connectionNTCindirect(wxWindow* parent, } void connectionNTCindirect::setMatrix(Data::AreaLink* link) { - matrix(link ? &(link->indirectCapacities) : nullptr); + matrix(link ? &(link->indirectCapacities.timeSeries) : nullptr); mLoopFlowData = link ? &(link->parameters[Data::fhlLoopFlow]) : nullptr; } diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/connection.h b/src/ui/simulator/toolbox/components/datagrid/renderer/connection.h index 955a2e3111..3d5c8cdafc 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/connection.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/connection.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_CONNECTION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_CONNECTION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.cpp index 1d20de31e5..da5f71932d 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "links.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.h b/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.h index 79b4d90de3..b8907fab63 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/constraintsbuilder/links.h @@ -1,35 +1,30 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LINKS_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LINKS_H__ #include "../../renderer.h" #include -#include "../solver/constraints-builder/cbuilder.h" +#include "antares/solver/constraints-builder/cbuilder.h" +#include #include #include #include @@ -76,7 +71,7 @@ class Links final : public virtual Renderer::IRenderer } public: - mutable Yuni::Mutex mutex; + mutable std::mutex mutex; std::vector array; bool canRunAnalyzer; }; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.cpp index afd30ab0f8..797aa44dd9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "correlation.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.h b/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.h index 1ad2498663..06ca9704a9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/correlation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_CORRELATION_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREA_CORRELATION_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.cpp index 0cbb82f83f..89faea97ba 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "geographic-trimming-grid.h" #include #include "windows/inspector.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.h b/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.h index e78e8ef593..fe53d6499b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/geographic-trimming-grid.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREAS_TRIMMING_GRID_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREAS_TRIMMING_GRID_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/layers.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/layers.cpp index e5d30d6164..e3e769f647 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/layers.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/layers.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "layers.h" #include "../../../../windows/inspector.h" @@ -227,13 +221,13 @@ wxString LayersUI::cellValue(int x, int y) const return layerPosition != layerListEnd ? wxString::Format(wxT("%d"), pArea->ui->layerX[layerIterator->first]) - : wxT("-"); + : wxString(wxT("-")); case 2: return layerPosition != layerListEnd ? wxString::Format(wxT("%d"), pArea->ui->layerY[layerIterator->first]) - : wxT("-"); + : wxString(wxT("-")); } } return wxEmptyString; diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/layers.h b/src/ui/simulator/toolbox/components/datagrid/renderer/layers.h index ef7a55a98f..ef52f20aec 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/layers.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/layers.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LAYERS_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LAYERS_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.cpp index 08fe84de68..26ce235a98 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "summary.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.h b/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.h index f4f4ff1712..18f6dd18e8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/links/summary.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LINKS_SUMMARY_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LINKS_SUMMARY_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.cpp index a8c1d46d37..3fc556e8f9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "logfile.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.h b/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.h index e19b5f0605..27cee7bf95 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/logfile.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MC_PLAYLIST_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MC_PLAYLIST_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.h b/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.h index 36ade4c3c0..3f5eb6d2e3 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MATRIX_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MATRIX_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.hxx b/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.hxx index d771b1c43f..eb9fcff4a6 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.hxx +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/matrix.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MATRIX_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MATRIX_HXX__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.cpp index 6be9503fbe..fc7bf7f16a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.h b/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.h index dea0be4e4f..4bb558232a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/mc-playlist.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MC_PLAYLIST_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_MC_PLAYLIST_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.cpp new file mode 100644 index 0000000000..809767e8e6 --- /dev/null +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.cpp @@ -0,0 +1,82 @@ +/* +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ + +#include "scenario-builder-hydro-final-levels-renderer.h" +#include "antares/study/scenario-builder/scBuilderUtils.h" + +using namespace Antares::Data::ScenarioBuilder; + +namespace Antares +{ +namespace Component +{ +namespace Datagrid +{ +namespace Renderer +{ +wxString hydroFinalLevelsScBuilderRenderer::cellValue(int x, int y) const +{ + const double d = cellNumericValue(x, y); + return (std::isnan(d)) ? wxString() << wxT("init") : wxString() << fromHydroLevelToString(d); +} + +bool hydroFinalLevelsScBuilderRenderer::cellValue(int x, int y, const Yuni::String& value) +{ + if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears + && (uint)y < study->areas.size()) + { + assert((uint)y < pRules->hydroFinalLevels.width()); + assert((uint)x < pRules->hydroFinalLevels.height()); + double val = fromStringToHydroLevel(value, 100.) / 100.; + pRules->hydroFinalLevels.set_value(x, y, val); + return true; + } + return false; +} + +double hydroFinalLevelsScBuilderRenderer::cellNumericValue(int x, int y) const +{ + if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears + && (uint)y < study->areas.size()) + { + assert((uint)y < pRules->hydroFinalLevels.width()); + assert((uint)x < pRules->hydroFinalLevels.height()); + return pRules->hydroFinalLevels.get_value(x, y) * 100.; + } + return 0.; +} + +IRenderer::CellStyle hydroFinalLevelsScBuilderRenderer::cellStyle(int x, int y) const +{ + bool valid = (!(!study) && !(!pRules) && std::isnan(cellNumericValue(x, y))); + return valid ? cellStyleDefaultCenterDisabled : cellStyleDefaultCenter; +} + +} // namespace Renderer +} // namespace Datagrid +} // namespace Component +} // namespace Antares diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h new file mode 100644 index 0000000000..85a7c87e0f --- /dev/null +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h @@ -0,0 +1,56 @@ +/* +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator 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. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator 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 Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ +#ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_FINAL_LEVELS_SCENARIO_BUILDER_H__ +#define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_FINAL_LEVELS_SCENARIO_BUILDER_H__ + +#include "scenario-builder-renderer-base.h" + +namespace Antares +{ +namespace Component +{ +namespace Datagrid +{ +namespace Renderer +{ +class hydroFinalLevelsScBuilderRenderer : public ScBuilderRendererAreasAsRows +{ +public: + hydroFinalLevelsScBuilderRenderer() = default; + + wxString cellValue(int x, int y) const; + bool cellValue(int x, int y, const Yuni::String& value); + double cellNumericValue(int x, int y) const; + IRenderer::CellStyle cellStyle(int x, int y) const; +}; // class hydroLevelsScBuilderRenderer + +} // namespace Renderer +} // namespace Datagrid +} // namespace Component +} // namespace Antares + +#endif // __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_FINAL_LEVELS_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.cpp index 53d5c1714d..4dce437a7d 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-hydro-levels-renderer.h" @@ -46,30 +40,26 @@ wxString hydroLevelsScBuilderRenderer::cellValue(int x, int y) const bool hydroLevelsScBuilderRenderer::cellValue(int x, int y, const Yuni::String& value) { - if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears) + if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears + && (uint)y < study->areas.size()) { - if ((uint)y < study->areas.size()) - { - assert((uint)y < pRules->hydroLevels.width()); - assert((uint)x < pRules->hydroLevels.height()); - double val = fromStringToHydroLevel(value, 100.) / 100.; - pRules->hydroLevels.set_value(x, y, val); - return true; - } + assert((uint)y < pRules->hydroInitialLevels.width()); + assert((uint)x < pRules->hydroInitialLevels.height()); + double val = fromStringToHydroLevel(value, 100.) / 100.; + pRules->hydroInitialLevels.set_value(x, y, val); + return true; } return false; } double hydroLevelsScBuilderRenderer::cellNumericValue(int x, int y) const { - if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears) + if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears + && (uint)y < study->areas.size()) { - if ((uint)y < study->areas.size()) - { - assert((uint)y < pRules->hydroLevels.width()); - assert((uint)x < pRules->hydroLevels.height()); - return pRules->hydroLevels.get_value(x, y) * 100.; - } + assert((uint)y < pRules->hydroInitialLevels.width()); + assert((uint)x < pRules->hydroInitialLevels.height()); + return pRules->hydroInitialLevels.get_value(x, y) * 100.; } return 0.; } @@ -77,7 +67,7 @@ double hydroLevelsScBuilderRenderer::cellNumericValue(int x, int y) const IRenderer::CellStyle hydroLevelsScBuilderRenderer::cellStyle(int x, int y) const { bool valid = (!(!study) && !(!pRules) && std::isnan(cellNumericValue(x, y))); - return (valid) ? cellStyleDefaultCenterDisabled : cellStyleDefaultCenter; + return valid ? cellStyleDefaultCenterDisabled : cellStyleDefaultCenter; } } // namespace Renderer diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.h index 1e44d44d50..58202fc499 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-levels-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_LEVELS_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_LEVELS_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.cpp index b0576280d7..9ff1f71f68 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-hydro-renderer.h" @@ -68,7 +62,6 @@ double hydroScBuilderRenderer::cellNumericValue(int x, int y) const } return 0.; } - } // namespace Renderer } // namespace Datagrid } // namespace Component diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.h index d0b8480f28..617f7fbf71 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_HYDRO_SCENARIO_BUILDER_H__ @@ -45,7 +39,6 @@ class hydroScBuilderRenderer : public ScBuilderRendererAreasAsRows bool cellValue(int x, int y, const Yuni::String& value); double cellNumericValue(int x, int y) const; }; // class hydroScBuilderRenderer - } // namespace Renderer } // namespace Datagrid } // namespace Component diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.cpp index 0373144194..5b038704c9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-load-renderer.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.h index acc63a2109..87be1596a3 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-load-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LOAD_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LOAD_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.cpp index da91b31b6e..95aa81ac97 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "scenario-builder-ntc-renderer.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.h index 700a5390f0..edc1c49580 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-ntc-renderer.h @@ -1,3 +1,23 @@ +/* + * Copyright 2007-2024, RTE (https://www.rte-france.com) + * See AUTHORS.txt + * SPDX-License-Identifier: MPL-2.0 + * This file is part of Antares-Simulator, + * Adequacy and Performance assessment for interconnected energy networks. + * + * Antares_Simulator is free software: you can redistribute it and/or modify + * it under the terms of the Mozilla Public Licence 2.0 as published by + * the Mozilla Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * Antares_Simulator 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 + * Mozilla Public Licence 2.0 for more details. + * + * You should have received a copy of the Mozilla Public Licence 2.0 + * along with Antares_Simulator. If not, see . + */ #pragma once #include "scenario-builder-renderer-base.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.cpp index d3d2f7c1db..a0858ae227 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-renderer-base.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.h index aa34127985..90cac32786 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renderer-base.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.cpp index c522544756..50bd75bba1 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-renewable-renderer.h" @@ -43,7 +37,7 @@ int renewableScBuilderRenderer::height() const { if (!(!study) && !(!pRules) && selectedArea()) { - return (int)selectedArea()->renewable.list.size(); + return (int)selectedArea()->renewable.list.allClustersCount(); } return 0; } @@ -51,10 +45,10 @@ int renewableScBuilderRenderer::height() const wxString renewableScBuilderRenderer::rowCaption(int rowIndx) const { if (!(!study) && !(!pRules) && selectedArea() - && (uint)rowIndx < selectedArea()->renewable.list.size()) + && (uint)rowIndx < selectedArea()->renewable.list.allClustersCount()) { return wxString() << wxT( - " ") << wxStringFromUTF8(selectedArea()->renewable.list.byIndex[rowIndx]->name()) + " ") << wxStringFromUTF8(selectedArea()->renewable.list[rowIndx]->name()) << wxT(" "); } return wxEmptyString; @@ -63,14 +57,14 @@ wxString renewableScBuilderRenderer::rowCaption(int rowIndx) const bool renewableScBuilderRenderer::cellValue(int x, int y, const String& value) { if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears && selectedArea() - && (uint)y < selectedArea()->renewable.list.size()) + && (uint)y < selectedArea()->renewable.list.allClustersCount()) { assert(selectedArea()->index < pRules->areaCount()); assert((uint)y < pRules->renewable[selectedArea()->index].width()); assert((uint)x < pRules->renewable[selectedArea()->index].height()); uint val = fromStringToTSnumber(value); pRules->renewable[selectedArea()->index].setTSnumber( - selectedArea()->renewable.list.byIndex[y], x, val); + selectedArea()->renewable.list[y].get(), x, val); return true; } return false; @@ -79,7 +73,7 @@ bool renewableScBuilderRenderer::cellValue(int x, int y, const String& value) double renewableScBuilderRenderer::cellNumericValue(int x, int y) const { if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears && selectedArea() - && (uint)y < selectedArea()->renewable.list.size()) + && (uint)y < selectedArea()->renewable.list.allClustersCount()) { assert((uint)y < pRules->renewable[selectedArea()->index].width()); assert((uint)x < pRules->renewable[selectedArea()->index].height()); diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.h index 60ccd2a08c..8d3dcd9b66 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-renewable-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_RENEWABLE_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_RENEWABLE_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.cpp index 73efeca0be..0ba2822cc5 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-solar-renderer.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.h index 9bbbb71e43..88ba21cc6b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-solar-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_SOLAR_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_LOAD_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.cpp index 7449c3c9b0..c31d39e64e 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-thermal-renderer.h" @@ -43,7 +37,7 @@ int thermalScBuilderRenderer::height() const { if (!(!study) && !(!pRules) && selectedArea()) { - return (int)selectedArea()->thermal.list.size(); + return (int)selectedArea()->thermal.list.allClustersCount(); } return 0; } @@ -51,10 +45,10 @@ int thermalScBuilderRenderer::height() const wxString thermalScBuilderRenderer::rowCaption(int rowIndx) const { if (!(!study) && !(!pRules) && selectedArea() - && (uint)rowIndx < selectedArea()->thermal.list.size()) + && (uint)rowIndx < selectedArea()->thermal.list.allClustersCount()) { return wxString() << wxT(" ") - << wxStringFromUTF8(selectedArea()->thermal.list.byIndex[rowIndx]->name()) + << wxStringFromUTF8(selectedArea()->thermal.list[rowIndx]->name()) << wxT(" "); } return wxEmptyString; @@ -63,13 +57,13 @@ wxString thermalScBuilderRenderer::rowCaption(int rowIndx) const bool thermalScBuilderRenderer::cellValue(int x, int y, const String& value) { if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears && selectedArea() - && (uint)y < selectedArea()->thermal.list.size()) + && (uint)y < selectedArea()->thermal.list.allClustersCount()) { assert(selectedArea()->index < pRules->areaCount()); assert((uint)y < pRules->thermal[selectedArea()->index].width()); assert((uint)x < pRules->thermal[selectedArea()->index].height()); uint val = fromStringToTSnumber(value); - pRules->thermal[selectedArea()->index].setTSnumber(selectedArea()->thermal.list.byIndex[y], x, val); + pRules->thermal[selectedArea()->index].setTSnumber(selectedArea()->thermal.list[y].get(), x, val); return true; } return false; @@ -78,7 +72,7 @@ bool thermalScBuilderRenderer::cellValue(int x, int y, const String& value) double thermalScBuilderRenderer::cellNumericValue(int x, int y) const { if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears && selectedArea() - && (uint)y < selectedArea()->thermal.list.size()) + && (uint)y < selectedArea()->thermal.list.allClustersCount()) { assert((uint)y < pRules->thermal[selectedArea()->index].width()); assert((uint)x < pRules->thermal[selectedArea()->index].height()); diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.h index 3c7735376b..7a7fd1ce30 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-thermal-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_THERMAL_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_THERMAL_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.cpp index f112bbacc2..315db9b19a 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "scenario-builder-wind-renderer.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.h index 67c9ea1fd6..6dc2343a4c 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-wind-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_WIND_SCENARIO_BUILDER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_WIND_SCENARIO_BUILDER_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.cpp index 80b7223f7d..b5eae1f1e7 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "select-variables.h" #include diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.h b/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.h index ea9e8a9d2d..7b30d03eb9 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/select-variables.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_SELECT_VARIABLES_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_SELECT_VARIABLES_H__ diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.cpp index b993a65661..845b5aeb51 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "ts-management-aggregated-as-renewables.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.h b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.h index 8784e9979e..18037c933b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-aggregated-as-renewables.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include "ts-management.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.cpp index 9ff8b880f1..7f10d13bbc 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "ts-management-clusters-as-renewables.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.h b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.h index 420ef37910..55ecaa7bdf 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management-clusters-as-renewables.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.cpp b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.cpp index d4a25498ca..e41f805379 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "cell.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.h b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.h index 34570186d2..6a2986d35b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/ts-management.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.cpp b/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.cpp index 49687bdc00..059293aad7 100644 --- a/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "wxgrid-renderer.h" diff --git a/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.h b/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.h index a167876cf2..0cc7e215cc 100644 --- a/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/wxgrid-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_WXGRID_RENDERER_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_WXGRID_RENDERER_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/component.cpp b/src/ui/simulator/toolbox/components/htmllistbox/component.cpp index 560cfed3fb..d922dc254a 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/component.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/component.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "component.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/component.h b/src/ui/simulator/toolbox/components/htmllistbox/component.h index 5239354c99..b09b280310 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/component.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/component.h @@ -1,35 +1,28 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_COMPONENT_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_COMPONENT_H__ #include #include "item/item.h" -#include "sort.h" #include #include "datasource/datasource.h" #include diff --git a/src/ui/simulator/toolbox/components/htmllistbox/component.hxx b/src/ui/simulator/toolbox/components/htmllistbox/component.hxx index 25af2e2608..d1a99f6506 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/component.hxx +++ b/src/ui/simulator/toolbox/components/htmllistbox/component.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_COMPONENT_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_COMPONENT_HXX__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/bindingconstraint.cpp b/src/ui/simulator/toolbox/components/htmllistbox/datasource/bindingconstraint.cpp index c47faacf31..f9e0b95b0f 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/bindingconstraint.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/bindingconstraint.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "bindingconstraint.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.cpp b/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.cpp index c1d0d91676..39a377de07 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "cluster-order.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.h b/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.h index 851c27efe2..8216e548f1 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/cluster-order.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.h b/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.h index 4d642a1a2f..638aeb686f 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_DATASOURCE_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_DATASOURCE_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.hxx b/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.hxx index 92c985243c..e51ab14792 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.hxx +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/datasource.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_DATASOURCE_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_DATASOURCE_HXX__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.cpp b/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.cpp index a79334cc6c..9d49dce517 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../item/group.h" @@ -53,16 +47,13 @@ void GetRenewableClusterMap(Data::Area* area, RenewableClusterMap& l, const wxSt { wxString grp; - const Data::RenewableClusterList::iterator end = area->renewable.list.end(); - for (Data::RenewableClusterList::iterator i = area->renewable.list.begin(); i != end; ++i) + for (auto& cluster : area->renewable.list.all()) { - Data::RenewableCluster* cluster = i->second.get(); - if (search.empty()) { grp = wxStringFromUTF8(cluster->group()); grp.MakeLower(); - l[grp].push_back(cluster); + l[grp].push_back(cluster.get()); } } } diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.h b/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.h index 4134c0e5bf..44be873c71 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/renewable-cluster-order.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.cpp b/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.cpp index 029c0b8a2f..5347965c82 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../item/group.h" @@ -53,16 +47,13 @@ void GetThermalClusterMap(Data::Area* area, ThermalClusterMap& l, const wxString { wxString grp; - const Data::ThermalClusterList::iterator end = area->thermal.list.end(); - for (Data::ThermalClusterList::iterator i = area->thermal.list.begin(); i != end; ++i) + for (auto& cluster : area->thermal.list.all()) { - Data::ThermalCluster* cluster = i->second.get(); - if (search.empty()) { grp = wxStringFromUTF8(cluster->group()); grp.MakeLower(); - l[grp].push_back(cluster); + l[grp].push_back(cluster.get()); } } } diff --git a/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.h b/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.h index 081b718bc4..4008aeabda 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/datasource/thermal-cluster-order.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/area.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/area.cpp index 9b522d9e8d..dc1504efb8 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/area.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/area.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "area.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/area.h b/src/ui/simulator/toolbox/components/htmllistbox/item/area.h index 5db5ad2444..bc9e43759e 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/area.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/area.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_AREA_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_AREA_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/area.hxx b/src/ui/simulator/toolbox/components/htmllistbox/item/area.hxx index 20366b927c..5fbda6b866 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/area.hxx +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/area.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_AREA_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_AREA_HXX__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.cpp index cc4ed95afb..16b8c00723 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "cluster-item.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.h b/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.h index ca231e9295..7a592daaa7 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/cluster-item.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #pragma once diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/error.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/error.cpp index 92654db753..476ff588f9 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/error.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/error.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "error.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/error.h b/src/ui/simulator/toolbox/components/htmllistbox/item/error.h index 9b38db76e0..274431dd28 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/error.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/error.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ERROR_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ERROR_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/group.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/group.cpp index 8f3725f4dc..9785b91e0c 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/group.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/group.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "group.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/group.h b/src/ui/simulator/toolbox/components/htmllistbox/item/group.h index d397e60336..780bd8336e 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/group.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/group.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_GROUP_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_GROUP_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/info.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/info.cpp index f3e6419113..5ae191dab0 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/info.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/info.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "info.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/info.h b/src/ui/simulator/toolbox/components/htmllistbox/item/info.h index 8e21a065c2..c2e244b95b 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/info.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/info.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_INFO_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_INFO_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/item.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/item.cpp index 8597a71131..1a4bc84cec 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/item.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/item.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "item.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/item.h b/src/ui/simulator/toolbox/components/htmllistbox/item/item.h index 30600dd761..092b8e7136 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/item.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/item.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/item.hxx b/src/ui/simulator/toolbox/components/htmllistbox/item/item.hxx index 44106df9af..4c31442430 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/item.hxx +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/item.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_HXX__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.cpp index b867ba86ac..96cef48dcb 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "pathlistitem.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.h b/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.h index b50e825998..a3a91094db 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/pathlistitem.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_PATHLIST_ITEM_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_PATHLIST_ITEM_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.cpp index f6e7d25c39..6352195a5a 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "renewable-cluster-item.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.h b/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.h index b6104f01eb..cb3efd0abb 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/renewable-cluster-item.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_RENEWABLE_CLUSTER_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_RENEWABLE_CLUSTER_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.cpp b/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.cpp index a31880f4f9..ab11f24928 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.cpp +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "thermal-cluster-item.h" diff --git a/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.h b/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.h index 3c03c90c7f..1e5b6aa135 100644 --- a/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.h +++ b/src/ui/simulator/toolbox/components/htmllistbox/item/thermal-cluster-item.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_THERMAL_CLUSTER_H__ #define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_ITEM_THERMAL_CLUSTER_H__ diff --git a/src/ui/simulator/toolbox/components/htmllistbox/sort.h b/src/ui/simulator/toolbox/components/htmllistbox/sort.h deleted file mode 100644 index fe192b2131..0000000000 --- a/src/ui/simulator/toolbox/components/htmllistbox/sort.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_SORT_H__ -#define __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_SORT_H__ - -#include "item/item.h" - -namespace Antares -{ -namespace Component -{ -namespace HTMLListbox -{ -/*! -** \brief A virtual Sorting predicate -*/ -struct ISortPredicate -{ -public: - ISortPredicate() - { - } - virtual ~ISortPredicate() - { - } - - virtual bool operator()(const Item::IItem::Ptr a, const Item::IItem::Ptr b) = 0; -}; - -} // namespace HTMLListbox -} // namespace Component -} // namespace Antares - -#endif // __ANTARES_TOOLBOX_COMPONENT_HTMLLISTBOX_SORT_H__ diff --git a/src/ui/simulator/toolbox/components/mainpanel.cpp b/src/ui/simulator/toolbox/components/mainpanel.cpp index a736040790..1bdbbb42ba 100644 --- a/src/ui/simulator/toolbox/components/mainpanel.cpp +++ b/src/ui/simulator/toolbox/components/mainpanel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "mainpanel.h" @@ -30,7 +24,7 @@ #include #include "../../application/study.h" #include "../../application/main/main.h" -#include "../../config.h" +#include "antares/config/config.h" #include "../../toolbox/resources.h" #include "../../../common/lock.h" @@ -151,13 +145,13 @@ void MainPanel::onDraw(wxPaintEvent&) f.SetWeight(wxFONTWEIGHT_BOLD); dc.SetFont(f); - if (study->header.version != (uint)Data::versionLatest) + if (study->header.version != Data::StudyVersion::latest()) { wxString s; if (StudyHasBeenModified()) s << wxT("(*) "); s << pStudyCaption << wxT(" (v") - << Data::VersionToWStr((Data::Version(study->header.version))) << wxT(")"); + << study->header.version.toString() << wxT(")"); addProperty(dc, name, s, size, posY); } else diff --git a/src/ui/simulator/toolbox/components/mainpanel.h b/src/ui/simulator/toolbox/components/mainpanel.h index 3f69216908..df05c01944 100644 --- a/src/ui/simulator/toolbox/components/mainpanel.h +++ b/src/ui/simulator/toolbox/components/mainpanel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_MAIN_PANEL_H__ #define __ANTARES_TOOLBOX_COMPONENT_MAIN_PANEL_H__ diff --git a/src/ui/simulator/toolbox/components/map/component.cpp b/src/ui/simulator/toolbox/components/map/component.cpp index 253af512c9..93de041cb9 100644 --- a/src/ui/simulator/toolbox/components/map/component.cpp +++ b/src/ui/simulator/toolbox/components/map/component.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "component.h" @@ -109,12 +103,12 @@ Component::Component(wxWindow* parent) : pSelectionPopUpMenu->Connect(Antares::Forms::MenusID::mnIDPopupSelectionHide, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(Component::evtOnSelectionHide), - NULL, + nullptr, this); pSelectionPopUpMenu->Connect(Antares::Forms::MenusID::mnIDPopupSelectionShow, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(Component::evtOnSelectionShow), - NULL, + nullptr, this); mainSizer->Layout(); diff --git a/src/ui/simulator/toolbox/components/map/component.h b/src/ui/simulator/toolbox/components/map/component.h index 5971629f1c..8b13ba7539 100644 --- a/src/ui/simulator/toolbox/components/map/component.h +++ b/src/ui/simulator/toolbox/components/map/component.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_COMPONENT_H__ #define __ANTARES_TOOLBOX_MAP_COMPONENT_H__ diff --git a/src/ui/simulator/toolbox/components/map/control.cpp b/src/ui/simulator/toolbox/components/map/control.cpp index 43aaef53d5..c276b650ac 100644 --- a/src/ui/simulator/toolbox/components/map/control.cpp +++ b/src/ui/simulator/toolbox/components/map/control.cpp @@ -1,31 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include +#include "antares/utils/utils.h" #include "control.h" #include #include @@ -34,6 +29,7 @@ #include "../../resources.h" #include "settings.h" #include "nodes/bindingconstraint.h" +#include #include "controls/addtools.h" #include "component.h" diff --git a/src/ui/simulator/toolbox/components/map/control.h b/src/ui/simulator/toolbox/components/map/control.h index af86d27b7c..766d449b16 100644 --- a/src/ui/simulator/toolbox/components/map/control.h +++ b/src/ui/simulator/toolbox/components/map/control.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_CONTROL_H__ #define __ANTARES_TOOLBOX_MAP_CONTROL_H__ diff --git a/src/ui/simulator/toolbox/components/map/controls/addtools.cpp b/src/ui/simulator/toolbox/components/map/controls/addtools.cpp index 32f8e860e9..0ca3d422c5 100644 --- a/src/ui/simulator/toolbox/components/map/controls/addtools.cpp +++ b/src/ui/simulator/toolbox/components/map/controls/addtools.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "addtools.h" diff --git a/src/ui/simulator/toolbox/components/map/controls/addtools.h b/src/ui/simulator/toolbox/components/map/controls/addtools.h index 9472821490..6017edbf3f 100644 --- a/src/ui/simulator/toolbox/components/map/controls/addtools.h +++ b/src/ui/simulator/toolbox/components/map/controls/addtools.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_CONTROLS_ADD_TOOLS_H__ #define __ANTARES_TOOLBOX_MAP_CONTROLS_ADD_TOOLS_H__ diff --git a/src/ui/simulator/toolbox/components/map/drawingcontext.cpp b/src/ui/simulator/toolbox/components/map/drawingcontext.cpp index 3712e6148a..03bfe77a74 100644 --- a/src/ui/simulator/toolbox/components/map/drawingcontext.cpp +++ b/src/ui/simulator/toolbox/components/map/drawingcontext.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "drawingcontext.h" diff --git a/src/ui/simulator/toolbox/components/map/drawingcontext.h b/src/ui/simulator/toolbox/components/map/drawingcontext.h index 398a930a93..b5a51dd6b4 100644 --- a/src/ui/simulator/toolbox/components/map/drawingcontext.h +++ b/src/ui/simulator/toolbox/components/map/drawingcontext.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_DRAWING_CONTEXT_H__ #define __ANTARES_TOOLBOX_MAP_DRAWING_CONTEXT_H__ diff --git a/src/ui/simulator/toolbox/components/map/infos.cpp b/src/ui/simulator/toolbox/components/map/infos.cpp index 3c68a0ac3c..747615d7dd 100644 --- a/src/ui/simulator/toolbox/components/map/infos.cpp +++ b/src/ui/simulator/toolbox/components/map/infos.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "infos.h" diff --git a/src/ui/simulator/toolbox/components/map/infos.h b/src/ui/simulator/toolbox/components/map/infos.h index d502dd32c0..b784fdf31a 100644 --- a/src/ui/simulator/toolbox/components/map/infos.h +++ b/src/ui/simulator/toolbox/components/map/infos.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_PANEL_INFOS_H__ #define __ANTARES_TOOLBOX_MAP_PANEL_INFOS_H__ diff --git a/src/ui/simulator/toolbox/components/map/manager.cpp b/src/ui/simulator/toolbox/components/map/manager.cpp index 7193fbef99..5809b757a9 100644 --- a/src/ui/simulator/toolbox/components/map/manager.cpp +++ b/src/ui/simulator/toolbox/components/map/manager.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "manager.h" @@ -764,11 +758,8 @@ void Manager::selectFromBoundingBox(const wxPoint& a, const wxPoint& b, const si j->first->selected(true); if (mouseSelectionPlants) { - Data::ThermalClusterList::iterator tend = area->thermal.list.end(); - for (Data::ThermalClusterList::iterator t = area->thermal.list.begin(); - t != tend; - ++t) - clusterlist.push_back(t->second.get()); + for(auto cluster : area->thermal.list.all()) + clusterlist.push_back(cluster.get()); } continue; } diff --git a/src/ui/simulator/toolbox/components/map/manager.h b/src/ui/simulator/toolbox/components/map/manager.h index 3c8ae96791..0129eeb524 100644 --- a/src/ui/simulator/toolbox/components/map/manager.h +++ b/src/ui/simulator/toolbox/components/map/manager.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_CONTAINER_H__ #define __ANTARES_TOOLBOX_MAP_CONTAINER_H__ diff --git a/src/ui/simulator/toolbox/components/map/manager.hxx b/src/ui/simulator/toolbox/components/map/manager.hxx index dfa502d88c..2e25e56980 100644 --- a/src/ui/simulator/toolbox/components/map/manager.hxx +++ b/src/ui/simulator/toolbox/components/map/manager.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_CONTAINER_HXX__ #define __ANTARES_TOOLBOX_MAP_CONTAINER_HXX__ diff --git a/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.cpp b/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.cpp index 05c8851efa..b519eb55cf 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.cpp +++ b/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "bindingconstraint.h" diff --git a/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.h b/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.h index e1d831febe..d2e2de6d3c 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.h +++ b/src/ui/simulator/toolbox/components/map/nodes/bindingconstraint.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_BINDING_CONSTRAINT_H__ #define __ANTARES_TOOLBOX_MAP_BINDING_CONSTRAINT_H__ diff --git a/src/ui/simulator/toolbox/components/map/nodes/connection.cpp b/src/ui/simulator/toolbox/components/map/nodes/connection.cpp index c3c76e658f..778f5e6005 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/connection.cpp +++ b/src/ui/simulator/toolbox/components/map/nodes/connection.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "connection.h" #include "../settings.h" diff --git a/src/ui/simulator/toolbox/components/map/nodes/connection.h b/src/ui/simulator/toolbox/components/map/nodes/connection.h index 31fe996072..ca3435e12c 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/connection.h +++ b/src/ui/simulator/toolbox/components/map/nodes/connection.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_CONNECTION_H__ #define __ANTARES_TOOLBOX_MAP_CONNECTION_H__ diff --git a/src/ui/simulator/toolbox/components/map/nodes/connection.hxx b/src/ui/simulator/toolbox/components/map/nodes/connection.hxx index d670a8a7d3..ab7d518356 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/connection.hxx +++ b/src/ui/simulator/toolbox/components/map/nodes/connection.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_CONNECTION_HXX__ #define __ANTARES_TOOLBOX_MAP_CONNECTION_HXX__ diff --git a/src/ui/simulator/toolbox/components/map/nodes/item.cpp b/src/ui/simulator/toolbox/components/map/nodes/item.cpp index 303289bc3c..cb567af5af 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/item.cpp +++ b/src/ui/simulator/toolbox/components/map/nodes/item.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "item.h" @@ -118,7 +112,7 @@ void Item::internalClearAllLinks() if (pLinks && !pLinks->empty()) { Links* lnks = pLinks; - pLinks = NULL; + pLinks = nullptr; const Links::const_iterator end = lnks->end(); for (Links::const_iterator i = lnks->begin(); i != end; ++i) diff --git a/src/ui/simulator/toolbox/components/map/nodes/item.h b/src/ui/simulator/toolbox/components/map/nodes/item.h index 012ee3dc85..853b92446d 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/item.h +++ b/src/ui/simulator/toolbox/components/map/nodes/item.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_ITEM_H__ #define __ANTARES_TOOLBOX_MAP_ITEM_H__ diff --git a/src/ui/simulator/toolbox/components/map/nodes/node.cpp b/src/ui/simulator/toolbox/components/map/nodes/node.cpp index 70d0cbf9e6..2e3c4109af 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/node.cpp +++ b/src/ui/simulator/toolbox/components/map/nodes/node.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "node.h" diff --git a/src/ui/simulator/toolbox/components/map/nodes/node.h b/src/ui/simulator/toolbox/components/map/nodes/node.h index 2cfb2d50b8..75e6895640 100644 --- a/src/ui/simulator/toolbox/components/map/nodes/node.h +++ b/src/ui/simulator/toolbox/components/map/nodes/node.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_NODE_H__ #define __ANTARES_TOOLBOX_MAP_NODE_H__ diff --git a/src/ui/simulator/toolbox/components/map/settings.cpp b/src/ui/simulator/toolbox/components/map/settings.cpp index 37bd5fb977..50c5d5a0b8 100644 --- a/src/ui/simulator/toolbox/components/map/settings.cpp +++ b/src/ui/simulator/toolbox/components/map/settings.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "settings.h" diff --git a/src/ui/simulator/toolbox/components/map/settings.h b/src/ui/simulator/toolbox/components/map/settings.h index 89539fde7e..3e67558260 100644 --- a/src/ui/simulator/toolbox/components/map/settings.h +++ b/src/ui/simulator/toolbox/components/map/settings.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_SETTINGS_H__ #define __ANTARES_TOOLBOX_MAP_SETTINGS_H__ @@ -31,6 +25,7 @@ #include #include #include +#include namespace Antares { diff --git a/src/ui/simulator/toolbox/components/map/tools/connectioncreator.cpp b/src/ui/simulator/toolbox/components/map/tools/connectioncreator.cpp index 322ea5780f..6f68fa5ed6 100644 --- a/src/ui/simulator/toolbox/components/map/tools/connectioncreator.cpp +++ b/src/ui/simulator/toolbox/components/map/tools/connectioncreator.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "connectioncreator.h" diff --git a/src/ui/simulator/toolbox/components/map/tools/connectioncreator.h b/src/ui/simulator/toolbox/components/map/tools/connectioncreator.h index 67db939c50..aeaebda1e0 100644 --- a/src/ui/simulator/toolbox/components/map/tools/connectioncreator.h +++ b/src/ui/simulator/toolbox/components/map/tools/connectioncreator.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_TOOLS_NEW_CONNECTION_H__ #define __ANTARES_TOOLBOX_MAP_TOOLS_NEW_CONNECTION_H__ diff --git a/src/ui/simulator/toolbox/components/map/tools/remover.cpp b/src/ui/simulator/toolbox/components/map/tools/remover.cpp index da2a340ece..22931adc04 100644 --- a/src/ui/simulator/toolbox/components/map/tools/remover.cpp +++ b/src/ui/simulator/toolbox/components/map/tools/remover.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/map/tools/remover.h b/src/ui/simulator/toolbox/components/map/tools/remover.h index a8469c91b3..af55aa7797 100644 --- a/src/ui/simulator/toolbox/components/map/tools/remover.h +++ b/src/ui/simulator/toolbox/components/map/tools/remover.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_TOOLS_DELETE_H__ #define __ANTARES_TOOLBOX_MAP_TOOLS_DELETE_H__ diff --git a/src/ui/simulator/toolbox/components/map/tools/tool.cpp b/src/ui/simulator/toolbox/components/map/tools/tool.cpp index 5542074ecf..3b244b5869 100644 --- a/src/ui/simulator/toolbox/components/map/tools/tool.cpp +++ b/src/ui/simulator/toolbox/components/map/tools/tool.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "tool.h" @@ -38,7 +32,7 @@ namespace Tool Tool::Tool(Manager& manager, const char* icon) : pManager(manager), pX(0), pY(0), pWidth(20), pHeight(20) { - pIcon = (icon && *icon != '\0') ? Resources::BitmapLoadFromFile(icon) : NULL; + pIcon = (icon && *icon != '\0') ? Resources::BitmapLoadFromFile(icon) : nullptr; } Tool::~Tool() @@ -49,7 +43,7 @@ Tool::~Tool() void Tool::icon(const char* filename) { delete pIcon; - pIcon = (filename && *filename != '\0') ? Resources::BitmapLoadFromFile(filename) : NULL; + pIcon = (filename && *filename != '\0') ? Resources::BitmapLoadFromFile(filename) : nullptr; } void Tool::draw(DrawingContext& dc, const bool mouseDown, const wxPoint&, const wxPoint&) const diff --git a/src/ui/simulator/toolbox/components/map/tools/tool.h b/src/ui/simulator/toolbox/components/map/tools/tool.h index 0e2bb33cde..bad1bf6b72 100644 --- a/src/ui/simulator/toolbox/components/map/tools/tool.h +++ b/src/ui/simulator/toolbox/components/map/tools/tool.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_MAP_TOOLS_TOOL_H__ #define __ANTARES_TOOLBOX_MAP_TOOLS_TOOL_H__ diff --git a/src/ui/simulator/toolbox/components/notebook/mapnotebook.cpp b/src/ui/simulator/toolbox/components/notebook/mapnotebook.cpp index ab7c391e55..f4bee76ce3 100644 --- a/src/ui/simulator/toolbox/components/notebook/mapnotebook.cpp +++ b/src/ui/simulator/toolbox/components/notebook/mapnotebook.cpp @@ -1,30 +1,24 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/antares/antares.h" #include "mapnotebook.h" #include "../../resources.h" #include @@ -104,8 +98,8 @@ bool MapNotebook::remove(Page* page) MapNotebook::MapTabs::MapTabs(wxWindow* parent, Notebook& notebook) : Tabs(parent, notebook), undrawnLeftTabs(0), remainingRightTabs(0), pTabNameCtrl(nullptr) { - Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(MapTabs::onMouseMove), NULL, this); - Connect(GetId(), wxEVT_LEAVE_WINDOW, wxMouseEventHandler(MapTabs::onMouseLeave), NULL, this); + Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(MapTabs::onMouseMove), nullptr, this); + Connect(GetId(), wxEVT_LEAVE_WINDOW, wxMouseEventHandler(MapTabs::onMouseLeave), nullptr, this); // add Page button addPageButton = new tabButton( "images/16x16/white_add_18.png", this, tabButton::btnNone, "images/16x16/grey_add_18.png"); diff --git a/src/ui/simulator/toolbox/components/notebook/mapnotebook.h b/src/ui/simulator/toolbox/components/notebook/mapnotebook.h index 43a56a1b41..95d7befe6d 100644 --- a/src/ui/simulator/toolbox/components/notebook/mapnotebook.h +++ b/src/ui/simulator/toolbox/components/notebook/mapnotebook.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_MAPNOTEBOOK_H__ #define __ANTARES_TOOLBOX_COMPONENT_MAPNOTEBOOK_H__ diff --git a/src/ui/simulator/toolbox/components/notebook/notebook.cpp b/src/ui/simulator/toolbox/components/notebook/notebook.cpp index a70350d5df..bd9c8107e3 100644 --- a/src/ui/simulator/toolbox/components/notebook/notebook.cpp +++ b/src/ui/simulator/toolbox/components/notebook/notebook.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/antares/antares.h" #include "notebook.h" #include #include diff --git a/src/ui/simulator/toolbox/components/notebook/notebook.h b/src/ui/simulator/toolbox/components/notebook/notebook.h index 74deedf38d..a7931c92ef 100644 --- a/src/ui/simulator/toolbox/components/notebook/notebook.h +++ b/src/ui/simulator/toolbox/components/notebook/notebook.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_NOTEBOOK_H__ #define __ANTARES_TOOLBOX_COMPONENT_NOTEBOOK_H__ diff --git a/src/ui/simulator/toolbox/components/notebook/notebook.hxx b/src/ui/simulator/toolbox/components/notebook/notebook.hxx index 632003c641..e04b71c8f7 100644 --- a/src/ui/simulator/toolbox/components/notebook/notebook.hxx +++ b/src/ui/simulator/toolbox/components/notebook/notebook.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENT_NOTEBOOK_HXX__ #define __ANTARES_TOOLBOX_COMPONENT_NOTEBOOK_HXX__ diff --git a/src/ui/simulator/toolbox/components/progressbar.cpp b/src/ui/simulator/toolbox/components/progressbar.cpp index 17ea11ee51..8259335d83 100644 --- a/src/ui/simulator/toolbox/components/progressbar.cpp +++ b/src/ui/simulator/toolbox/components/progressbar.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "progressbar.h" diff --git a/src/ui/simulator/toolbox/components/progressbar.h b/src/ui/simulator/toolbox/components/progressbar.h index fd8be4a1bb..ff911c6102 100644 --- a/src/ui/simulator/toolbox/components/progressbar.h +++ b/src/ui/simulator/toolbox/components/progressbar.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_PROGRESSBAR_H__ #define __ANTARES_TOOLBOX_COMPONENTS_PROGRESSBAR_H__ diff --git a/src/ui/simulator/toolbox/components/refresh.cpp b/src/ui/simulator/toolbox/components/refresh.cpp index 759132493c..34b6aa4ec9 100644 --- a/src/ui/simulator/toolbox/components/refresh.cpp +++ b/src/ui/simulator/toolbox/components/refresh.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "refresh.h" diff --git a/src/ui/simulator/toolbox/components/refresh.h b/src/ui/simulator/toolbox/components/refresh.h index 6f1c1d6050..507a828959 100644 --- a/src/ui/simulator/toolbox/components/refresh.h +++ b/src/ui/simulator/toolbox/components/refresh.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_REFRESH_H__ #define __ANTARES_TOOLBOX_COMPONENTS_REFRESH_H__ diff --git a/src/ui/simulator/toolbox/components/wip-panel.cpp b/src/ui/simulator/toolbox/components/wip-panel.cpp index ad9ae4d1c4..cf6fd3a828 100644 --- a/src/ui/simulator/toolbox/components/wip-panel.cpp +++ b/src/ui/simulator/toolbox/components/wip-panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "wip-panel.h" diff --git a/src/ui/simulator/toolbox/components/wip-panel.h b/src/ui/simulator/toolbox/components/wip-panel.h index a7e31cc360..38787a0f26 100644 --- a/src/ui/simulator/toolbox/components/wip-panel.h +++ b/src/ui/simulator/toolbox/components/wip-panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_WIP_PANEL_WIP_PANEL_H__ #define __ANTARES_TOOLBOX_COMPONENTS_WIP_PANEL_WIP_PANEL_H__ diff --git a/src/ui/simulator/toolbox/components/wizardheader.cpp b/src/ui/simulator/toolbox/components/wizardheader.cpp index a86c574620..9408bd8e29 100644 --- a/src/ui/simulator/toolbox/components/wizardheader.cpp +++ b/src/ui/simulator/toolbox/components/wizardheader.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/components/wizardheader.h b/src/ui/simulator/toolbox/components/wizardheader.h index 97d3ef0ccf..544e0986a5 100644 --- a/src/ui/simulator/toolbox/components/wizardheader.h +++ b/src/ui/simulator/toolbox/components/wizardheader.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_COMPONENTS_H__ #define __ANTARES_TOOLBOX_COMPONENTS_H__ diff --git a/src/ui/simulator/toolbox/create.cpp b/src/ui/simulator/toolbox/create.cpp index 60cac27ef4..5687a5fc37 100644 --- a/src/ui/simulator/toolbox/create.cpp +++ b/src/ui/simulator/toolbox/create.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "create.h" @@ -44,7 +38,7 @@ CustomWxButton::CustomWxButton(wxWindow* parent, const wxString& title) : wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent( wxCommandEventFunction, &CustomWxButton::evtOnUserClick), - NULL, + nullptr, this); } diff --git a/src/ui/simulator/toolbox/create.h b/src/ui/simulator/toolbox/create.h index adb2402d91..627de7b829 100644 --- a/src/ui/simulator/toolbox/create.h +++ b/src/ui/simulator/toolbox/create.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_CREATE_H__ #define __ANTARES_TOOLBOX_CREATE_H__ diff --git a/src/ui/simulator/toolbox/create.hxx b/src/ui/simulator/toolbox/create.hxx index ab77ef933c..521d298cc8 100644 --- a/src/ui/simulator/toolbox/create.hxx +++ b/src/ui/simulator/toolbox/create.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_CREATE_HXX__ #define __ANTARES_TOOLBOX_CREATE_HXX__ diff --git a/src/ui/simulator/toolbox/dispatcher/study.cpp b/src/ui/simulator/toolbox/dispatcher/study.cpp index adf0a65c42..2972295b5a 100644 --- a/src/ui/simulator/toolbox/dispatcher/study.cpp +++ b/src/ui/simulator/toolbox/dispatcher/study.cpp @@ -1,34 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include "study.h" +#include "antares/study/study.h" #include "../../application/study.h" #include "../../application/main/main.h" #include "../../../common/lock.h" +#include "study.h" using namespace Yuni; diff --git a/src/ui/simulator/toolbox/dispatcher/study.h b/src/ui/simulator/toolbox/dispatcher/study.h index 86f788be89..c96fef7d9e 100644 --- a/src/ui/simulator/toolbox/dispatcher/study.h +++ b/src/ui/simulator/toolbox/dispatcher/study.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_DISPATCHER_STUDY_H__ #define __ANTARES_TOOLBOX_DISPATCHER_STUDY_H__ diff --git a/src/ui/simulator/toolbox/execute.h b/src/ui/simulator/toolbox/execute.h index eedc618762..3d7363c595 100644 --- a/src/ui/simulator/toolbox/execute.h +++ b/src/ui/simulator/toolbox/execute.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_EXECUTE_H__ #define __ANTARES_TOOLBOX_EXECUTE_H__ diff --git a/src/ui/simulator/toolbox/execute/execute.cpp b/src/ui/simulator/toolbox/execute/execute.cpp index 1a30f3edd2..2e865385fd 100644 --- a/src/ui/simulator/toolbox/execute/execute.cpp +++ b/src/ui/simulator/toolbox/execute/execute.cpp @@ -1,35 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include #include #include "execute.h" #include "../jobs.h" #include +#include #include #include #include @@ -76,7 +70,7 @@ class JobExecute : public Jobs::Job const wxString pCommand; const wxString pWDirectory; //! Get if the job is - Atomic::Int<32> pRunning; + std::atomic pRunning; //! runtime Informations about the process which will be executed JobProcess* pProcess; //! The original directory diff --git a/src/ui/simulator/toolbox/execute/execute.h b/src/ui/simulator/toolbox/execute/execute.h index 114f4e0242..98265d4b59 100644 --- a/src/ui/simulator/toolbox/execute/execute.h +++ b/src/ui/simulator/toolbox/execute/execute.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_E_EXECUTE_H__ #define __ANTARES_TOOLBOX_E_EXECUTE_H__ diff --git a/src/ui/simulator/toolbox/ext-source/action-panel.cpp b/src/ui/simulator/toolbox/ext-source/action-panel.cpp index d4d4979b1b..3bfb1accbb 100644 --- a/src/ui/simulator/toolbox/ext-source/action-panel.cpp +++ b/src/ui/simulator/toolbox/ext-source/action-panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/ext-source/action-panel.h b/src/ui/simulator/toolbox/ext-source/action-panel.h index 232f055056..7489d45338 100644 --- a/src/ui/simulator/toolbox/ext-source/action-panel.h +++ b/src/ui/simulator/toolbox/ext-source/action-panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_EXT_SOURCE_ACTION_PANEL_H__ #define __ANTARES_TOOLBOX_EXT_SOURCE_ACTION_PANEL_H__ diff --git a/src/ui/simulator/toolbox/ext-source/apply.cpp b/src/ui/simulator/toolbox/ext-source/apply.cpp index 1060e5f342..13ea0c43a0 100644 --- a/src/ui/simulator/toolbox/ext-source/apply.cpp +++ b/src/ui/simulator/toolbox/ext-source/apply.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "apply.h" @@ -46,12 +40,12 @@ void Apply(Antares::Action::Context::Ptr context, if (windowRequired) { - auto* form = new Antares::Window::ApplyActionsDialog(NULL, context, root); + auto* form = new Antares::Window::ApplyActionsDialog(nullptr, context, root); Dispatcher::GUI::ShowModal(form); } else { - auto* form = new Antares::Window::PerformerDialog(NULL, context, root); + auto* form = new Antares::Window::PerformerDialog(nullptr, context, root); Dispatcher::GUI::ShowModal(form); } } diff --git a/src/ui/simulator/toolbox/ext-source/apply.h b/src/ui/simulator/toolbox/ext-source/apply.h index e6b5fd364a..0aff4824b8 100644 --- a/src/ui/simulator/toolbox/ext-source/apply.h +++ b/src/ui/simulator/toolbox/ext-source/apply.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_EXT_SOURCE_APPLY_H__ #define __ANTARES_TOOLBOX_EXT_SOURCE_APPLY_H__ diff --git a/src/ui/simulator/toolbox/ext-source/handler.h b/src/ui/simulator/toolbox/ext-source/handler.h index aff41d80e8..74af31449c 100644 --- a/src/ui/simulator/toolbox/ext-source/handler.h +++ b/src/ui/simulator/toolbox/ext-source/handler.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_EXT_SOURCE_HANDLER_H__ #define __ANTARES_TOOLBOX_EXT_SOURCE_HANDLER_H__ diff --git a/src/ui/simulator/toolbox/ext-source/handler/build-context.cpp b/src/ui/simulator/toolbox/ext-source/handler/build-context.cpp index 20a5bed61f..4eebbad8d8 100644 --- a/src/ui/simulator/toolbox/ext-source/handler/build-context.cpp +++ b/src/ui/simulator/toolbox/ext-source/handler/build-context.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "build-context.h" diff --git a/src/ui/simulator/toolbox/ext-source/handler/build-context.h b/src/ui/simulator/toolbox/ext-source/handler/build-context.h index d3ebebc3e5..3140106f29 100644 --- a/src/ui/simulator/toolbox/ext-source/handler/build-context.h +++ b/src/ui/simulator/toolbox/ext-source/handler/build-context.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_EXT_SOURCE_HANDLER_BUILD_CONTEXT_H__ #define __ANTARES_TOOLBOX_EXT_SOURCE_HANDLER_BUILD_CONTEXT_H__ diff --git a/src/ui/simulator/toolbox/ext-source/handler/com.rte-france.antares.study.cpp b/src/ui/simulator/toolbox/ext-source/handler/com.rte-france.antares.study.cpp index 6b548e514f..831cb2c091 100644 --- a/src/ui/simulator/toolbox/ext-source/handler/com.rte-france.antares.study.cpp +++ b/src/ui/simulator/toolbox/ext-source/handler/com.rte-france.antares.study.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "handler.h" diff --git a/src/ui/simulator/toolbox/ext-source/handler/handler.h b/src/ui/simulator/toolbox/ext-source/handler/handler.h index c652f872c3..fdc27660b7 100644 --- a/src/ui/simulator/toolbox/ext-source/handler/handler.h +++ b/src/ui/simulator/toolbox/ext-source/handler/handler.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_EXT_SOURCE_HANDLER_HANDLER_H__ #define __ANTARES_TOOLBOX_EXT_SOURCE_HANDLER_HANDLER_H__ diff --git a/src/ui/simulator/toolbox/ext-source/performer.cpp b/src/ui/simulator/toolbox/ext-source/performer.cpp index 794aeee637..f1475da293 100644 --- a/src/ui/simulator/toolbox/ext-source/performer.cpp +++ b/src/ui/simulator/toolbox/ext-source/performer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/ext-source/performer.h b/src/ui/simulator/toolbox/ext-source/performer.h index 67b5063c4e..8188014efe 100644 --- a/src/ui/simulator/toolbox/ext-source/performer.h +++ b/src/ui/simulator/toolbox/ext-source/performer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_EXT_SOURCE_PERFORMER_H__ #define __ANTARES_APPLICATION_EXT_SOURCE_PERFORMER_H__ @@ -33,6 +27,8 @@ #include #include #include "../components/progressbar.h" +#include +#include namespace Antares { @@ -98,10 +94,10 @@ class PerformerDialog : public wxDialog wxTimer* pTimer; Yuni::Thread::IThread* pThread; - Yuni::Mutex pMutex; - Yuni::Atomic::Int<> pGUINeedRefresh; - Yuni::Atomic::Int<> pProgression; - Yuni::Atomic::Int<> pProgressionMax; + std::mutex pMutex; + std::atomic pGUINeedRefresh; + std::atomic pProgression; + std::atomic pProgressionMax; }; // class PerformerDialog diff --git a/src/ui/simulator/toolbox/ext-source/window.cpp b/src/ui/simulator/toolbox/ext-source/window.cpp index 4808c0195c..3dd41632ee 100644 --- a/src/ui/simulator/toolbox/ext-source/window.cpp +++ b/src/ui/simulator/toolbox/ext-source/window.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/ext-source/window.h b/src/ui/simulator/toolbox/ext-source/window.h index 66e5aa4c80..3e11a12ceb 100644 --- a/src/ui/simulator/toolbox/ext-source/window.h +++ b/src/ui/simulator/toolbox/ext-source/window.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_EXT_SOURCE_WINDOW_H__ #define __ANTARES_APPLICATION_EXT_SOURCE_WINDOW_H__ diff --git a/src/ui/simulator/toolbox/input/area.cpp b/src/ui/simulator/toolbox/input/area.cpp index ff6e3d3dd3..d364875a81 100644 --- a/src/ui/simulator/toolbox/input/area.cpp +++ b/src/ui/simulator/toolbox/input/area.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -225,10 +219,10 @@ class SpotlightProviderArea final : public Component::Spotlight::IProvider if (0 != (equipment & Data::timeSeriesThermal)) { - if (area->thermal.list.size() > 0) + if (area->thermal.list.allClustersCount() > 0) { CString<32, false> text; - text << area->thermal.list.size(); + text << area->thermal.list.allClustersCount(); const uint8_t R_COLOR = 210; const uint8_t G_COLOR = 217; const uint8_t B_COLOR = 216; @@ -241,10 +235,10 @@ class SpotlightProviderArea final : public Component::Spotlight::IProvider } if (0 != (equipment & Data::timeSeriesRenewable)) { - if (area->renewable.list.size() > 0) + if (area->renewable.list.allClustersCount() > 0) { CString<32, false> text; - text << area->renewable.list.size(); + text << area->renewable.list.allClustersCount(); item->addRightTag(text, 210, 217, 216); } } diff --git a/src/ui/simulator/toolbox/input/area.h b/src/ui/simulator/toolbox/input/area.h index 7e6d4472db..54cf4c0f47 100644 --- a/src/ui/simulator/toolbox/input/area.h +++ b/src/ui/simulator/toolbox/input/area.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_AREA_H__ #define __ANTARES_TOOLBOX_INPUT_AREA_H__ diff --git a/src/ui/simulator/toolbox/input/bindingconstraint.h b/src/ui/simulator/toolbox/input/bindingconstraint.h index b884eb57db..36578a6a31 100644 --- a/src/ui/simulator/toolbox/input/bindingconstraint.h +++ b/src/ui/simulator/toolbox/input/bindingconstraint.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_BINDING_CONSTRAINT_H__ #define __ANTARES_TOOLBOX_INPUT_BINDING_CONSTRAINT_H__ diff --git a/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.cpp b/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.cpp index 56c8b980d1..17cf30d6df 100644 --- a/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.cpp +++ b/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "bindingconstraint.h" diff --git a/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.h b/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.h index 412952da84..67016b5ca7 100644 --- a/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.h +++ b/src/ui/simulator/toolbox/input/bindingconstraint/bindingconstraint.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_BINDING_CONSTRAINT_BINDING_CONSTRAINT_H__ #define __ANTARES_TOOLBOX_INPUT_BINDING_CONSTRAINT_BINDING_CONSTRAINT_H__ diff --git a/src/ui/simulator/toolbox/input/connection.cpp b/src/ui/simulator/toolbox/input/connection.cpp index 4c8b0ccfaa..68e6f39f9f 100644 --- a/src/ui/simulator/toolbox/input/connection.cpp +++ b/src/ui/simulator/toolbox/input/connection.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -118,7 +112,7 @@ void Connections::internalBuildSubControls() sizer->AddSpacer(1); // Layer filter pLayerFilter = new wxComboBox( - this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_READONLY); pLayerFilter->SetFont(wxFont(wxFontInfo().Bold())); pLayerFilter->AppendString("All"); pLayerFilter->SetValue("All"); diff --git a/src/ui/simulator/toolbox/input/connection.h b/src/ui/simulator/toolbox/input/connection.h index e1e2488ede..de6666f99d 100644 --- a/src/ui/simulator/toolbox/input/connection.h +++ b/src/ui/simulator/toolbox/input/connection.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_CONNECTIONS_H__ #define __ANTARES_TOOLBOX_INPUT_CONNECTIONS_H__ diff --git a/src/ui/simulator/toolbox/input/input.h b/src/ui/simulator/toolbox/input/input.h index bc3de0a775..93f57f39e1 100644 --- a/src/ui/simulator/toolbox/input/input.h +++ b/src/ui/simulator/toolbox/input/input.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_H__ #define __ANTARES_TOOLBOX_INPUT_H__ diff --git a/src/ui/simulator/toolbox/input/renewable-cluster.cpp b/src/ui/simulator/toolbox/input/renewable-cluster.cpp index 043ff85e3a..8f9c60b318 100644 --- a/src/ui/simulator/toolbox/input/renewable-cluster.cpp +++ b/src/ui/simulator/toolbox/input/renewable-cluster.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../../application/study.h" @@ -291,8 +285,6 @@ void RenewableCluster::internalDeletePlant(void*) Refresh(); MarkTheStudyAsModified(); updateInnerValues(); - pArea->renewable.list.rebuildIndex(); - pArea->renewable.prepareAreaWideIndexes(); study->uiinfo->reload(); } else @@ -374,7 +366,7 @@ void RenewableCluster::internalAddPlant(void*) // Trying to find an uniq name YString sFl; sFl.clear() << "new cluster"; - while (pArea->renewable.list.find(sFl)) + while (pArea->renewable.list.findInAll(sFl.c_str())) { ++indx; sFl.clear() << "new cluster " << indx; @@ -388,9 +380,7 @@ void RenewableCluster::internalAddPlant(void*) logs.info() << "adding new renewable cluster " << pArea->id << '.' << sFl; cluster->setName(sFl); cluster->reset(); - pArea->renewable.list.add(cluster); - pArea->renewable.list.rebuildIndex(); - pArea->renewable.prepareAreaWideIndexes(); + pArea->renewable.list.addToCompleteList(cluster); // Update the list update(); @@ -411,7 +401,7 @@ void RenewableCluster::internalClonePlant(void*) if (!pArea || !pLastSelectedRenewableCluster) return; - if (!pArea->renewable.list.find(pLastSelectedRenewableCluster->renewableAggregate()->id())) + if (!pArea->renewable.list.findInAll(pLastSelectedRenewableCluster->renewableAggregate()->id())) { // The selected has been obviously invalidated pLastSelectedRenewableCluster = nullptr; @@ -450,7 +440,7 @@ void RenewableCluster::internalClonePlant(void*) YString sFl; sFl << copy << indx; // lowercase - while (pArea->renewable.list.find(sFl)) + while (pArea->renewable.list.findInAll(sFl.c_str())) { ++indx; sFl.clear() << copy << indx; @@ -466,9 +456,7 @@ void RenewableCluster::internalClonePlant(void*) // Reset to default values cluster->copyFrom(selectedPlant); - pArea->renewable.list.add(cluster); - pArea->renewable.list.rebuildIndex(); - pArea->renewable.prepareAreaWideIndexes(); + pArea->renewable.list.addToCompleteList(cluster); // Update the list update(); diff --git a/src/ui/simulator/toolbox/input/renewable-cluster.h b/src/ui/simulator/toolbox/input/renewable-cluster.h index 58d18bc865..cd641d3770 100644 --- a/src/ui/simulator/toolbox/input/renewable-cluster.h +++ b/src/ui/simulator/toolbox/input/renewable-cluster.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_RENEWABLE_CLUSTER_H__ #define __ANTARES_TOOLBOX_INPUT_RENEWABLE_CLUSTER_H__ diff --git a/src/ui/simulator/toolbox/input/thermal-cluster.cpp b/src/ui/simulator/toolbox/input/thermal-cluster.cpp index 0a40b9ee29..8939dc7242 100644 --- a/src/ui/simulator/toolbox/input/thermal-cluster.cpp +++ b/src/ui/simulator/toolbox/input/thermal-cluster.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../../application/study.h" @@ -317,8 +311,6 @@ void ThermalCluster::internalDeletePlant(void*) Refresh(); MarkTheStudyAsModified(); updateInnerValues(); - pArea->thermal.list.rebuildIndex(); - pArea->thermal.prepareAreaWideIndexes(); study->uiinfo->reload(); // delete associated constraints @@ -433,7 +425,7 @@ void ThermalCluster::internalAddPlant(void*) // Trying to find an uniq name YString sFl; sFl.clear() << "new cluster"; - while (pArea->thermal.list.find(sFl)) + while (pArea->thermal.list.findInAll(sFl.c_str())) { ++indx; sFl.clear() << "new cluster " << indx; @@ -447,9 +439,7 @@ void ThermalCluster::internalAddPlant(void*) logs.info() << "adding new thermal cluster " << pArea->id << '.' << sFl; cluster->setName(sFl); cluster->reset(); - pArea->thermal.list.add(cluster); - pArea->thermal.list.rebuildIndex(); - pArea->thermal.prepareAreaWideIndexes(); + pArea->thermal.list.addToCompleteList(cluster); // Update the list update(); @@ -471,7 +461,7 @@ void ThermalCluster::internalClonePlant(void*) if (!pArea || !pLastSelectedThermalCluster) return; - if (!pArea->thermal.list.find(pLastSelectedThermalCluster->thermalAggregate()->id())) + if (!pArea->thermal.list.findInAll(pLastSelectedThermalCluster->thermalAggregate()->id())) { // The selected has been obviously invalidated pLastSelectedThermalCluster = nullptr; @@ -510,7 +500,7 @@ void ThermalCluster::internalClonePlant(void*) YString sFl; sFl << copy << indx; // lowercase - while (pArea->thermal.list.find(sFl)) + while (pArea->thermal.list.findInAll(sFl.c_str())) { ++indx; sFl.clear() << copy << indx; @@ -526,9 +516,7 @@ void ThermalCluster::internalClonePlant(void*) // Reset to default values cluster->copyFrom(selectedPlant); - pArea->thermal.list.add(cluster); - pArea->thermal.list.rebuildIndex(); - pArea->thermal.prepareAreaWideIndexes(); + pArea->thermal.list.addToCompleteList(cluster); // Update the list update(); diff --git a/src/ui/simulator/toolbox/input/thermal-cluster.h b/src/ui/simulator/toolbox/input/thermal-cluster.h index 02a6e37759..3da4a91f1f 100644 --- a/src/ui/simulator/toolbox/input/thermal-cluster.h +++ b/src/ui/simulator/toolbox/input/thermal-cluster.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_INPUT_THERMAL_CLUSTER_H__ #define __ANTARES_TOOLBOX_INPUT_THERMAL_CLUSTER_H__ diff --git a/src/ui/simulator/toolbox/jobs.h b/src/ui/simulator/toolbox/jobs.h index e8bed1a483..10ea75a27b 100644 --- a/src/ui/simulator/toolbox/jobs.h +++ b/src/ui/simulator/toolbox/jobs.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_JOBS_H__ #define __ANTARES_TOOLBOX_JOBS_H__ diff --git a/src/ui/simulator/toolbox/jobs/job.cpp b/src/ui/simulator/toolbox/jobs/job.cpp index 7474a24209..f4c2f4e284 100644 --- a/src/ui/simulator/toolbox/jobs/job.cpp +++ b/src/ui/simulator/toolbox/jobs/job.cpp @@ -1,30 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ +#include #include #include #include @@ -374,7 +369,7 @@ class TimerElapsedTime final : public Yuni::Thread::Timer bool pUseProgression; Job& pJob; wxDateTime pStartTime; - Yuni::Mutex pMutex; + std::mutex pMutex; PartList& pParts; }; // class TimerElapsedTime @@ -480,10 +475,11 @@ class TimerRemainingTime final : public Yuni::Thread::Timer class MessageFlusherTimer final : public wxTimer { public: - MessageFlusherTimer(const wxString& messageBuffer, wxStaticText* label, Yuni::Mutex& mutex) : + MessageFlusherTimer(const wxString& messageBuffer, wxStaticText* label, std::mutex& mutex) : wxTimer(), pMessageBuffer(messageBuffer), pLabel(label), pMutex(mutex) { - assert(pLabel != NULL); + assert(pLabel); + } virtual ~MessageFlusherTimer() @@ -493,7 +489,7 @@ class MessageFlusherTimer final : public wxTimer virtual void Notify() { { - Yuni::MutexLocker locker(pMutex); + std::lock_guard locker(pMutex); // We use .c_str() here to force the copy of the string if (pStrCopy == pMessageBuffer) return; @@ -509,8 +505,7 @@ class MessageFlusherTimer final : public wxTimer wxString pStrCopy; //! GUI label wxStaticText* pLabel; - //! Mutex - Yuni::Mutex& pMutex; + std::mutex& pMutex; }; // class MessageFlusherTimer @@ -519,7 +514,8 @@ class ReadWriteStatsFlusherTimer final : public wxTimer public: ReadWriteStatsFlusherTimer(wxStaticText* label) : wxTimer(), pLabel(label) { - assert(pLabel != NULL); + assert(pLabel); + } virtual ~ReadWriteStatsFlusherTimer() @@ -794,7 +790,7 @@ void Job::displayGauge(const bool visible) } } -void Job::onLogMessage(int level, const String& message) +void Job::onLogMessage(int level, const std::string& message) { if (message.empty() or message[0] == ' ') return; diff --git a/src/ui/simulator/toolbox/jobs/job.h b/src/ui/simulator/toolbox/jobs/job.h index d493158b3f..f329f56b64 100644 --- a/src/ui/simulator/toolbox/jobs/job.h +++ b/src/ui/simulator/toolbox/jobs/job.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_JOB_H__ #define __ANTARES_TOOLBOX_JOB_H__ @@ -43,6 +37,8 @@ #include "../create.h" #include +#include +#include #include namespace Antares @@ -199,7 +195,7 @@ class Job : public wxDialog, public Yuni::IEventObserver void evtOnClose(wxCloseEvent& evt); - void onLogMessage(int, const Yuni::String& message); + void onLogMessage(int, const std::string& message); protected: /*! @@ -262,8 +258,8 @@ class Job : public wxDialog, public Yuni::IEventObserver Yuni::String::ListPtr pWarningList; Yuni::String::ListPtr pErrorList; - Yuni::Atomic::Int<> pJobIsRunning; - Yuni::Atomic::Int<> pGUICanUpdate; + std::atomic pJobIsRunning; + std::atomic pGUICanUpdate; // Event table DECLARE_EVENT_TABLE() @@ -290,8 +286,8 @@ class Job : public wxDialog, public Yuni::IEventObserver wxString pMessage; wxString pSubMessage; - Yuni::Mutex pMutex; - Yuni::Mutex pErrorMutex; + std::mutex pMutex; + std::mutex pErrorMutex; PartList* pPartList; diff --git a/src/ui/simulator/toolbox/locales.cpp b/src/ui/simulator/toolbox/locales.cpp index 978e5d9fa9..5c8947aefe 100644 --- a/src/ui/simulator/toolbox/locales.cpp +++ b/src/ui/simulator/toolbox/locales.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/locales.h b/src/ui/simulator/toolbox/locales.h index 0d52693a53..6f1595ee8c 100644 --- a/src/ui/simulator/toolbox/locales.h +++ b/src/ui/simulator/toolbox/locales.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_LOCALES_H__ #define __ANTARES_LOCALES_H__ diff --git a/src/ui/simulator/toolbox/resources.cpp b/src/ui/simulator/toolbox/resources.cpp index 81e7b4cfd4..1b50cc093c 100644 --- a/src/ui/simulator/toolbox/resources.cpp +++ b/src/ui/simulator/toolbox/resources.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/resources.h b/src/ui/simulator/toolbox/resources.h index 692b1b2d72..70a9d53281 100644 --- a/src/ui/simulator/toolbox/resources.h +++ b/src/ui/simulator/toolbox/resources.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_RESOURCES_H__ #define __ANTARES_TOOLBOX_RESOURCES_H__ diff --git a/src/ui/simulator/toolbox/spotlight/area.cpp b/src/ui/simulator/toolbox/spotlight/area.cpp index f966dd060a..64a7589a31 100644 --- a/src/ui/simulator/toolbox/spotlight/area.cpp +++ b/src/ui/simulator/toolbox/spotlight/area.cpp @@ -1,33 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "area.h" #include -#include "../resources.h" +#include "antares/resources/resources.h" using namespace Yuni; @@ -39,7 +33,7 @@ namespace Spotlight { ItemArea::ItemArea(Data::Area* a) : area(a) { - assert(a != NULL); + assert(a); caption(a->name); group("Area"); diff --git a/src/ui/simulator/toolbox/spotlight/area.h b/src/ui/simulator/toolbox/spotlight/area.h index 3becd438f6..d7eda94053 100644 --- a/src/ui/simulator/toolbox/spotlight/area.h +++ b/src/ui/simulator/toolbox/spotlight/area.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_SPOTLIGHT_AREA_H__ #define __ANTARES_TOOLBOX_SPOTLIGHT_AREA_H__ diff --git a/src/ui/simulator/toolbox/spotlight/constraint.cpp b/src/ui/simulator/toolbox/spotlight/constraint.cpp index c31707d270..de73cb889d 100644 --- a/src/ui/simulator/toolbox/spotlight/constraint.cpp +++ b/src/ui/simulator/toolbox/spotlight/constraint.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "constraint.h" @@ -39,7 +33,7 @@ namespace Spotlight { ItemConstraint::ItemConstraint(Data::BindingConstraint* a) : constraint(a) { - assert(a != NULL); + assert(a); caption(a->name()); group("Constraint"); diff --git a/src/ui/simulator/toolbox/spotlight/constraint.h b/src/ui/simulator/toolbox/spotlight/constraint.h index fe12301d84..39f575bdea 100644 --- a/src/ui/simulator/toolbox/spotlight/constraint.h +++ b/src/ui/simulator/toolbox/spotlight/constraint.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_SPOTLIGHT_CONSTRAINT_H__ #define __ANTARES_TOOLBOX_SPOTLIGHT_CONSTRAINT_H__ diff --git a/src/ui/simulator/toolbox/system/diskfreespace.hxx b/src/ui/simulator/toolbox/system/diskfreespace.hxx index 8c68328ce3..5b5cff8087 100644 --- a/src/ui/simulator/toolbox/system/diskfreespace.hxx +++ b/src/ui/simulator/toolbox/system/diskfreespace.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/toolbox/validator.cpp b/src/ui/simulator/toolbox/validator.cpp index e192369a2c..0765a50541 100644 --- a/src/ui/simulator/toolbox/validator.cpp +++ b/src/ui/simulator/toolbox/validator.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "validator.h" diff --git a/src/ui/simulator/toolbox/validator.h b/src/ui/simulator/toolbox/validator.h index 27c8b76ad2..7e77f799e0 100644 --- a/src/ui/simulator/toolbox/validator.h +++ b/src/ui/simulator/toolbox/validator.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_VALIDATOR_H__ #define __ANTARES_TOOLBOX_VALIDATOR_H__ diff --git a/src/ui/simulator/toolbox/wx-wrapper.h b/src/ui/simulator/toolbox/wx-wrapper.h index 27180806f3..63780f2173 100644 --- a/src/ui/simulator/toolbox/wx-wrapper.h +++ b/src/ui/simulator/toolbox/wx-wrapper.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_TOOLBOX_WX_WRAPPER_H__ #define __ANTARES_TOOLBOX_WX_WRAPPER_H__ diff --git a/src/ui/simulator/windows/about/aboutbox.cpp b/src/ui/simulator/windows/about/aboutbox.cpp index fcdf92d6cd..1cdf5f0331 100644 --- a/src/ui/simulator/windows/about/aboutbox.cpp +++ b/src/ui/simulator/windows/about/aboutbox.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -32,7 +26,7 @@ #include #include "../../toolbox/resources.h" #include "../../toolbox/create.h" -#include "../../../config.h" +#include #include #include @@ -64,7 +58,7 @@ Li Wu V5\n\ Artwork\n\ == == == =\n\ \n\ -Damien Gérard"; +Damien G�rard"; static std::string Thanks = "ATTRIBUTION NOTICES\n\ ===================\n\ @@ -105,740 +99,179 @@ Special thanks are due to a few Authors without whom Antares_Simulator would not const char* AntaresLicense = R"( -Valid-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +Valid-License-Identifier: MPL-2.0 License-Text: - Copyright (C) 2007-2018 RTE -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 . - -In accordance with the terms of section 7 (7. Additional Terms.) of -the GNU GPL v3, the copyright holders of this Program add the -following Additional permissions: - -* If you modify this Program, or any covered work, by linking or -combining it with OpenSSL (or a modified version of that library), -containing parts covered by the terms of the OpenSSL license, the -copyright holders of this Program grant you additional permission to -convey the resulting work. Corresponding Source for a non-source form -of such a combination shall include the source code for the parts of -OpenSSL used as well as that of the covered work. - -* The terms "Sirius_Solver Substitution Exception" may be used to -refer to the permission defined in the next two paragraphs. - -In the following paragraph, the terms "Non-GPL code" mean code that is -covered neither by the GNU GPL v3 nor by a GPL-compatible license. -The terms "Eligible Interface" mean the interface definition files of -the Sirius_Solver library (version 6.0.0 or later). - -If you modify this Program, or any covered work, by linking it with -Non-GPL code through an Eligible Interface, the copyright holders of -this Program grant you additional conditional permission to convey the -resulting work. The condition to which the use of the permission is -subject to is that you replace the three characters between brackets -at the end of this line by the version identifiers of the Sirius_Solver -library whose eligible interface you make use of : [X.Y.Z] - -* As a special exception, the copyright holders of this Program give -you permission to link this software with libYuni library, licensed -under MPL-2.0, to produce an executable without applying the GNU GPL -v3 to the library itself providing that you meet the terms and -conditions of the MPL-2.0 on this library. +Mozilla Public License +Version 2.0 +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. +1.3. "Contribution" + + means Covered Software of a particular Contributor. +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. +1.5. "Incompatible With Secondary Licenses" + + means + + that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or + + that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. +1.8. "License" + + means this document. +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. +1.10. "Modifications" + + means any of the following: + + any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or + + any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants and Conditions +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + + under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and + + under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. )"; const char* AntaresLicense1 = R"( -### 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. +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: + + for any code that a Contributor has removed from Covered Software; or + + for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or + + under Patent Claims infringed by Covered Software in the absence of its Contributions. + +This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). +2.5. Representation + +Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. +2.6. Fair Use + +This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. +3. Responsibilities +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + + such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and + + You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). +3.4. Notices + +You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. )"; const char* AntaresLicense2 = R"( -#### 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. +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. +4. Inability to Comply Due to Statute or Regulation + +If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. +5. Termination + +5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. +6. Disclaimer of Warranty + +Covered Software is provided under this License on an "as is" basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. )"; const char* AntaresLicense3 = R"( -#### 12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under -this License and any other pertinent obligations, then as a -consequence you may not convey it at all. For example, if you agree to -terms that obligate you to collect a royalty for further conveying -from those to whom you convey the Program, the only way you could -satisfy both those terms and this License would be to refrain entirely -from conveying the Program. - -#### 13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - -#### 14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions -of the GNU General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in -detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or -of any later version published by the Free Software Foundation. If the -Program does not specify a version number of the GNU General Public -License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions -of the GNU General Public License can be used, that proxy's public -statement of acceptance of a version permanently authorizes you to -choose that version for the Program. - -Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - -#### 15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT -WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND -PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR -CORRECTION. - -#### 16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR -CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES -ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT -NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR -LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM -TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER -PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -#### 17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - -END OF TERMS AND CONDITIONS - -### How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these -terms. - -To do so, attach the following notices to the program. It is safest to -attach them to the start of each source file to most effectively state -the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper -mail. - -If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands \`show w' and \`show c' should show the -appropriate parts of the General Public License. Of course, your -program's commands might be different; for a GUI interface, you would -use an "about box". - -You should also get your employer (if you work as a programmer) or -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. For more information on this, and how to apply and follow -the GNU GPL, see . - -The GNU General Public License does not permit incorporating your -program into proprietary programs. If your program is a subroutine -library, you may consider it more useful to permit linking proprietary -applications with the library. If this is what you want to do, use the -GNU Lesser General Public License instead of this License. But first, -please read . +7. Limitation of Liability + +Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. +8. Litigation + +Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. +9. Miscellaneous + +This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. +10. Versions of the License +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. +10.3. Modified Versions + +If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + +If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. )"; namespace Antares diff --git a/src/ui/simulator/windows/about/aboutbox.h b/src/ui/simulator/windows/about/aboutbox.h index c92031b69d..4a0477b4e2 100644 --- a/src/ui/simulator/windows/about/aboutbox.h +++ b/src/ui/simulator/windows/about/aboutbox.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_ABOUTBOX_ABOUTBOX_H__ #define __ANTARES_APPLICATION_ABOUTBOX_ABOUTBOX_H__ diff --git a/src/ui/simulator/windows/aboutbox.h b/src/ui/simulator/windows/aboutbox.h index bbc7dd9dd8..04c2cfe031 100644 --- a/src/ui/simulator/windows/aboutbox.h +++ b/src/ui/simulator/windows/aboutbox.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_ABOUTBOX_H__ #define __ANTARES_APPLICATION_ABOUTBOX_H__ diff --git a/src/ui/simulator/windows/analyzer/analyzer.cpp b/src/ui/simulator/windows/analyzer/analyzer.cpp index 42bd55d71c..47d223f2fa 100644 --- a/src/ui/simulator/windows/analyzer/analyzer.cpp +++ b/src/ui/simulator/windows/analyzer/analyzer.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/antares/antares.h" #include "analyzer.h" #include #include @@ -54,7 +48,7 @@ #include #include #include "../../application/study.h" -#include +#include #include using namespace Yuni; @@ -189,7 +183,7 @@ class AnalyzeSourceFolder final : public Yuni::Thread::IThread private: AnalyzerWizard& pForm; - Mutex pDataMutex; + std::mutex pDataMutex; String pFolder; AnalyzerWizard::FileMappingPtr pMapping; @@ -559,7 +553,7 @@ AnalyzerWizard::AnalyzerWizard(wxFrame* parent) : pAnalyzeSource(nullptr), pCheckRelationship(nullptr), pFileSearch(nullptr), - pTSSelected(Data::timeSeriesCount), // invalid in our case + pTSSelected(Data::timeSeriesLoad), // invalid in our case pUpdating(false) { pRefreshTimer = new AnalyzeTimer(*this); diff --git a/src/ui/simulator/windows/analyzer/analyzer.h b/src/ui/simulator/windows/analyzer/analyzer.h index f85252a8c0..96d903a3b9 100644 --- a/src/ui/simulator/windows/analyzer/analyzer.h +++ b/src/ui/simulator/windows/analyzer/analyzer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_ANALYZER_H__ #define __ANTARES_APPLICATION_WINDOW_ANALYZER_H__ diff --git a/src/ui/simulator/windows/analyzer/analyzer.hxx b/src/ui/simulator/windows/analyzer/analyzer.hxx index d80dc0d85e..9acdad27bc 100644 --- a/src/ui/simulator/windows/analyzer/analyzer.hxx +++ b/src/ui/simulator/windows/analyzer/analyzer.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_ANALYZER_HXX__ #define __ANTARES_APPLICATION_WINDOW_ANALYZER_HXX__ diff --git a/src/ui/simulator/windows/bindingconstraint/bindingconstraint.cpp b/src/ui/simulator/windows/bindingconstraint/bindingconstraint.cpp index 7c9e766d60..830634356d 100644 --- a/src/ui/simulator/windows/bindingconstraint/bindingconstraint.cpp +++ b/src/ui/simulator/windows/bindingconstraint/bindingconstraint.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "bindingconstraint.h" diff --git a/src/ui/simulator/windows/bindingconstraint/bindingconstraint.h b/src/ui/simulator/windows/bindingconstraint/bindingconstraint.h index 33d3263328..75b3c1912a 100644 --- a/src/ui/simulator/windows/bindingconstraint/bindingconstraint.h +++ b/src/ui/simulator/windows/bindingconstraint/bindingconstraint.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_BINDING_CONSTRAINT_H__ #define __ANTARES_APPLICATION_WINDOW_BINDING_CONSTRAINT_H__ diff --git a/src/ui/simulator/windows/bindingconstraint/edit.cpp b/src/ui/simulator/windows/bindingconstraint/edit.cpp index 42b1e30d84..d6676de936 100644 --- a/src/ui/simulator/windows/bindingconstraint/edit.cpp +++ b/src/ui/simulator/windows/bindingconstraint/edit.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "edit.h" @@ -273,7 +267,7 @@ void BindingConstraintInfoEditor::onSave(void*) if (pConstraint) { - if (not newname.empty() and pConstraint->name() != newname) + if (not newname.empty() and pConstraint->name() != Data::ConstraintName(newname)) { if (not study.bindingConstraints.rename(pConstraint, newname)) { diff --git a/src/ui/simulator/windows/bindingconstraint/edit.h b/src/ui/simulator/windows/bindingconstraint/edit.h index c0b41ede5d..b1680dbdda 100644 --- a/src/ui/simulator/windows/bindingconstraint/edit.h +++ b/src/ui/simulator/windows/bindingconstraint/edit.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_BINDING_CONSTRAINT_EDIT_H__ #define __ANTARES_APPLICATION_WINDOW_BINDING_CONSTRAINT_EDIT_H__ diff --git a/src/ui/simulator/windows/calendar/calendar.cpp b/src/ui/simulator/windows/calendar/calendar.cpp index a98473d72c..552e54d171 100644 --- a/src/ui/simulator/windows/calendar/calendar.cpp +++ b/src/ui/simulator/windows/calendar/calendar.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -32,7 +26,7 @@ #include #include "../../toolbox/resources.h" #include "../../toolbox/create.h" -#include "../../../config.h" +#include #include "../../application/menus.h" #include diff --git a/src/ui/simulator/windows/calendar/calendar.h b/src/ui/simulator/windows/calendar/calendar.h index 4eb9e1c3f0..e460104a7d 100644 --- a/src/ui/simulator/windows/calendar/calendar.h +++ b/src/ui/simulator/windows/calendar/calendar.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_CALENDAR_CALENDAR_H__ #define __ANTARES_APPLICATION_WINDOWS_CALENDAR_CALENDAR_H__ diff --git a/src/ui/simulator/windows/calendar/view-standard.hxx b/src/ui/simulator/windows/calendar/view-standard.hxx index 9e4ba08fe8..6fcac664c5 100644 --- a/src/ui/simulator/windows/calendar/view-standard.hxx +++ b/src/ui/simulator/windows/calendar/view-standard.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/windows/cleaner.cpp b/src/ui/simulator/windows/cleaner.cpp deleted file mode 100644 index 39dec36887..0000000000 --- a/src/ui/simulator/windows/cleaner.cpp +++ /dev/null @@ -1,411 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ - -#include "cleaner.h" -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "../toolbox/components/htmllistbox/item/info.h" -#include "../toolbox/components/htmllistbox/item/pathlistitem.h" -#include "../toolbox/components/wizardheader.h" -#include "../toolbox/create.h" -#include "../application/main.h" -#include "../application/wait.h" -#include - -using namespace Yuni; - -namespace Antares -{ -namespace Window -{ -class CleaningThread final : public Yuni::Thread::IThread -{ -public: - CleaningThread(StudyCleaner* parent) : pParent(parent) - { - } - - virtual ~CleaningThread() - { - // Removing references to this instance - { - Yuni::MutexLocker locker(pParent->pMutex); - if (pParent->pInfos) - pParent->pInfos->onProgress.unbind(); - } - stop(); - } - -protected: - virtual bool onStarting() override - { - // Cleaning - Yuni::MutexLocker locker(pParent->pMutex); - if (pParent->pInfos) - { - pParent->pInfos->onProgress.bind(this, &CleaningThread::onProgress); - delete pParent->pInfos; - pParent->pInfos = nullptr; - } - return true; - } - - virtual bool onExecute() override - { - // Folder - String stdFolder; - pParent->pMutex.lock(); - wxStringToString(pParent->pFolder, stdFolder); - - if (not stdFolder.empty() and IO::Directory::Exists(stdFolder)) - { - logs.callback.clear(); - pParent->pInfos = new Data::StudyCleaningInfos(stdFolder.c_str()); - pParent->pInfos->onProgress.bind(this, &CleaningThread::onProgress); - pParent->pMutex.unlock(); - - pParent->pInfos->analyze(); - Forms::ApplWnd::Instance()->connectLogCallback(); - } - else - pParent->pMutex.unlock(); - - return false; - } - - virtual void onStop() - { - Bind callback; - callback.bind(pParent, &StudyCleaner::updateGUI, true); - Dispatcher::GUI::Post(callback); - } - - bool onProgress(uint count) - { - pParent->progress(count); - return !(shouldAbort()); - } - -private: - StudyCleaner* pParent; -}; - -class CleaningInfoRefreshTimer final : public wxTimer -{ -public: - CleaningInfoRefreshTimer(StudyCleaner* parent) : pParent(parent) - { - // Do Nothing - } - - virtual ~CleaningInfoRefreshTimer() - { - // Do nothing - } - - virtual void Notify() override - { - pParent->updateProgressionLabel(); - } - -private: - StudyCleaner* pParent; -}; - -StudyCleaner::StudyCleaner(wxFrame* parent) : - wxDialog(parent, - wxID_ANY, - wxT("Cleaner"), - wxDefaultPosition, - wxDefaultSize, - wxCLOSE_BOX | wxCAPTION | wxCLIP_CHILDREN), - pInfos(nullptr), - pRefreshTimer(nullptr), - pThread(nullptr) -{ - wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL); - - // Header - mainSizer->Add( - Toolbox::Components::WizardHeader::Create( - this, - wxT("Study folder cleaner"), - "images/32x32/cleaner.png", - wxT("Remove all files and folders that are no longer needed in a study folder")), - 0, - wxALL | wxEXPAND); - - wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); - mainSizer->Add(sizer, 1, wxALL | wxEXPAND); - - pListbox = new Component::HTMLListbox::Component(this); - sizer->AddSpacer(15); - sizer->Add(pListbox, 1, wxALL | wxEXPAND); - sizer->AddSpacer(15); - - // Buttons - wxBoxSizer* pnlBtns = new wxBoxSizer(wxHORIZONTAL); - pnlBtns->AddSpacer(15); - - // Refresh - pBtnRefresh = Component::CreateButton(this, wxT("Refresh"), this, &StudyCleaner::onRefresh); - pnlBtns->Add(pBtnRefresh); - pnlBtns->AddSpacer(15); - - pLblInfos = new wxStaticText(this, wxID_ANY, wxString()); - pnlBtns->Add(pLblInfos, 0, wxALL | wxALIGN_CENTER_VERTICAL); - pnlBtns->AddStretchSpacer(); - - // Cancel - pBtnCancel = Component::CreateButton(this, wxT("Cancel"), this, &StudyCleaner::onCancel); - pnlBtns->Add(pBtnCancel); - pnlBtns->AddSpacer(5); - pBtnGo = Component::CreateButton( - this, wxT("Perform a disk cleanup"), this, &StudyCleaner::onProceed); - pnlBtns->Add(pBtnGo, 0, wxALL | wxEXPAND); - pnlBtns->AddSpacer(15); - - // Button Panel - if (System::unix) - mainSizer->Add(new wxStaticLine(this, wxID_ANY), 0, wxALL | wxEXPAND, 8); - else - mainSizer->AddSpacer(8); - - mainSizer->Add(pnlBtns, 0, wxALL | wxEXPAND); - mainSizer->AddSpacer(8); - - // Set the sizer - sizer->Layout(); - SetSizer(mainSizer); - - GetSizer()->Fit(this); - wxSize p = GetSize(); - p.SetWidth(p.GetWidth() + 20); - if (p.GetHeight() < 430) - p.SetHeight(430); - if (p.GetWidth() < 750) - p.SetWidth(750); - SetSize(p); - Centre(wxBOTH); - - pRefreshTimer = new CleaningInfoRefreshTimer(this); -} - -StudyCleaner::~StudyCleaner() -{ - delete pRefreshTimer; - if (pThread) - { - pThread->stop(); - delete pThread; - } - - delete pInfos; -} - -void StudyCleaner::studyFolder(const wxString& folder) -{ - if (pRefreshTimer) - pRefreshTimer->Stop(); - - if (not pThread) - pThread = new CleaningThread(this); - else - pThread->stop(); - - // Reset internal variables - { - Yuni::MutexLocker locker(pMutex); - if (&pFolder != &folder) // avoid possible undefined behavior - pFolder = folder; - pProgressionCount = 0; - } - - // We are working ! - pListbox->clear(); - *(pListbox) - += std::make_shared(wxT("Gathering informations...")); - pLblInfos->SetLabel(wxT("Gathering informations...")); - GetSizer()->Show(pBtnGo, false, true); - GetSizer()->Show(pBtnRefresh, false, true); - pBtnGo->Enable(true); - GetSizer()->Layout(); - Refresh(); - - if (pRefreshTimer) - pRefreshTimer->Start(300 /*ms*/, wxTIMER_CONTINUOUS); - pThread->start(); -} - -void StudyCleaner::onRefresh(void*) -{ - // Refresh - studyFolder(pFolder); -} - -void StudyCleaner::onCancel(void*) -{ - Enable(false); - if (pBtnRefresh) - pBtnRefresh->Enable(false); - if (pBtnCancel) - pBtnCancel->Enable(false); - if (pBtnGo) - pBtnGo->Enable(false); - Refresh(); - if (pThread) - pThread->gracefulStop(); - - Dispatcher::GUI::Post(this, &StudyCleaner::closeMe); -} - -void StudyCleaner::closeMe() -{ - if (pRefreshTimer) - pRefreshTimer->Stop(); - if (pThread) - pThread->stop(); - Dispatcher::GUI::Close(this); -} - -void StudyCleaner::onProceed(void*) -{ - WIP::Locker wip; - pLblInfos->SetLabel(wxT("Performing a cleanup...")); - GetSizer()->Show(pBtnGo, false, true); - GetSizer()->Show(pBtnRefresh, false, true); - GetSizer()->Layout(); - Refresh(); - - // Performing the cleanup - Dispatcher::GUI::Post(this, &StudyCleaner::launchCleanup); -} - -void StudyCleaner::launchCleanup() -{ - // Performing the cleanup - if (pInfos) - pInfos->performCleanup(); - studyFolder(pFolder); -} - -void StudyCleaner::updateProgressionLabel() -{ - if (not pLblInfos) - return; - - pMutex.lock(); - uint p = pProgressionCount; - pMutex.unlock(); - - switch (p) - { - case 0: - break; - case 1: - pLblInfos->SetLabel(wxT("1 folder has been analyzed...")); - break; - default: - pLblInfos->SetLabel(wxString() << p << wxT(" folders have been analyzed...")); - } -} - -void StudyCleaner::updateGUI(bool hasItems) -{ - if (pRefreshTimer) - pRefreshTimer->Stop(); - - pMutex.lock(); - - bool hasAtLeastOneItem = false; - - pListbox->clear(); - if (hasItems and pInfos and !pInfos->intruders.empty()) - { - const PathList::const_iterator end = pInfos->intruders.end(); - for (PathList::const_iterator i = pInfos->intruders.begin(); i != end; ++i) - { - *(pListbox) - += std::make_shared(i->first, i->second); - hasAtLeastOneItem = true; - } - pBtnGo->Enable(true); - } - else - { - *(pListbox) - += std::make_shared(wxT("The folder is clean.")); - pBtnGo->Enable(false); - } - - if (hasAtLeastOneItem and pInfos) - { - const double totalSize = (double)(pInfos->totalSize()) / 1024. / 1024.; - pLblInfos->SetLabel(wxString::Format( - wxT("Total size : %.1f Mb (%u files)"), totalSize, pInfos->intruders.size())); - - GetSizer()->Layout(); - pLblInfos->Refresh(); - } - else - pLblInfos->SetLabel(wxEmptyString); - - if (pThread) - { - pMutex.unlock(); - pThread->stop(1000); - pMutex.lock(); - - delete pThread; - pThread = nullptr; - } - - GetSizer()->Show(pBtnCancel, true, true); - GetSizer()->Show(pBtnGo, true, true); - GetSizer()->Show(pBtnRefresh, true, true); - GetSizer()->Layout(); - pListbox->Refresh(); - - pMutex.unlock(); -} - -void StudyCleaner::progress(uint count) -{ - Yuni::MutexLocker locker(pMutex); - pProgressionCount = count; -} - -} // namespace Window -} // namespace Antares diff --git a/src/ui/simulator/windows/cleaner.h b/src/ui/simulator/windows/cleaner.h deleted file mode 100644 index 7f7b1a419e..0000000000 --- a/src/ui/simulator/windows/cleaner.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator 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. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator 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 Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions -*/ -#ifndef __ANTARES_APPLICATION_WINDOW_CLEANER_H__ -#define __ANTARES_APPLICATION_WINDOW_CLEANER_H__ - -#include -#include -#include -#include -#include "../toolbox/components/htmllistbox/component.h" -#include -#include -#include - -namespace Antares -{ -namespace Window -{ -// Forward declaration -class CleaningThread; - -class StudyCleaner final : public wxDialog -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor, with a parent frame - */ - StudyCleaner(wxFrame* parent); - //! Destructor - virtual ~StudyCleaner(); - //@} - - //! \name Folder - //@{ - //! Set the study folder - void studyFolder(const wxString& folder); - //! Get the study folder - const wxString& studyFolder() const - { - return pFolder; - } - //@} - - //! \name Progression - //@{ - void progress(uint count); - void updateProgressionLabel(); - //@} - -private: - void onRefresh(void*); - void onCancel(void*); - void onProceed(void*); - void updateGUI(bool hasItems); - void launchCleanup(); - void closeMe(); - -private: - //! The study folder - wxString pFolder; - //! Listbox - Component::HTMLListbox::Component* pListbox; - //! - Data::StudyCleaningInfos* pInfos; - //! - wxStaticText* pLblInfos; - wxButton* pBtnRefresh; - wxButton* pBtnCancel; - wxButton* pBtnGo; - - wxTimer* pRefreshTimer; - Yuni::Thread::IThread* pThread; - Yuni::Mutex pMutex; - uint pProgressionCount; - - friend class CleaningThread; - -}; // class StudyCleaner - -} // namespace Window -} // namespace Antares - -#endif // __ANTARES_APPLICATION_WINDOW_CLEANER_H__ diff --git a/src/ui/simulator/windows/connection.cpp b/src/ui/simulator/windows/connection.cpp index b2058c57c8..269ab1d5bf 100644 --- a/src/ui/simulator/windows/connection.cpp +++ b/src/ui/simulator/windows/connection.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "connection.h" diff --git a/src/ui/simulator/windows/connection.h b/src/ui/simulator/windows/connection.h index 5948d61f65..e12887d758 100644 --- a/src/ui/simulator/windows/connection.h +++ b/src/ui/simulator/windows/connection.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_INTERCONNECTIONS_H__ #define __ANTARES_APPLICATION_WINDOW_INTERCONNECTIONS_H__ diff --git a/src/ui/simulator/windows/constraints-builder/constraintsbuilder.cpp b/src/ui/simulator/windows/constraints-builder/constraintsbuilder.cpp index f8cd2a3028..017c9b869c 100644 --- a/src/ui/simulator/windows/constraints-builder/constraintsbuilder.cpp +++ b/src/ui/simulator/windows/constraints-builder/constraintsbuilder.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/antares/antares.h" #include "constraintsbuilder.h" #include #include @@ -59,7 +53,7 @@ #include #include #include "../../application/study.h" -#include +#include #include #include "../../application/main.h" @@ -343,7 +337,7 @@ ConstraintsBuilderWizard::ConstraintsBuilderWizard(wxFrame* parent) : sLinks->AddSpacer(6); // Constraint builder object - pCBuilder = new CBuilder(GetCurrentStudy()); + pCBuilder = new CBuilder(*GetCurrentStudy()); pCBuilder->completeFromStudy(); pCBuilder->completeCBuilderFromFile(); pIncludeLoopFlow->SetValue(pCBuilder->getLoopFlowInclusion()); diff --git a/src/ui/simulator/windows/constraints-builder/constraintsbuilder.h b/src/ui/simulator/windows/constraints-builder/constraintsbuilder.h index bba1a9b408..8c32251e04 100644 --- a/src/ui/simulator/windows/constraints-builder/constraintsbuilder.h +++ b/src/ui/simulator/windows/constraints-builder/constraintsbuilder.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_CONSTRAINTSBUILDER_H__ #define __ANTARES_APPLICATION_WINDOW_CONSTRAINTSBUILDER_H__ @@ -34,7 +28,7 @@ #include #include "../../toolbox/components/datagrid/component.h" #include "../../toolbox/components/datagrid/renderer/constraintsbuilder/links.h" -#include "../../../../solver/constraints-builder/cbuilder.h" +#include "antares/solver/constraints-builder/cbuilder.h" #include #include #include diff --git a/src/ui/simulator/windows/correlation/correlation.cpp b/src/ui/simulator/windows/correlation/correlation.cpp index 03787f9eb9..762479f64e 100644 --- a/src/ui/simulator/windows/correlation/correlation.cpp +++ b/src/ui/simulator/windows/correlation/correlation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "correlation.h" @@ -309,7 +303,7 @@ void CorrelationPanel::assignMatrices(Data::Correlation* corr) { if (pData) { - if (corr == NULL) + if (!corr) { for (uint i = 0; i < 12 + 1; ++i) { diff --git a/src/ui/simulator/windows/correlation/correlation.h b/src/ui/simulator/windows/correlation/correlation.h index aeef6636d8..2f7c8f70fd 100644 --- a/src/ui/simulator/windows/correlation/correlation.h +++ b/src/ui/simulator/windows/correlation/correlation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_CORRELATION_CORRELATION_H__ #define __ANTARES_WINDOWS_CORRELATION_CORRELATION_H__ diff --git a/src/ui/simulator/windows/correlation/datasources.hxx b/src/ui/simulator/windows/correlation/datasources.hxx index aedafb6d17..92cbcc8013 100644 --- a/src/ui/simulator/windows/correlation/datasources.hxx +++ b/src/ui/simulator/windows/correlation/datasources.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "../../toolbox/components/datagrid/component.h" @@ -182,7 +176,7 @@ public: { int lastLevel = 0; int j = 0; - Yuni::CString<15, false> old; + Yuni::CString<12, false> old; wxColour color; wxColour colorIdentity; const Data::Area::Vector::const_iterator end = pArray.end(); diff --git a/src/ui/simulator/windows/exportmap.cpp b/src/ui/simulator/windows/exportmap.cpp index 4492b29cdc..6d843c45c7 100644 --- a/src/ui/simulator/windows/exportmap.cpp +++ b/src/ui/simulator/windows/exportmap.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "exportmap.h" diff --git a/src/ui/simulator/windows/exportmap.h b/src/ui/simulator/windows/exportmap.h index 36a5418687..c5854f1828 100644 --- a/src/ui/simulator/windows/exportmap.h +++ b/src/ui/simulator/windows/exportmap.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_EXPORTMAP_H__ #define __ANTARES_APPLICATION_WINDOWS_EXPORTMAP_H__ diff --git a/src/ui/simulator/windows/exportmap.hxx b/src/ui/simulator/windows/exportmap.hxx index a79d0ca881..c16d0018d1 100644 --- a/src/ui/simulator/windows/exportmap.hxx +++ b/src/ui/simulator/windows/exportmap.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_EXPORTMAP_HXX__ #define __ANTARES_APPLICATION_WINDOWS_EXPORTMAP_HXX__ diff --git a/src/ui/simulator/windows/hydro/allocation.cpp b/src/ui/simulator/windows/hydro/allocation.cpp index 4926c3ac1f..cc490d54e1 100644 --- a/src/ui/simulator/windows/hydro/allocation.cpp +++ b/src/ui/simulator/windows/hydro/allocation.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "allocation.h" diff --git a/src/ui/simulator/windows/hydro/allocation.h b/src/ui/simulator/windows/hydro/allocation.h index 8715cc55c0..53e1a3f5e2 100644 --- a/src/ui/simulator/windows/hydro/allocation.h +++ b/src/ui/simulator/windows/hydro/allocation.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_HYDRO_ALLOCATION_H__ #define __ANTARES_APPLICATION_WINDOWS_HYDRO_ALLOCATION_H__ diff --git a/src/ui/simulator/windows/hydro/dailypower.cpp b/src/ui/simulator/windows/hydro/dailypower.cpp index 8a99499e05..3d9a28f29e 100644 --- a/src/ui/simulator/windows/hydro/dailypower.cpp +++ b/src/ui/simulator/windows/hydro/dailypower.cpp @@ -1,40 +1,31 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "dailypower.h" -#include #include "../../toolbox/components/datagrid/renderer/area/hydroprepro.h" #include "../../toolbox/components/datagrid/renderer/area/inflowpattern.h" #include "../../toolbox/components/datagrid/renderer/area/hydromonthlypower.h" #include "../../toolbox/components/datagrid/renderer/area/creditmodulations.h" -#include "../../toolbox/components/button.h" #include "../../toolbox/validator.h" #include "../../toolbox/create.h" -#include "../../application/menus.h" #include using namespace Yuni; @@ -73,14 +64,6 @@ void Dailypower::createComponents() wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); pSupport->SetSizer(sizer); - const wxSize ourDefaultSize(55, wxDefaultSize.GetHeight()); - - enum - { - right = wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, - left = wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, - }; - wxBoxSizer* sizerHigh = new wxBoxSizer(wxHORIZONTAL); sizer->Add(sizerHigh, 2, wxALL | wxEXPAND | wxFIXED_MINSIZE); @@ -96,16 +79,30 @@ void Dailypower::createComponents() wxBoxSizer* ssGridsLow = new wxBoxSizer(wxHORIZONTAL); - ssGridsLow->Add( - new Component::Datagrid::Component( - pSupport, - new Component::Datagrid::Renderer::HydroMonthlyPower(this, pInputAreaSelector), - wxT("Standard Credits (calendar)")), - 3, - wxALL | wxEXPAND, - 5); + ssGridsLow->Add(new Component::Datagrid::Component( + pSupport, + new Component::Datagrid::Renderer::HydroMonthlyHours( + this, + pInputAreaSelector, + Component::Datagrid::Renderer::HydroMonthlyHours::HoursType::Generation), + wxT("Standard Credits Calendar (Maximum Generation)")), + 3, + wxALL | wxEXPAND, + 5); + sizer->Add(ssGridsLow, 4, wxALL | wxEXPAND | wxFIXED_MINSIZE); + ssGridsLow->Add(new Component::Datagrid::Component( + pSupport, + new Component::Datagrid::Renderer::HydroMonthlyHours( + this, + pInputAreaSelector, + Component::Datagrid::Renderer::HydroMonthlyHours::HoursType::Pumping), + wxT("Standard Credits Calendar (Maximum Pumping)")), + 3, + wxALL | wxEXPAND, + 5); + sizer->Layout(); } diff --git a/src/ui/simulator/windows/hydro/dailypower.h b/src/ui/simulator/windows/hydro/dailypower.h index 4be3f0296b..696a62ebe6 100644 --- a/src/ui/simulator/windows/hydro/dailypower.h +++ b/src/ui/simulator/windows/hydro/dailypower.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_HYDROOW_HYDRO_DAILYPOWER_H__ #define __ANTARES_APPLICATION_HYDROOW_HYDRO_DAILYPOWER_H__ diff --git a/src/ui/simulator/windows/hydro/levelsandvalues.cpp b/src/ui/simulator/windows/hydro/levelsandvalues.cpp index 0711cfec36..13bac231fb 100644 --- a/src/ui/simulator/windows/hydro/levelsandvalues.cpp +++ b/src/ui/simulator/windows/hydro/levelsandvalues.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "levelsandvalues.h" diff --git a/src/ui/simulator/windows/hydro/levelsandvalues.h b/src/ui/simulator/windows/hydro/levelsandvalues.h index 178350b8e4..4c13e6fca9 100644 --- a/src/ui/simulator/windows/hydro/levelsandvalues.h +++ b/src/ui/simulator/windows/hydro/levelsandvalues.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_HYDROOW_HYDRO_LEVELSANDVALUES_H__ #define __ANTARES_APPLICATION_HYDROOW_HYDRO_LEVELSANDVALUES_H__ diff --git a/src/ui/simulator/windows/hydro/localdatahydro.cpp b/src/ui/simulator/windows/hydro/localdatahydro.cpp index 58d65e570b..3891a056c1 100644 --- a/src/ui/simulator/windows/hydro/localdatahydro.cpp +++ b/src/ui/simulator/windows/hydro/localdatahydro.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "localdatahydro.h" @@ -30,18 +24,12 @@ #include "dailypower.h" #include "levelsandvalues.h" #include "management.h" -#include "../../toolbox/components/notebook/notebook.h" -#include "../../toolbox/components/datagrid/component.h" #include "../../toolbox/components/datagrid/renderer/area/timeseries.h" #include "../../toolbox/components/datagrid/renderer/area/hydromonthlypower.h" using namespace Yuni; -namespace Antares -{ -namespace Window -{ -namespace Hydro +namespace Antares::Window::Hydro { Localdatahydro::Localdatahydro(wxWindow* parent, Toolbox::InputSelector::Area* notifier) : Component::Panel(parent), pNotifier(notifier), pLastArea(nullptr) @@ -97,6 +85,6 @@ void Localdatahydro::onStudyLoaded() pPageFatal->select(); } -} // namespace Hydro -} // namespace Window -} // namespace Antares +} // namespace Antares::Window::Hydro + + diff --git a/src/ui/simulator/windows/hydro/localdatahydro.h b/src/ui/simulator/windows/hydro/localdatahydro.h index 2f76d79409..4c248e8291 100644 --- a/src/ui/simulator/windows/hydro/localdatahydro.h +++ b/src/ui/simulator/windows/hydro/localdatahydro.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_HYDRO_LOCALDATAHYDRO_H__ #define __ANTARES_APPLICATION_WINDOWS_HYDRO_LOCALDATAHYDRO_H__ diff --git a/src/ui/simulator/windows/hydro/management.cpp b/src/ui/simulator/windows/hydro/management.cpp index c76bfc6d05..7822f58544 100644 --- a/src/ui/simulator/windows/hydro/management.cpp +++ b/src/ui/simulator/windows/hydro/management.cpp @@ -1,48 +1,37 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "management.h" -#include +#include +#include + #include "../../toolbox/components/datagrid/renderer/area/hydroprepro.h" #include "../../toolbox/components/datagrid/renderer/area/inflowpattern.h" -#include "../../toolbox/components/datagrid/renderer/area/hydromonthlypower.h" -#include "../../toolbox/components/button.h" #include "../../toolbox/validator.h" #include "../../toolbox/create.h" #include "../../application/menus.h" -#include using namespace Yuni; -namespace Antares -{ -namespace Window -{ -namespace Hydro +namespace Antares::Window::Hydro { Management::Management(wxWindow* parent, Toolbox::InputSelector::Area* notifier) : wxScrolledWindow(parent), pInputAreaSelector(notifier) @@ -69,11 +58,8 @@ void Management::createComponents() const wxSize ourDefaultSize(55, wxDefaultSize.GetHeight()); - enum - { - right = wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, - left = wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, - }; + const auto right = (wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + const auto left = (wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); auto* pGrid = new wxFlexGridSizer(6, 0, 8); sizer->Add(pGrid, 0, wxALL, 15); @@ -970,7 +956,7 @@ void Management::onToggleInitializeReservoirLevelDate(Component::Button&, wxMenu for (int i = 0; i < 12; i++) { - it = Menu::CreateItem(&menu, i, Antares::Date::MonthToString(i, 0), NULL, wxEmptyString); + it = Menu::CreateItem(&menu, i, Antares::Date::MonthToString(i, 0), nullptr, wxEmptyString); menu.Connect(it->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(Management::onChangingInitializeReservoirLevelDate), @@ -1161,6 +1147,6 @@ void Management::onChangingInitializeReservoirLevelDate(wxCommandEvent& evt) } } -} // namespace Hydro -} // namespace Window -} // namespace Antares +} // namespace Antares::Window::Hydro + + diff --git a/src/ui/simulator/windows/hydro/management.h b/src/ui/simulator/windows/hydro/management.h index 711790338e..6acf2536c8 100644 --- a/src/ui/simulator/windows/hydro/management.h +++ b/src/ui/simulator/windows/hydro/management.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_HYDROOW_HYDRO_MANAGEMENT_H__ #define __ANTARES_APPLICATION_HYDROOW_HYDRO_MANAGEMENT_H__ diff --git a/src/ui/simulator/windows/hydro/prepro.cpp b/src/ui/simulator/windows/hydro/prepro.cpp index c19e84b277..1139246cb3 100644 --- a/src/ui/simulator/windows/hydro/prepro.cpp +++ b/src/ui/simulator/windows/hydro/prepro.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "prepro.h" diff --git a/src/ui/simulator/windows/hydro/prepro.h b/src/ui/simulator/windows/hydro/prepro.h index be1965cc0c..210cbff268 100644 --- a/src/ui/simulator/windows/hydro/prepro.h +++ b/src/ui/simulator/windows/hydro/prepro.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_HYDROOW_HYDRO_PREPRO_H__ #define __ANTARES_APPLICATION_HYDROOW_HYDRO_PREPRO_H__ diff --git a/src/ui/simulator/windows/hydro/series.cpp b/src/ui/simulator/windows/hydro/series.cpp index 36be9a658c..e6291f63d2 100644 --- a/src/ui/simulator/windows/hydro/series.cpp +++ b/src/ui/simulator/windows/hydro/series.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "series.h" @@ -57,6 +51,14 @@ Series::Series(wxWindow* parent, Toolbox::InputSelector::Area* notifier) : com->renderer(new Component::Datagrid::Renderer::TimeSeriesHydroMinGen(com, notifier)); pPageFatal = notebook->add(com, wxT("Minimum Generation")); + com = new Component::Datagrid::Component(notebook); + com->renderer(new Component::Datagrid::Renderer::TimeSeriesHydroMaxHourlyGenPower(com, notifier)); + pPageFatal = notebook->add(com, wxT("Maximum Generation")); + + com = new Component::Datagrid::Component(notebook); + com->renderer(new Component::Datagrid::Renderer::TimeSeriesHydroMaxHourlyPumpPower(com, notifier)); + pPageFatal = notebook->add(com, wxT("Maximum Pumping")); + // Connection to the notifier if (pNotifier) pNotifier->onAreaChanged.connect(this, &Series::onAreaChanged); diff --git a/src/ui/simulator/windows/hydro/series.h b/src/ui/simulator/windows/hydro/series.h index f6de6209a6..1d612a2c15 100644 --- a/src/ui/simulator/windows/hydro/series.h +++ b/src/ui/simulator/windows/hydro/series.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_HYDRO_PREPRO_H__ #define __ANTARES_APPLICATION_WINDOWS_HYDRO_PREPRO_H__ diff --git a/src/ui/simulator/windows/inspector.h b/src/ui/simulator/windows/inspector.h index 6b19c25a7c..4123337563 100644 --- a/src/ui/simulator/windows/inspector.h +++ b/src/ui/simulator/windows/inspector.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_H__ #define __ANTARES_WINDOWS_INSPECTOR_H__ diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index 53ea80a8b2..778d0fe2ce 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef ANTARES_WINDOWS_INSPECTOR_ACCUMULATOR_HXX__ #define ANTARES_WINDOWS_INSPECTOR_ACCUMULATOR_HXX__ @@ -187,25 +181,24 @@ struct PAreaColor } }; -struct PStudyMode +struct PSimulationMode { - using Type = Data::StudyMode; + using Type = Data::SimulationMode; static Type Value(const Data::Study::Ptr& study) { - return (!(!study) ? study->parameters.mode : Data::stdmEconomy); + return (!(!study) ? study->parameters.mode : Data::SimulationMode::Economy); } static wxString ConvertToString(const Type v) { switch (v) { - case Data::stdmEconomy: + case Data::SimulationMode::Economy: return wxT("Economy"); - case Data::stdmAdequacy: + case Data::SimulationMode::Adequacy: return wxT("Adequacy"); - case Data::stdmExpansion: + case Data::SimulationMode::Expansion: return wxT("Expansion"); - case Data::stdmUnknown: - case Data::stdmMax: + case Data::SimulationMode::Unknown: return wxEmptyString; } return wxEmptyString; @@ -1055,7 +1048,7 @@ struct PClusterLawForced } static wxString ConvertToString(const Type v) { - return (v < thermalLawCount) ? thermalLaws[v] : nullptr; + return (v < LawCount) ? Laws[v] : nullptr; } }; @@ -1068,7 +1061,7 @@ struct PClusterLawPlanned } static wxString ConvertToString(const Type v) { - return (v < thermalLawCount) ? thermalLaws[v] : nullptr; + return (v < LawCount) ? Laws[v] : nullptr; } }; diff --git a/src/ui/simulator/windows/inspector/constants.cpp b/src/ui/simulator/windows/inspector/constants.cpp index 67aebf6bd5..95e05b83b5 100644 --- a/src/ui/simulator/windows/inspector/constants.cpp +++ b/src/ui/simulator/windows/inspector/constants.cpp @@ -1,4 +1,23 @@ -#include +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "constants.h" namespace Antares @@ -216,8 +235,8 @@ const unsigned int renewableTSModeCount = 2; const wxChar* const renewableTSMode[] = {wxT("power generation"), wxT("production factor"), nullptr}; -const unsigned int thermalLawCount = 2; -const wxChar* const thermalLaws[] = {wxT("uniform"), wxT("geometric"), nullptr}; +const unsigned int LawCount = 2; +const wxChar* const Laws[] = {wxT("uniform"), wxT("geometric"), nullptr}; const unsigned int costgenerationCount = 2; const wxChar* const costgeneration[] = {wxT("Set manually"), wxT("Use cost timeseries"), nullptr}; @@ -267,7 +286,7 @@ const wxChar* const calendarWeeks[] = {wxT("MON - SUN"), wxT("SUN - SAT"), nullptr}; -const wxChar* const studyMode[] = {wxT("Economy"), +const wxChar* const simulationMode[] = {wxT("Economy"), wxT("Adequacy"), #if STUDY_MODE_EXPANSION wxT("Expansion"), diff --git a/src/ui/simulator/windows/inspector/constants.h b/src/ui/simulator/windows/inspector/constants.h index 34b7c238bf..90b996098f 100644 --- a/src/ui/simulator/windows/inspector/constants.h +++ b/src/ui/simulator/windows/inspector/constants.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include @@ -16,8 +36,8 @@ extern const unsigned int arrayClusterGroupCount; extern const wxChar* const arrayClusterGroup[]; // Thermal laws -extern const unsigned int thermalLawCount; -extern const wxChar* const thermalLaws[]; +extern const unsigned int LawCount; +extern const wxChar* const Laws[]; // Thermal cost generation extern const unsigned int costgenerationCount; @@ -44,7 +64,7 @@ extern const wxChar* const playlist[]; extern const wxChar* const geographicTrimming[]; extern const wxChar* const thematicTrimming[]; -extern const wxChar* const studyMode[]; +extern const wxChar* const simulationMode[]; extern const wxChar* const adequacyPatchMode[]; } // namespace Inspector } // namespace Window diff --git a/src/ui/simulator/windows/inspector/data.cpp b/src/ui/simulator/windows/inspector/data.cpp index e9ee00ca0e..dad1119b35 100644 --- a/src/ui/simulator/windows/inspector/data.cpp +++ b/src/ui/simulator/windows/inspector/data.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "data.h" diff --git a/src/ui/simulator/windows/inspector/data.h b/src/ui/simulator/windows/inspector/data.h index 6a553854fd..43c55b4768 100644 --- a/src/ui/simulator/windows/inspector/data.h +++ b/src/ui/simulator/windows/inspector/data.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_DATA_H__ #define __ANTARES_WINDOWS_INSPECTOR_DATA_H__ diff --git a/src/ui/simulator/windows/inspector/data.hxx b/src/ui/simulator/windows/inspector/data.hxx index 37c8b90019..fe57d26f76 100644 --- a/src/ui/simulator/windows/inspector/data.hxx +++ b/src/ui/simulator/windows/inspector/data.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_DATA_HXX__ #define __ANTARES_WINDOWS_INSPECTOR_DATA_HXX__ diff --git a/src/ui/simulator/windows/inspector/editor-calendar.cpp b/src/ui/simulator/windows/inspector/editor-calendar.cpp index bfafa13512..d042c74f7f 100644 --- a/src/ui/simulator/windows/inspector/editor-calendar.cpp +++ b/src/ui/simulator/windows/inspector/editor-calendar.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "editor-calendar.h" diff --git a/src/ui/simulator/windows/inspector/editor-calendar.h b/src/ui/simulator/windows/inspector/editor-calendar.h index 4ceda21560..bb29feded1 100644 --- a/src/ui/simulator/windows/inspector/editor-calendar.h +++ b/src/ui/simulator/windows/inspector/editor-calendar.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_EDITOR_STUDY_CALENDAR_H__ #define __ANTARES_WINDOWS_INSPECTOR_EDITOR_STUDY_CALENDAR_H__ diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 22b9ad28c9..da6e46946a 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -1,45 +1,35 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "frame.h" +#include "constants.h" #include "../../application/main.h" #include -#include -#include +#include #include -#include #include "../../application/study.h" #include "editor-calendar.h" -#include "../../toolbox/resources.h" #include "../../toolbox/components/map/component.h" #include "../../toolbox/components/mainpanel.h" -#include "../../toolbox/components/button.h" -#include #include "grid.h" using namespace Yuni; @@ -178,9 +168,8 @@ void Frame::onSelectAllPlants(wxCommandEvent&) for (auto i = data->areas.begin(); i != areaEnd; ++i) { Data::Area& area = *(*i); - auto end = area.thermal.list.end(); - for (auto i = area.thermal.list.begin(); i != end; ++i) - data->ThClusters.insert(i->second.get()); + for (auto c : area.thermal.list.all()) + data->ThClusters.insert(c.get()); } data->areas.clear(); data->links.clear(); @@ -204,26 +193,6 @@ void Frame::onSelectPlant(wxCommandEvent& evt) } } -// gp : never used - to be removed -void Frame::onSelectAllPlantsFromArea(wxCommandEvent& evt) -{ - InspectorData::Ptr data = gData; - if (!(!data) and gInspector and evt.GetEventObject()) - { - Data::Area* area = (Data::Area*)mapIDPointer[evt.GetId()]; - if (!area) - return; - data->ThClusters.clear(); - auto end = area->thermal.list.end(); - for (auto i = area->thermal.list.begin(); i != end; ++i) - data->ThClusters.insert(i->second.get()); - data->areas.clear(); - data->links.clear(); - data->empty = data->ThClusters.empty(); - gInspector->delayApplyGlobalSelection(); - } -} - Frame::Frame(wxWindow* parent, bool allowAnyObject) : Antares::Component::Panel(parent), pNotes(nullptr), @@ -340,7 +309,7 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : // --- STUDIES --- pPGStudyTitle = Group(pg, wxT("GENERAL PARAMETERS"), wxT("study.title")); pPGStudyGrpSimulation = Category(pg, wxT("Simulation"), wxT("study.context")); - pPGStudyMode = P_ENUM("Mode", "study.mode", studyMode); + pPGSimulationMode = P_ENUM("Mode", "study.mode", simulationMode); pPGStudyCalendarBegin = P_UINT("First day", "study.cal.begin"); pPGStudyCalendarEnd = P_UINT("Last day", "study.cal.end"); pg->SetPropertyEditor(pPGStudyCalendarBegin, wxPG_EDITOR(StudyCalendarBtnEditor)); @@ -541,8 +510,8 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGThClusterDoGenerateTS = P_ENUM("Generate timeseries", "cluster.gen-ts", localGenTS); pPGThClusterVolatilityForced = P_FLOAT("Volatility (forced)", "cluster.forcedVolatility"); pPGThClusterVolatilityPlanned = P_FLOAT("Volatility (planned)", "cluster.plannedVolatility"); - pPGThClusterLawForced = P_ENUM("Law (forced)", "cluster.forcedlaw", thermalLaws); - pPGThClusterLawPlanned = P_ENUM("Law (planned)", "cluster.plannedlaw", thermalLaws); + pPGThClusterLawForced = P_ENUM("Law (forced)", "cluster.forcedlaw", Laws); + pPGThClusterLawPlanned = P_ENUM("Law (planned)", "cluster.plannedlaw", Laws); // --- RENEWABLE CLUSTERS --- pPGRnClusterSeparator = Group(pg, wxEmptyString, wxEmptyString); @@ -743,7 +712,7 @@ void Frame::apply(const InspectorData::Ptr& data) if (!hide) { // Context - Accumulator::Apply(pPGStudyMode, data->studies); + Accumulator::Apply(pPGSimulationMode, data->studies); Accumulator::Apply(pPGStudyHorizon, data->studies); Accumulator::Apply(pPGStudyCalendarMonth, data->studies); Accumulator::Apply(pPGStudyCalendarWeek, data->studies); @@ -804,7 +773,7 @@ void Frame::apply(const InspectorData::Ptr& data) { const Data::Area& area = *(*i); nbLinks += (uint)area.links.size(); - nbThermalClusters += area.thermal.list.size(); + nbThermalClusters += area.thermal.list.allClustersCount(); } pPGAreaLinks->SetValueFromInt(nbLinks); pPGAreaPlants->SetValueFromInt(nbThermalClusters); diff --git a/src/ui/simulator/windows/inspector/frame.h b/src/ui/simulator/windows/inspector/frame.h index 2d49c0bd8e..05ad7395fc 100644 --- a/src/ui/simulator/windows/inspector/frame.h +++ b/src/ui/simulator/windows/inspector/frame.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_FRAME_H__ #define __ANTARES_WINDOWS_INSPECTOR_FRAME_H__ @@ -100,7 +94,6 @@ class Frame final : public Antares::Component::Panel, public Yuni::IEventObserve void onSelectAllPlants(wxCommandEvent& evt); void onSelectPlant(wxCommandEvent& evt); - void onSelectAllPlantsFromArea(wxCommandEvent& evt); void clearAssociatinsBetweenIDAndPtr() { @@ -149,7 +142,7 @@ class Frame final : public Antares::Component::Panel, public Yuni::IEventObserve wxPGProperty* pPGStudyGrpCalendar; wxPGProperty* pPGStudyMCScenarios; wxPGProperty* pPGStudyOutputProfile; - wxPGProperty* pPGStudyMode; + wxPGProperty* pPGSimulationMode; wxPGProperty* pPGStudyYears; wxPGProperty* pPGStudyCalendarBegin; wxPGProperty* pPGStudyCalendarEnd; diff --git a/src/ui/simulator/windows/inspector/grid.cpp b/src/ui/simulator/windows/inspector/grid.cpp index 89697db827..b8ddbade7f 100644 --- a/src/ui/simulator/windows/inspector/grid.cpp +++ b/src/ui/simulator/windows/inspector/grid.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "grid.h" diff --git a/src/ui/simulator/windows/inspector/grid.h b/src/ui/simulator/windows/inspector/grid.h index 653d9f9869..6c5bffdd7d 100644 --- a/src/ui/simulator/windows/inspector/grid.h +++ b/src/ui/simulator/windows/inspector/grid.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_GRID_H__ #define __ANTARES_WINDOWS_INSPECTOR_GRID_H__ diff --git a/src/ui/simulator/windows/inspector/inspector.cpp b/src/ui/simulator/windows/inspector/inspector.cpp index d895d26f1c..61007baf94 100644 --- a/src/ui/simulator/windows/inspector/inspector.cpp +++ b/src/ui/simulator/windows/inspector/inspector.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include @@ -704,7 +698,7 @@ bool isConstraintSelected(const Yuni::String& constraintName) for (auto i = gData->constraints.begin(); i != end; ++i) { auto constraint = *i; - if (constraint->name() == constraintName) + if (constraint->name().equals(constraintName)) { return true; } diff --git a/src/ui/simulator/windows/inspector/inspector.h b/src/ui/simulator/windows/inspector/inspector.h index df8c2ac790..bffed579ef 100644 --- a/src/ui/simulator/windows/inspector/inspector.h +++ b/src/ui/simulator/windows/inspector/inspector.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_INSPECTOR_INSPECTOR_H__ #define __ANTARES_WINDOWS_INSPECTOR_INSPECTOR_H__ diff --git a/src/ui/simulator/windows/inspector/property.cluster.update.cpp b/src/ui/simulator/windows/inspector/property.cluster.update.cpp index 3c5b8680e4..2e483f9b09 100644 --- a/src/ui/simulator/windows/inspector/property.cluster.update.cpp +++ b/src/ui/simulator/windows/inspector/property.cluster.update.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "property.cluster.update.h" #include #include @@ -80,7 +100,7 @@ bool ClusterUpdater::changeGroup(const wxVariant& value) using SetType = std::set; SetType set; - for (auto cluster : clusters) + for (auto& cluster : clusters) { if (cluster->group() != name) { @@ -102,7 +122,7 @@ bool ClusterUpdater::changeUnit(const wxVariant& value) { using unitT = decltype(Antares::Data::ThermalCluster::unitCount); const auto nbUnits = static_cast(value.GetLong()); - for (auto cluster : clusters) + for (auto& cluster : clusters) cluster->unitCount = nbUnits; // refresh the installed capacity @@ -119,13 +139,13 @@ bool ClusterUpdater::changeNominalCapacity(const wxVariant& value) double d = value.GetDouble(); if (d < 0.) { - for (auto cluster : clusters) + for (auto& cluster : clusters) cluster->nominalCapacity = 0.; pFrame.delayApply(); } else { - for (auto cluster : clusters) + for (auto& cluster : clusters) cluster->nominalCapacity = d; } @@ -141,7 +161,7 @@ bool ClusterUpdater::changeNominalCapacity(const wxVariant& value) bool ClusterUpdater::changeEnabled(const wxVariant& value) { const bool d = value.GetBool(); - for (auto cluster : clusters) + for (auto& cluster : clusters) cluster->enabled = d; // Notify OnCommonSettingsChanged(); diff --git a/src/ui/simulator/windows/inspector/property.cluster.update.h b/src/ui/simulator/windows/inspector/property.cluster.update.h index e5ec5ce672..e1b276f08a 100644 --- a/src/ui/simulator/windows/inspector/property.cluster.update.h +++ b/src/ui/simulator/windows/inspector/property.cluster.update.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include "data.h" diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 4ae3778c54..1c1879dfae 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "grid.h" @@ -42,6 +36,7 @@ #include #include #include +#include #include "../message.h" #include "../../application/main/internal-ids.h" #include "property.cluster.update.h" @@ -803,7 +798,7 @@ bool InspectorGrid::onPropertyChanging_ThermalCluster(wxPGProperty*, (*i)->marginalCost = d; (*i)->ComputeCostTimeSeries(); // update } - + pFrame.delayApply(); // Notify OnStudyThermalClusterCommonSettingsChanged(); @@ -982,15 +977,15 @@ bool InspectorGrid::onPropertyChanging_ThermalCluster(wxPGProperty*, if (name == "cluster.forcedlaw") { long index = value.GetLong(); - Data::ThermalLaw law = Data::thermalLawUniform; + Data::StatisticalLaw law = Data::LawUniform; switch (index) { case 0: - law = Data::thermalLawUniform; + law = Data::LawUniform; break; case 1: - law = Data::thermalLawGeometric; + law = Data::LawGeometric; break; default: return false; @@ -1003,15 +998,15 @@ bool InspectorGrid::onPropertyChanging_ThermalCluster(wxPGProperty*, if (name == "cluster.plannedlaw") { long index = value.GetLong(); - Data::ThermalLaw law = Data::thermalLawUniform; + Data::StatisticalLaw law = Data::LawUniform; switch (index) { case 0: - law = Data::thermalLawUniform; + law = Data::LawUniform; break; case 1: - law = Data::thermalLawGeometric; + law = Data::LawGeometric; break; default: return false; @@ -1185,13 +1180,13 @@ bool InspectorGrid::onPropertyChanging_S(wxPGProperty*, wxStringToString(value.GetString(), s); s.toLower(); - Data::StudyMode mode = Data::stdmUnknown; + Data::SimulationMode mode = Data::SimulationMode::Unknown; if (s == "economy" || s == "0") - mode = Data::stdmEconomy; + mode = Data::SimulationMode::Economy; else if (s == "adequacy" || s == "1") - mode = Data::stdmAdequacy; + mode = Data::SimulationMode::Adequacy; else - mode = Data::stdmEconomy; + mode = Data::SimulationMode::Economy; for (; i != end; ++i) { diff --git a/src/ui/simulator/windows/link-property-buttons.cpp b/src/ui/simulator/windows/link-property-buttons.cpp index eb04c0eb29..6390b7c516 100644 --- a/src/ui/simulator/windows/link-property-buttons.cpp +++ b/src/ui/simulator/windows/link-property-buttons.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include diff --git a/src/ui/simulator/windows/link-property-buttons.h b/src/ui/simulator/windows/link-property-buttons.h index 87c167567b..d88f6af23e 100644 --- a/src/ui/simulator/windows/link-property-buttons.h +++ b/src/ui/simulator/windows/link-property-buttons.h @@ -1,10 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #pragma once #include #include #include "yuni/core/event/interfaces.h" #include "../toolbox/components/button.h" -#include "libs/antares/study/area/links.h" +#include "antares/study/area/links.h" namespace Antares { diff --git a/src/ui/simulator/windows/memorystatistics.h b/src/ui/simulator/windows/memorystatistics.h index 2541b1e35d..36b84d6e35 100644 --- a/src/ui/simulator/windows/memorystatistics.h +++ b/src/ui/simulator/windows/memorystatistics.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MEMORY_STATISTICS_H__ #define __ANTARES_APPLICATION_MEMORY_STATISTICS_H__ diff --git a/src/ui/simulator/windows/memorystatistics/memorystatistics.cpp b/src/ui/simulator/windows/memorystatistics/memorystatistics.cpp index cf77689f15..b42d93489a 100644 --- a/src/ui/simulator/windows/memorystatistics/memorystatistics.cpp +++ b/src/ui/simulator/windows/memorystatistics/memorystatistics.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/windows/memorystatistics/memorystatistics.h b/src/ui/simulator/windows/memorystatistics/memorystatistics.h index b4915d8ff8..11eff50fdb 100644 --- a/src/ui/simulator/windows/memorystatistics/memorystatistics.h +++ b/src/ui/simulator/windows/memorystatistics/memorystatistics.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MEMORYSTATISTICS_MEMORYSTATISTICS_H__ #define __ANTARES_APPLICATION_MEMORYSTATISTICS_MEMORYSTATISTICS_H__ diff --git a/src/ui/simulator/windows/memorystatistics/private.h b/src/ui/simulator/windows/memorystatistics/private.h index 1971a26b98..998d82d08e 100644 --- a/src/ui/simulator/windows/memorystatistics/private.h +++ b/src/ui/simulator/windows/memorystatistics/private.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MEMORYSTATISTICS_PRIVATE_H__ #define __ANTARES_APPLICATION_MEMORYSTATISTICS_PRIVATE_H__ diff --git a/src/ui/simulator/windows/message.cpp b/src/ui/simulator/windows/message.cpp index 2b3b065d2f..a3f8ce495e 100644 --- a/src/ui/simulator/windows/message.cpp +++ b/src/ui/simulator/windows/message.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/windows/message.h b/src/ui/simulator/windows/message.h index 3ca130bc55..acc568dcb8 100644 --- a/src/ui/simulator/windows/message.h +++ b/src/ui/simulator/windows/message.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MESSAGE_H__ #define __ANTARES_APPLICATION_MESSAGE_H__ diff --git a/src/ui/simulator/windows/message.hxx b/src/ui/simulator/windows/message.hxx index 3675f1357d..dd44aaf6f3 100644 --- a/src/ui/simulator/windows/message.hxx +++ b/src/ui/simulator/windows/message.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_MESSAGE_HXX__ #define __ANTARES_APPLICATION_MESSAGE_HXX__ diff --git a/src/ui/simulator/windows/notes.cpp b/src/ui/simulator/windows/notes.cpp index 5273971e87..1cb7ce05b1 100644 --- a/src/ui/simulator/windows/notes.cpp +++ b/src/ui/simulator/windows/notes.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "notes.h" diff --git a/src/ui/simulator/windows/notes.h b/src/ui/simulator/windows/notes.h index 2b2a44966f..49300e58c0 100644 --- a/src/ui/simulator/windows/notes.h +++ b/src/ui/simulator/windows/notes.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_NOTES_H__ #define __ANTARES_APPLICATION_WINDOWS_NOTES_H__ diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp index b9af7956ae..a149ef2984 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "adequacy-patch-areas.h" @@ -30,7 +24,7 @@ #include #include -#include +#include #include "../../../toolbox/resources.h" #include "../../../application/study.h" #include "../../../application/main.h" diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h index 5ca9e2c160..2dcde07f28 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp index 090b837699..2368e68d13 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "adequacy-patch-options.h" @@ -68,7 +62,7 @@ static void updateButton(Component::Button* button, bool value, std::string_view type = (buttonType == "pto") ? 'P' : 'S'; } - assert(button != NULL); + assert(button); if (value) { switch (type) diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h index 5a0d1c3c45..37bdd49e99 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ #define __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ diff --git a/src/ui/simulator/windows/options/advanced/advanced.cpp b/src/ui/simulator/windows/options/advanced/advanced.cpp index 3b925d47ef..fa21ca6895 100644 --- a/src/ui/simulator/windows/options/advanced/advanced.cpp +++ b/src/ui/simulator/windows/options/advanced/advanced.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "advanced.h" @@ -162,14 +156,12 @@ AdvancedParameters::AdvancedParameters(wxWindow* parent) : // Initial reservoir levels { label = Component::CreateLabel(this, wxT("Initial reservoir levels")); - button = new Component::Button(this, wxT("cold start"), "images/16x16/tag.png"); + button = new Component::Button(this, wxT(""), "images/16x16/tag.png"); button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, &AdvancedParameters::onInitialReservoirLevels); button->onPopupMenu(onPopup); + button->caption("hydro hot start deprecated"); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnInitialReservoirLevels = button; } // Hydro heuristic policy { @@ -291,7 +283,7 @@ AdvancedParameters::AdvancedParameters(wxWindow* parent) : // refresh Connect( - GetId(), wxEVT_MOTION, wxMouseEventHandler(AdvancedParameters::onInternalMotion), NULL, this); + GetId(), wxEVT_MOTION, wxMouseEventHandler(AdvancedParameters::onInternalMotion), nullptr, this); refresh(); SetSizer(sizer); @@ -333,12 +325,11 @@ void AdvancedParameters::onResetToDefault(void*) parameters.timeSeriesAccuracyOnCorrelation &= ~Data::timeSeriesWind; parameters.timeSeriesAccuracyOnCorrelation &= ~Data::timeSeriesSolar; - parameters.initialReservoirLevels.iniLevels = Data::irlColdStart; parameters.hydroHeuristicPolicy.hhPolicy = Data::hhpAccommodateRuleCurves; parameters.hydroPricing.hpMode = Data::hpHeuristic; parameters.power.fluctuations = Data::lssFreeModulations; parameters.shedding.policy = Data::shpShavePeaks; - parameters.unitCommitment.ucMode = Data::ucHeuristic; + parameters.unitCommitment.ucMode = Data::ucHeuristicFast; parameters.nbCores.ncMode = Data::ncAvg; parameters.renewableGeneration.rgModelling = Data::rgAggregated; @@ -381,10 +372,6 @@ void AdvancedParameters::refresh() wxString text; - text = wxStringFromUTF8( - InitialReservoirLevelsToCString(study.parameters.initialReservoirLevels.iniLevels)); - pBtnInitialReservoirLevels->caption(text); - text = wxStringFromUTF8( HydroHeuristicPolicyToCString(study.parameters.hydroHeuristicPolicy.hhPolicy)); pBtnHydroHeuristicPolicy->caption(text); @@ -514,58 +501,6 @@ void AdvancedParameters::onSelectNumericQualityHigh(wxCommandEvent&) } } -void AdvancedParameters::onInitialReservoirLevels(Component::Button&, wxMenu& menu, void*) -{ - wxMenuItem* it; - wxString text; - - text = wxStringFromUTF8(InitialReservoirLevelsToCString(Data::irlColdStart)); - text << wxT(" [default]"); - it = Menu::CreateItem(&menu, wxID_ANY, text, "images/16x16/tag.png"); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdvancedParameters::onSelectColdStart), - nullptr, - this); - - text.clear(); - text << wxStringFromUTF8(InitialReservoirLevelsToCString(Data::irlHotStart)); - it = Menu::CreateItem(&menu, wxID_ANY, text, "images/16x16/tag.png"); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdvancedParameters::onSelectHotStart), - nullptr, - this); -} - -void AdvancedParameters::onSelectColdStart(wxCommandEvent&) -{ - if (not CurrentStudyIsValid()) - return; - auto& study = *GetCurrentStudy(); - - if (study.parameters.initialReservoirLevels.iniLevels != Data::irlColdStart) - { - study.parameters.initialReservoirLevels.iniLevels = Data::irlColdStart; - MarkTheStudyAsModified(); - refresh(); - } -} - -void AdvancedParameters::onSelectHotStart(wxCommandEvent&) -{ - if (not CurrentStudyIsValid()) - return; - auto& study = *GetCurrentStudy(); - - if (study.parameters.initialReservoirLevels.iniLevels != Data::irlHotStart) - { - study.parameters.initialReservoirLevels.iniLevels = Data::irlHotStart; - MarkTheStudyAsModified(); - refresh(); - } -} - // ... Hydro heuristic policy void AdvancedParameters::onHydroHeuristicPolicy(Component::Button&, wxMenu& menu, void*) { @@ -806,52 +741,63 @@ void AdvancedParameters::onUnitCommitmentMode(Component::Button&, wxMenu& menu, wxMenuItem* it; wxString text; - text = wxStringFromUTF8(UnitCommitmentModeToCString(Data::ucHeuristic)); // Fast + text = wxStringFromUTF8(UnitCommitmentModeToCString(Data::ucHeuristicFast)); // Fast text << wxT(" [default]"); it = Menu::CreateItem(&menu, wxID_ANY, text, "images/16x16/tag.png"); menu.Connect(it->GetId(), wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdvancedParameters::onSelectUCHeuristic), + wxCommandEventHandler(AdvancedParameters::onSelectUCHeuristicFast), nullptr, this); text.clear(); - text = wxStringFromUTF8(UnitCommitmentModeToCString(Data::ucMILP)); // Accurate + text = wxStringFromUTF8(UnitCommitmentModeToCString(Data::ucHeuristicAccurate)); // Accurate text << wxT(" (slow)"); it = Menu::CreateItem(&menu, wxID_ANY, text, "images/16x16/tag.png"); menu.Connect(it->GetId(), wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdvancedParameters::onSelectUCMixedIntegerLinearProblem), + wxCommandEventHandler(AdvancedParameters::onSelectUCHeuristicAccurate), + nullptr, + this); + + text.clear(); + text = wxStringFromUTF8(UnitCommitmentModeToCString(Data::ucMILP)); // Accurate + text << wxT(" "); + it = Menu::CreateItem(&menu, wxID_ANY, text, "images/16x16/tag.png"); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdvancedParameters::onSelectUCMILP), nullptr, this); } -void AdvancedParameters::onSelectUCHeuristic(wxCommandEvent& /* evt */) +void AdvancedParameters::onSelectUCMode(Antares::Data::UnitCommitmentMode mode) { - auto& study = *GetCurrentStudy(); if (not CurrentStudyIsValid()) return; + auto study = GetCurrentStudy(); - if (study.parameters.unitCommitment.ucMode != Data::ucHeuristic) + if (study->parameters.unitCommitment.ucMode != mode) { - study.parameters.unitCommitment.ucMode = Data::ucHeuristic; + study->parameters.unitCommitment.ucMode = mode; MarkTheStudyAsModified(); refresh(); } } -void AdvancedParameters::onSelectUCMixedIntegerLinearProblem(wxCommandEvent& /* evt */) +void AdvancedParameters::onSelectUCHeuristicFast(wxCommandEvent& /* evt */) { - if (not CurrentStudyIsValid()) - return; - auto& study = *GetCurrentStudy(); + onSelectUCMode(Data::ucHeuristicFast); +} - if (study.parameters.unitCommitment.ucMode != Data::ucMILP) - { - study.parameters.unitCommitment.ucMode = Data::ucMILP; - MarkTheStudyAsModified(); - refresh(); - } +void AdvancedParameters::onSelectUCHeuristicAccurate(wxCommandEvent& /* evt */) +{ + onSelectUCMode(Data::ucHeuristicAccurate); +} + +void AdvancedParameters::onSelectUCMILP(wxCommandEvent& /* evt */) +{ + onSelectUCMode(Data::ucMILP); } void AdvancedParameters::onNumberOfCores(Component::Button&, wxMenu& menu, void*) diff --git a/src/ui/simulator/windows/options/advanced/advanced.h b/src/ui/simulator/windows/options/advanced/advanced.h index 15e274fae5..1410d05595 100644 --- a/src/ui/simulator/windows/options/advanced/advanced.h +++ b/src/ui/simulator/windows/options/advanced/advanced.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADVANCED_PARAMETERS_H__ #define __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADVANCED_PARAMETERS_H__ @@ -75,11 +69,7 @@ class AdvancedParameters final : public wxDialog void onNumericQuality(Component::Button&, wxMenu&, void*, Data::TimeSeriesType ts); void onSelectNumericQualityStandard(wxCommandEvent& evt); void onSelectNumericQualityHigh(wxCommandEvent& evt); - - void onInitialReservoirLevels(Component::Button&, wxMenu&, void*); - void onSelectHotStart(wxCommandEvent& evt); - void onSelectColdStart(wxCommandEvent& evt); - + void onHydroHeuristicPolicy(Component::Button&, wxMenu& menu, void*); void onSelectAccomodateRuleCurves(wxCommandEvent& evt); void onSelectMaximizeGeneration(wxCommandEvent& evt); @@ -98,8 +88,11 @@ class AdvancedParameters final : public wxDialog void onSelectSHPMinimizeDuration(wxCommandEvent& evt); void onUnitCommitmentMode(Component::Button&, wxMenu& menu, void*); - void onSelectUCHeuristic(wxCommandEvent& evt); - void onSelectUCMixedIntegerLinearProblem(wxCommandEvent& evt); + + void onSelectUCMode(Antares::Data::UnitCommitmentMode mode); + void onSelectUCHeuristicFast(wxCommandEvent& evt); + void onSelectUCHeuristicAccurate(wxCommandEvent& evt); + void onSelectUCMILP(wxCommandEvent& evt); void onNumberOfCores(Component::Button&, wxMenu& menu, void*); template @@ -118,7 +111,6 @@ class AdvancedParameters final : public wxDialog Component::Button* pBtnNumericQualityWind; Component::Button* pBtnNumericQualitySolar; Component::Button* pBtnPowerFluctuations; - Component::Button* pBtnInitialReservoirLevels; Component::Button* pBtnHydroHeuristicPolicy; Component::Button* pBtnHydroPricing; Component::Button* pBtnSheddingPolicy; diff --git a/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.cpp b/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.cpp index ffbb59ed30..5911f3dd0a 100644 --- a/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.cpp +++ b/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "geographic-trimming.h" #include diff --git a/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.h b/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.h index cccf64c778..3f6ede678e 100644 --- a/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.h +++ b/src/ui/simulator/windows/options/geographic-trimming/geographic-trimming.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREAS_TRIMMING_H__ #define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_AREAS_TRIMMING_H__ diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index c690021256..7c0b01db29 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "optimization.h" @@ -47,7 +41,7 @@ namespace Options { static void ResetButton(Component::Button* button, bool value) { - assert(button != NULL); + assert(button); if (value) { button->image("images/16x16/light_green.png"); @@ -62,7 +56,7 @@ static void ResetButton(Component::Button* button, bool value) static void ResetButton(Component::Button* button, Data::GlobalTransmissionCapacities value) { - assert(button != NULL); + assert(button); button->image(transmissionCapacityIcon(value)); button->caption(GlobalTransmissionCapacitiesToString_Display(value)); } @@ -355,7 +349,7 @@ Optimization::Optimization(wxWindow* parent) : sizer->Add(panel, 0, wxALL | wxEXPAND); // refresh - Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(Optimization::onInternalMotion), NULL, this); + Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(Optimization::onInternalMotion), nullptr, this); refresh(); SetSizer(sizer); diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index b133861b7a..4a269eb8a0 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_OPTIONS_OPTIMIZATION_PREFS_H__ #define __ANTARES_APPLICATION_WINDOWS_OPTIONS_OPTIMIZATION_PREFS_H__ diff --git a/src/ui/simulator/windows/options/playlist/playlist.cpp b/src/ui/simulator/windows/options/playlist/playlist.cpp index 2521fdc209..a8ea6d723f 100644 --- a/src/ui/simulator/windows/options/playlist/playlist.cpp +++ b/src/ui/simulator/windows/options/playlist/playlist.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "playlist.h" @@ -30,7 +24,7 @@ #include #include -#include +#include #include "../../../toolbox/resources.h" #include "../../../application/study.h" #include "../../../application/main.h" diff --git a/src/ui/simulator/windows/options/playlist/playlist.h b/src/ui/simulator/windows/options/playlist/playlist.h index 8b266cfa95..69305aea74 100644 --- a/src/ui/simulator/windows/options/playlist/playlist.h +++ b/src/ui/simulator/windows/options/playlist/playlist.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_PLAYLIST_H__ #define __ANTARES_APPLICATION_WINDOWS_PLAYLIST_H__ diff --git a/src/ui/simulator/windows/options/select-output/select-output.cpp b/src/ui/simulator/windows/options/select-output/select-output.cpp index 5e70c3ad17..578dc30b58 100644 --- a/src/ui/simulator/windows/options/select-output/select-output.cpp +++ b/src/ui/simulator/windows/options/select-output/select-output.cpp @@ -1,10 +1,30 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "select-output.h" #include #include #include -#include +#include #include "../../../toolbox/resources.h" #include "../../../application/study.h" #include "../../../application/main.h" diff --git a/src/ui/simulator/windows/options/select-output/select-output.h b/src/ui/simulator/windows/options/select-output/select-output.h index 9e31a5b21f..5fe6a81fc9 100644 --- a/src/ui/simulator/windows/options/select-output/select-output.h +++ b/src/ui/simulator/windows/options/select-output/select-output.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_APPLICATION_WINDOWS_SELECTOUTPUT_H__ #define __ANTARES_APPLICATION_WINDOWS_SELECTOUTPUT_H__ diff --git a/src/ui/simulator/windows/options/temp-folder/temp-folder.cpp b/src/ui/simulator/windows/options/temp-folder/temp-folder.cpp index 56dc9ad5ee..bc82fd78e0 100644 --- a/src/ui/simulator/windows/options/temp-folder/temp-folder.cpp +++ b/src/ui/simulator/windows/options/temp-folder/temp-folder.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "temp-folder.h" @@ -69,7 +63,7 @@ ConfigureTempFolder::ConfigureTempFolder(wxWindow* parent) : pDefaults(nullptr), pText(nullptr) { - assert(NULL != parent); + assert(parent); auto* config = new wxConfig(wxT(LOG_APPLICATION_NAME), wxT(LOG_APPLICATION_VENDOR)); // Title of the Form diff --git a/src/ui/simulator/windows/options/temp-folder/temp-folder.h b/src/ui/simulator/windows/options/temp-folder/temp-folder.h index 0e0f8b1b67..208973ac67 100644 --- a/src/ui/simulator/windows/options/temp-folder/temp-folder.h +++ b/src/ui/simulator/windows/options/temp-folder/temp-folder.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_OPTIONS_TEMP_FOLDER_H__ #define __ANTARES_APPLICATION_WINDOWS_OPTIONS_TEMP_FOLDER_H__ diff --git a/src/ui/simulator/windows/output/content.h b/src/ui/simulator/windows/output/content.h index bf336032ba..5b5508e57e 100644 --- a/src/ui/simulator/windows/output/content.h +++ b/src/ui/simulator/windows/output/content.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_CONTENT_H__ #define __ANTARES_WINDOWS_OUTPUT_CONTENT_H__ diff --git a/src/ui/simulator/windows/output/content.hxx b/src/ui/simulator/windows/output/content.hxx index ec43707055..214dc4c239 100644 --- a/src/ui/simulator/windows/output/content.hxx +++ b/src/ui/simulator/windows/output/content.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_CONTENT_HXX__ #define __ANTARES_WINDOWS_OUTPUT_CONTENT_HXX__ diff --git a/src/ui/simulator/windows/output/fwd.h b/src/ui/simulator/windows/output/fwd.h index 6be44c8f5b..5d23d16b6b 100644 --- a/src/ui/simulator/windows/output/fwd.h +++ b/src/ui/simulator/windows/output/fwd.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_FWD_H__ #define __ANTARES_WINDOWS_OUTPUT_FWD_H__ diff --git a/src/ui/simulator/windows/output/job.cpp b/src/ui/simulator/windows/output/job.cpp index 66a66c291d..714e42b539 100644 --- a/src/ui/simulator/windows/output/job.cpp +++ b/src/ui/simulator/windows/output/job.cpp @@ -1,33 +1,29 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "job.h" +#include "antares/utils/utils.h" #include #include +#include #include using namespace Yuni; diff --git a/src/ui/simulator/windows/output/job.h b/src/ui/simulator/windows/output/job.h index b5569bcf4b..40e2c14da7 100644 --- a/src/ui/simulator/windows/output/job.h +++ b/src/ui/simulator/windows/output/job.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_JOB_H__ #define __ANTARES_WINDOWS_OUTPUT_JOB_H__ diff --git a/src/ui/simulator/windows/output/layer.cpp b/src/ui/simulator/windows/output/layer.cpp index 64b0223250..0ae1701044 100644 --- a/src/ui/simulator/windows/output/layer.cpp +++ b/src/ui/simulator/windows/output/layer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "layer.h" diff --git a/src/ui/simulator/windows/output/layer.h b/src/ui/simulator/windows/output/layer.h index 26eebad7bb..758aa1cc39 100644 --- a/src/ui/simulator/windows/output/layer.h +++ b/src/ui/simulator/windows/output/layer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_LAYER_H__ #define __ANTARES_WINDOWS_OUTPUT_LAYER_H__ diff --git a/src/ui/simulator/windows/output/layer.hxx b/src/ui/simulator/windows/output/layer.hxx index b9faa7ce12..acbbef5dc0 100644 --- a/src/ui/simulator/windows/output/layer.hxx +++ b/src/ui/simulator/windows/output/layer.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_LAYER_HXX__ #define __ANTARES_WINDOWS_OUTPUT_LAYER_HXX__ diff --git a/src/ui/simulator/windows/output/mini-frame.cpp b/src/ui/simulator/windows/output/mini-frame.cpp index 160f244a2d..39c6fd137e 100644 --- a/src/ui/simulator/windows/output/mini-frame.cpp +++ b/src/ui/simulator/windows/output/mini-frame.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "mini-frame.h" diff --git a/src/ui/simulator/windows/output/mini-frame.h b/src/ui/simulator/windows/output/mini-frame.h index b89c3e6d4f..632498e167 100644 --- a/src/ui/simulator/windows/output/mini-frame.h +++ b/src/ui/simulator/windows/output/mini-frame.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_MINI_FRAME_H__ #define __ANTARES_WINDOWS_OUTPUT_MINI_FRAME_H__ diff --git a/src/ui/simulator/windows/output/output.cpp b/src/ui/simulator/windows/output/output.cpp index 4537a70831..28be461e76 100644 --- a/src/ui/simulator/windows/output/output.cpp +++ b/src/ui/simulator/windows/output/output.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/antares/antares.h" #include "output.h" #include #include "../../toolbox/components/captionpanel.h" @@ -508,7 +502,7 @@ void Component::createAllControlsIfNeeded() OnStudyClosed.connect(this, &Component::onStudyClosed); // Layout - assert(GetSizer() != NULL); + assert(GetSizer()); GetSizer()->Layout(); pControlsAlreadyCreated = true; diff --git a/src/ui/simulator/windows/output/output.h b/src/ui/simulator/windows/output/output.h index 4aa2403eb4..4e83b77fb6 100644 --- a/src/ui/simulator/windows/output/output.h +++ b/src/ui/simulator/windows/output/output.h @@ -1,32 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_OUTPUT_H__ #define __ANTARES_WINDOWS_OUTPUT_OUTPUT_H__ +#include #include #include "../../application/study.h" #include "../../toolbox/components/button.h" @@ -378,8 +373,7 @@ class Component : public Antares::Component::Panel, public Yuni::IEventObserver< //! \name Background process //@{ - //! Mutex - Yuni::Mutex pMutex; + std::mutex pMutex; //! Jobs Antares::Private::OutputViewerData::JobVector pJobs; //! All already prepared outputs diff --git a/src/ui/simulator/windows/output/panel.h b/src/ui/simulator/windows/output/panel.h index 91a87ba8ba..1e71cde5d5 100644 --- a/src/ui/simulator/windows/output/panel.h +++ b/src/ui/simulator/windows/output/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PANEL_H__ #define __ANTARES_WINDOWS_OUTPUT_PANEL_H__ diff --git a/src/ui/simulator/windows/output/panel/area-link-renderer.cpp b/src/ui/simulator/windows/output/panel/area-link-renderer.cpp index 223072b1c5..0f6373334c 100644 --- a/src/ui/simulator/windows/output/panel/area-link-renderer.cpp +++ b/src/ui/simulator/windows/output/panel/area-link-renderer.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "area-link-renderer.h" @@ -180,7 +174,7 @@ int AreaLinkRenderer::height() const bool AreaLinkRenderer::valid() const { - return (NULL != pMatrix); + return (nullptr != pMatrix); } wxString AreaLinkRenderer::columnCaption(int colIndx) const diff --git a/src/ui/simulator/windows/output/panel/area-link-renderer.h b/src/ui/simulator/windows/output/panel/area-link-renderer.h index 9efe88fc89..f5c98fb490 100644 --- a/src/ui/simulator/windows/output/panel/area-link-renderer.h +++ b/src/ui/simulator/windows/output/panel/area-link-renderer.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PANEL_AREA_LINK_RENDERER_H__ #define __ANTARES_WINDOWS_OUTPUT_PANEL_AREA_LINK_RENDERER_H__ diff --git a/src/ui/simulator/windows/output/panel/area-link.cpp b/src/ui/simulator/windows/output/panel/area-link.cpp index eb913d6595..d8830b5784 100644 --- a/src/ui/simulator/windows/output/panel/area-link.cpp +++ b/src/ui/simulator/windows/output/panel/area-link.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" @@ -36,6 +30,7 @@ #include #include #include +#include using namespace Yuni; @@ -105,7 +100,7 @@ class JobMatrix : public Yuni::Job::IJob, public Yuni::IEventObserver //! Loading options uint options; //! - Atomic::Int<> shouldAbort; + std::atomic shouldAbort; protected: virtual void onExecute() @@ -126,7 +121,7 @@ class JobMatrix : public Yuni::Job::IJob, public Yuni::IEventObserver { // file lock auto mutex = ProvideLockingForFileLocking(filename); - Yuni::MutexLocker locker(*mutex); + std::lock_guard locker(*mutex); if (not shouldAbort) success = pMatrix->loadFromCSVFile(filename, 1, 0, options); } @@ -157,7 +152,7 @@ class JobMatrix : public Yuni::Job::IJob, public Yuni::IEventObserver } // The loading of the matrix had failed. - // The GUI will be updated with NULL + // The GUI will be updated with nullptr callback.bind(&pPanel, &Panel::loadDataFromMatrix, (MatrixType*)nullptr); if (not shouldAbort) Antares::Dispatcher::GUI::Post(callback, 50); @@ -212,7 +207,7 @@ class JobAggregator : public Yuni::Job::IJob, public Yuni::IEventObserver shouldAbort; + std::atomic shouldAbort; protected: enum @@ -280,7 +275,7 @@ class JobAggregator : public Yuni::Job::IJob, public Yuni::IEventObserverreset(ops.width, ops.height); @@ -469,7 +464,7 @@ class JobAggregator : public Yuni::Job::IJob, public Yuni::IEventObserver. +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" @@ -39,6 +33,7 @@ #include "../../../application/wait.h" #include +#include using namespace Yuni; @@ -48,12 +43,12 @@ namespace Private { namespace OutputViewerData { -Yuni::Atomic::Int<32> Panel::pPanelsInCallingLoadDataFromFile = 0; +std::atomic Panel::pPanelsInCallingLoadDataFromFile = 0; namespace // anonymous { -static std::map> mutexForFiles; -static Yuni::Mutex mutexToAccessToLockFiles; +static std::map> mutexForFiles; +static std::mutex mutexToAccessToLockFiles; static inline void DefaultBckColour(Antares::Component::Panel* panel) { @@ -477,18 +472,18 @@ void Panel::executeAggregator() delete exec; } -std::shared_ptr ProvideLockingForFileLocking(const YString& filename) +std::shared_ptr ProvideLockingForFileLocking(const YString& filename) { - Yuni::MutexLocker locker(mutexToAccessToLockFiles); + std::lock_guard locker(mutexToAccessToLockFiles); auto& ptr = mutexForFiles[filename]; if (!ptr) - ptr = std::make_shared(); + ptr = std::make_shared(); return ptr; } void ClearAllMutexForFileLocking() { - Yuni::MutexLocker locker(mutexToAccessToLockFiles); + std::lock_guard locker(mutexToAccessToLockFiles); mutexForFiles.clear(); } diff --git a/src/ui/simulator/windows/output/panel/panel.h b/src/ui/simulator/windows/output/panel/panel.h index f83ffca4c3..d9eec73201 100644 --- a/src/ui/simulator/windows/output/panel/panel.h +++ b/src/ui/simulator/windows/output/panel/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PANEL_PANEL_H__ #define __ANTARES_WINDOWS_OUTPUT_PANEL_PANEL_H__ @@ -35,7 +29,9 @@ #include #include +#include #include +#include namespace Antares { @@ -147,8 +143,7 @@ class Panel final : public Antares::Component::Panel wxWindow* pButton; bool pShouldRebuildMessage; - //! Mutex - Yuni::Mutex pMutex; + std::mutex pMutex; //! Data IData* pData; //! Filename currently used @@ -156,7 +151,7 @@ class Panel final : public Antares::Component::Panel //! The total number of panels currently calling loadDataFromFile // This method is often an async call - static Yuni::Atomic::Int<32> pPanelsInCallingLoadDataFromFile; + static std::atomic pPanelsInCallingLoadDataFromFile; }; // class Panel @@ -168,7 +163,7 @@ class Panel final : public Antares::Component::Panel ** This variable is cleared when the study is closed or the user get back ** to the input */ -std::shared_ptr ProvideLockingForFileLocking(const YString& filename); +std::shared_ptr ProvideLockingForFileLocking(const YString& filename); /*! ** \brief Clear all mutex for file locking diff --git a/src/ui/simulator/windows/output/panel/panel.hxx b/src/ui/simulator/windows/output/panel/panel.hxx index c7149d9a69..cb591e9fc2 100644 --- a/src/ui/simulator/windows/output/panel/panel.hxx +++ b/src/ui/simulator/windows/output/panel/panel.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PANEL_PANEL_HXX__ #define __ANTARES_WINDOWS_OUTPUT_PANEL_PANEL_HXX__ diff --git a/src/ui/simulator/windows/output/provider/output-comparison.cpp b/src/ui/simulator/windows/output/provider/output-comparison.cpp index 2e71b9e9d4..52798564f7 100644 --- a/src/ui/simulator/windows/output/provider/output-comparison.cpp +++ b/src/ui/simulator/windows/output/provider/output-comparison.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "output-comparison.h" diff --git a/src/ui/simulator/windows/output/provider/output-comparison.h b/src/ui/simulator/windows/output/provider/output-comparison.h index 84431b298c..f52ceb0d0a 100644 --- a/src/ui/simulator/windows/output/provider/output-comparison.h +++ b/src/ui/simulator/windows/output/provider/output-comparison.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PROVIDER_COMPARISON_H__ #define __ANTARES_WINDOWS_OUTPUT_PROVIDER_COMPARISON_H__ diff --git a/src/ui/simulator/windows/output/provider/outputs.cpp b/src/ui/simulator/windows/output/provider/outputs.cpp index aa95581337..338616ccfd 100644 --- a/src/ui/simulator/windows/output/provider/outputs.cpp +++ b/src/ui/simulator/windows/output/provider/outputs.cpp @@ -1,31 +1,25 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ -#include +#include "antares/antares/antares.h" #include "outputs.h" #include #include "../output.h" @@ -160,10 +154,10 @@ void Outputs::search(Spotlight::IItem::Vector& out, } auto item = std::make_shared(); - if (output->version != (uint)Data::versionLatest) + if (output->version != Data::StudyVersion::latest()) { CString<16, false> text; - text << 'v' << Data::VersionToCStr((Data::Version)output->version); + text << 'v' << output->version.toString(); item->addRightTag(text, 220, 220, 240); } item->caption(title); @@ -173,15 +167,16 @@ void Outputs::search(Spotlight::IItem::Vector& out, switch (output->mode) { - case Data::stdmEconomy: + case Data::SimulationMode::Economy: item->addTag("ECO", 162, 178, 197); break; - case Data::stdmAdequacy: + case Data::SimulationMode::Adequacy: item->addTag("ADQ", 220, 192, 245); break; - case Data::stdmUnknown: - case Data::stdmExpansion: - case Data::stdmMax: + case Data::SimulationMode::Expansion: + item->addTag("EXP", 220, 192, 245); + break; + case Data::SimulationMode::Unknown: item->addTag("...", 213, 213, 213); } int imgIndex = pComponent.imageIndexForOutput(output); diff --git a/src/ui/simulator/windows/output/provider/outputs.h b/src/ui/simulator/windows/output/provider/outputs.h index b60dd2f150..f3ab54e700 100644 --- a/src/ui/simulator/windows/output/provider/outputs.h +++ b/src/ui/simulator/windows/output/provider/outputs.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PROVIDER_OUTPUTS_H__ #define __ANTARES_WINDOWS_OUTPUT_PROVIDER_OUTPUTS_H__ diff --git a/src/ui/simulator/windows/output/provider/variable-collector.cpp b/src/ui/simulator/windows/output/provider/variable-collector.cpp index b2cee30bdc..3534669fe9 100644 --- a/src/ui/simulator/windows/output/provider/variable-collector.cpp +++ b/src/ui/simulator/windows/output/provider/variable-collector.cpp @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #include "variable-collector.h" diff --git a/src/ui/simulator/windows/output/provider/variable-collector.h b/src/ui/simulator/windows/output/provider/variable-collector.h index 9c69334fca..49a473b3fc 100644 --- a/src/ui/simulator/windows/output/provider/variable-collector.h +++ b/src/ui/simulator/windows/output/provider/variable-collector.h @@ -1,3 +1,23 @@ +/* +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or +** (at your option) any later version. +** +** Antares_Simulator 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 +** Mozilla Public Licence 2.0 for more details. +** +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . +*/ #ifndef __ANTARES_WINDOWS_OUTPUT_PROVIDER_VARIABLES_COLLECTOR_H__ #define __ANTARES_WINDOWS_OUTPUT_PROVIDER_VARIABLES_COLLECTOR_H__ diff --git a/src/ui/simulator/windows/output/provider/variables.cpp b/src/ui/simulator/windows/output/provider/variables.cpp index 07e0887b77..f6d2adc22c 100644 --- a/src/ui/simulator/windows/output/provider/variables.cpp +++ b/src/ui/simulator/windows/output/provider/variables.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "variables.h" @@ -31,7 +25,7 @@ #include "../content.h" #include "../../../toolbox/resources.h" #include -#include "../../../../../solver/variable/economy/all.h" +#include "antares/solver/variable/economy/all.h" #include "variable-collector.h" using namespace Yuni; diff --git a/src/ui/simulator/windows/output/provider/variables.h b/src/ui/simulator/windows/output/provider/variables.h index ac891cde11..8d1f0f5605 100644 --- a/src/ui/simulator/windows/output/provider/variables.h +++ b/src/ui/simulator/windows/output/provider/variables.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_PROVIDER_VARIABLES_H__ #define __ANTARES_WINDOWS_OUTPUT_PROVIDER_VARIABLES_H__ diff --git a/src/ui/simulator/windows/output/spotlight-provider.cpp b/src/ui/simulator/windows/output/spotlight-provider.cpp index 0eb1cc5528..cca302e2e1 100644 --- a/src/ui/simulator/windows/output/spotlight-provider.cpp +++ b/src/ui/simulator/windows/output/spotlight-provider.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "spotlight-provider.h" @@ -145,7 +139,7 @@ void SpotlightProvider::search(Spotlight::IItem::Vector& out, return; // Looking for the list of areas and links - Yuni::MutexLocker locker(pComponent->pMutex); + std::lock_guard locker(pComponent->pMutex); auto it = pComponent->pAlreadyPreparedContents.find(outputPath); if (it == pComponent->pAlreadyPreparedContents.end()) @@ -421,8 +415,8 @@ void SpotlightProviderGlobalSelection::search(Spotlight::IItem::Vector& out, auto aEnd = study.areas.end(); for (auto itArea = study.areas.begin(); itArea != aEnd; ++itArea) { - if (arealink->id == itArea->first) // this area is in the study (it is visible - // at least on layer 0) + if (arealink->id.equals(itArea->first)) // this area is in the study (it is visible + // at least on layer 0) { foundInALayer = true; break; @@ -482,7 +476,7 @@ void SpotlightProviderGlobalSelection::search(Spotlight::IItem::Vector& out, auto aEnd = study.areas.end(); for (auto itArea = study.areas.begin(); itArea != aEnd; ++itArea) { - if (arealink->id == itArea->first + if (arealink->id.equals(itArea->first) && itArea->second->isVisibleOnLayer( layerID)) // this area is in the study (it is visible at least on layer 0) { diff --git a/src/ui/simulator/windows/output/spotlight-provider.h b/src/ui/simulator/windows/output/spotlight-provider.h index 36bdd96a21..c926f625d5 100644 --- a/src/ui/simulator/windows/output/spotlight-provider.h +++ b/src/ui/simulator/windows/output/spotlight-provider.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_SPOTLIGHT_PROVIDER_H__ #define __ANTARES_WINDOWS_OUTPUT_SPOTLIGHT_PROVIDER_H__ diff --git a/src/ui/simulator/windows/output/tab.cpp b/src/ui/simulator/windows/output/tab.cpp index 3ec2d6422e..5185721d0c 100644 --- a/src/ui/simulator/windows/output/tab.cpp +++ b/src/ui/simulator/windows/output/tab.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "output.h" diff --git a/src/ui/simulator/windows/output/window.cpp b/src/ui/simulator/windows/output/window.cpp index aca46d1ecf..3b7eb96b74 100644 --- a/src/ui/simulator/windows/output/window.cpp +++ b/src/ui/simulator/windows/output/window.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "window.h" diff --git a/src/ui/simulator/windows/output/window.h b/src/ui/simulator/windows/output/window.h index 518c74fcfc..05398220cd 100644 --- a/src/ui/simulator/windows/output/window.h +++ b/src/ui/simulator/windows/output/window.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_OUTPUT_WINDOW_H__ #define __ANTARES_WINDOWS_OUTPUT_WINDOW_H__ diff --git a/src/ui/simulator/windows/renewables/cluster.cpp b/src/ui/simulator/windows/renewables/cluster.cpp index 7eedf0e33a..cb13fd96c9 100644 --- a/src/ui/simulator/windows/renewables/cluster.cpp +++ b/src/ui/simulator/windows/renewables/cluster.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "cluster.h" diff --git a/src/ui/simulator/windows/renewables/cluster.h b/src/ui/simulator/windows/renewables/cluster.h index 52d5a52a59..d8be7473b8 100644 --- a/src/ui/simulator/windows/renewables/cluster.h +++ b/src/ui/simulator/windows/renewables/cluster.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_RENEWABLE_COMMON_H__ #define __ANTARES_APPLICATION_WINDOW_RENEWABLE_COMMON_H__ diff --git a/src/ui/simulator/windows/renewables/panel.cpp b/src/ui/simulator/windows/renewables/panel.cpp index 2103eea79b..19e9dc290c 100644 --- a/src/ui/simulator/windows/renewables/panel.cpp +++ b/src/ui/simulator/windows/renewables/panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" diff --git a/src/ui/simulator/windows/renewables/panel.h b/src/ui/simulator/windows/renewables/panel.h index aec876f3db..7d4d782943 100644 --- a/src/ui/simulator/windows/renewables/panel.h +++ b/src/ui/simulator/windows/renewables/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOW_RENEWABLE_PANEL_H__ #define __ANTARES_WINDOW_RENEWABLE_PANEL_H__ diff --git a/src/ui/simulator/windows/saveas.cpp b/src/ui/simulator/windows/saveas.cpp index eb4ef1d0a4..0fba0f4719 100644 --- a/src/ui/simulator/windows/saveas.cpp +++ b/src/ui/simulator/windows/saveas.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "saveas.h" diff --git a/src/ui/simulator/windows/saveas.h b/src/ui/simulator/windows/saveas.h index af057cdd8b..7019b38cb1 100644 --- a/src/ui/simulator/windows/saveas.h +++ b/src/ui/simulator/windows/saveas.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_SAVEAS_H__ #define __ANTARES_APPLICATION_WINDOWS_SAVEAS_H__ diff --git a/src/ui/simulator/windows/saveas.hxx b/src/ui/simulator/windows/saveas.hxx index 988153098d..ef401569ac 100644 --- a/src/ui/simulator/windows/saveas.hxx +++ b/src/ui/simulator/windows/saveas.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_SAVEAS_HXX__ #define __ANTARES_APPLICATION_WINDOWS_SAVEAS_HXX__ diff --git a/src/ui/simulator/windows/scenario-builder/panel.cpp b/src/ui/simulator/windows/scenario-builder/panel.cpp index 1d96d5a411..7dd60c8e3d 100644 --- a/src/ui/simulator/windows/scenario-builder/panel.cpp +++ b/src/ui/simulator/windows/scenario-builder/panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" diff --git a/src/ui/simulator/windows/scenario-builder/panel.h b/src/ui/simulator/windows/scenario-builder/panel.h index 44e59afa00..e80dd3e3c6 100644 --- a/src/ui/simulator/windows/scenario-builder/panel.h +++ b/src/ui/simulator/windows/scenario-builder/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_SCENARIO_BUILDER_PANEL_H__ #define __ANTARES_APPLICATION_WINDOWS_SCENARIO_BUILDER_PANEL_H__ diff --git a/src/ui/simulator/windows/sets.cpp b/src/ui/simulator/windows/sets.cpp index 421e58b036..d92fe3873d 100644 --- a/src/ui/simulator/windows/sets.cpp +++ b/src/ui/simulator/windows/sets.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "sets.h" @@ -587,7 +581,8 @@ void Sets::saveToStudy() pRichEdit->SaveFile(wxStringFromUTF8(pTempFile), wxRICHTEXT_TYPE_TEXT); // ... and reloading it // IO::File::LoadFromFile(study->simulation.comments, pTempFile); - study->setsOfAreas.loadFromFile(pTempFile); + std::filesystem::path p{pTempFile.c_str()}; + study->setsOfAreas.loadFromFile(p); } bool Sets::initializeTemporaryFile() diff --git a/src/ui/simulator/windows/sets.h b/src/ui/simulator/windows/sets.h index 06c0d70266..ecbcb5084c 100644 --- a/src/ui/simulator/windows/sets.h +++ b/src/ui/simulator/windows/sets.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_SETS_H__ #define __ANTARES_APPLICATION_WINDOWS_SETS_H__ diff --git a/src/ui/simulator/windows/simulation/panel.cpp b/src/ui/simulator/windows/simulation/panel.cpp index a24f86fabd..29143b7944 100644 --- a/src/ui/simulator/windows/simulation/panel.cpp +++ b/src/ui/simulator/windows/simulation/panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" diff --git a/src/ui/simulator/windows/simulation/panel.h b/src/ui/simulator/windows/simulation/panel.h index 3113dba3a3..295cfa0d57 100644 --- a/src/ui/simulator/windows/simulation/panel.h +++ b/src/ui/simulator/windows/simulation/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_SIMULATION_PANEL_H__ #define __ANTARES_APPLICATION_WINDOWS_SIMULATION_PANEL_H__ diff --git a/src/ui/simulator/windows/simulation/run.cpp b/src/ui/simulator/windows/simulation/run.cpp index c6a68e868c..e32fb55101 100644 --- a/src/ui/simulator/windows/simulation/run.cpp +++ b/src/ui/simulator/windows/simulation/run.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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. +** Mozilla Public Licence 2.0 for more details. ** -** You should have received a copy of the GNU General Public License -** along with Antares_Simulator. If not, see . -** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "run.h" @@ -47,24 +41,20 @@ #include "../../toolbox/validator.h" #include "../../toolbox/create.h" -#include #include "../../application/study.h" #include "../../application/main/main.h" #include "../../application/menus.h" #include "../../windows/message.h" #include "../../toolbox/system/diskfreespace.hxx" -#include -#include +#include +#include "antares/antares/Enum.hpp" +#include "antares/solver/utils/ortools_utils.h" -#include +#include using namespace Yuni; -namespace Antares -{ -namespace Window -{ -namespace Simulation +namespace Antares::Window::Simulation { enum { @@ -217,7 +207,7 @@ Run::Run(wxWindow* parent, bool preproOnly) : "images/32x32/run.png", wxString(wxT("For the study `")) << wxStringFromUTF8(study.header.caption) << wxT("`, ") - << wxStringFromUTF8(Data::StudyModeToCString(study.parameters.mode))), + << wxStringFromUTF8(Data::SimulationModeToCString(study.parameters.mode))), 0, wxALL | wxEXPAND | wxFIXED_MINSIZE); @@ -242,7 +232,7 @@ Run::Run(wxWindow* parent, bool preproOnly) : } { auto* lblMode = Antares::Component::CreateLabel( - pBigDaddy, wxStringFromUTF8(Data::StudyModeToCString(study.parameters.mode))); + pBigDaddy, wxStringFromUTF8(Data::SimulationModeToCString(study.parameters.mode))); wxFont f = lblMode->GetFont(); f.SetWeight(wxFONTWEIGHT_BOLD); lblMode->SetFont(f); @@ -431,7 +421,7 @@ Run::Run(wxWindow* parent, bool preproOnly) : pTimer->Start(150); // Event - Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(Run::onInternalMotion), NULL, this); + Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(Run::onInternalMotion), nullptr, this); } Run::~Run() @@ -834,6 +824,6 @@ void Run::onOrtoolsCheckboxChanged(wxCommandEvent& WXUNUSED(event)) sizer->Fit(this); } -} // namespace Simulation -} // namespace Window -} // namespace Antares +} // namespace Antares::Window::Simulation + + diff --git a/src/ui/simulator/windows/simulation/run.h b/src/ui/simulator/windows/simulation/run.h index 0586fedae0..f9a7ef395c 100644 --- a/src/ui/simulator/windows/simulation/run.h +++ b/src/ui/simulator/windows/simulation/run.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_SIMULATION_RUN_H__ #define __ANTARES_APPLICATION_WINDOWS_SIMULATION_RUN_H__ diff --git a/src/ui/simulator/windows/startupwizard.cpp b/src/ui/simulator/windows/startupwizard.cpp index 4997cc2346..ea4372e981 100644 --- a/src/ui/simulator/windows/startupwizard.cpp +++ b/src/ui/simulator/windows/startupwizard.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "startupwizard.h" @@ -31,7 +25,7 @@ #include #include -#include +#include #include "../toolbox/resources.h" #include "../toolbox/components/button.h" #include "../application/study.h" @@ -41,7 +35,7 @@ #include "../application/menus.h" #include "../application/wait.h" #include "version.h" -#include "../../../config.h" +#include #include #include #include "../toolbox/dispatcher/study.h" @@ -73,7 +67,7 @@ class MyStudyFinder final : public Antares::Data::StudyFinder pOutputList.push_back(PairStringString(it.first, it.second)); } - virtual void onStudyFound(const String& folder, Data::Version) override + virtual void onStudyFound(const String& folder, const Data::StudyVersion&) override { if (Data::Study::TitleFromStudyFolder(folder, pTitle, false)) { diff --git a/src/ui/simulator/windows/startupwizard.h b/src/ui/simulator/windows/startupwizard.h index cc7a1e2a1c..2fc1266eec 100644 --- a/src/ui/simulator/windows/startupwizard.h +++ b/src/ui/simulator/windows/startupwizard.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_STARTUP_WIZARD_H__ #define __ANTARES_APPLICATION_WINDOWS_STARTUP_WIZARD_H__ diff --git a/src/ui/simulator/windows/studylogs.cpp b/src/ui/simulator/windows/studylogs.cpp index 732954e272..db957b421a 100644 --- a/src/ui/simulator/windows/studylogs.cpp +++ b/src/ui/simulator/windows/studylogs.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "studylogs.h" @@ -318,7 +312,7 @@ void FileListProvider::refreshFileList(bool showAll) if (showAll) { folder.clear(); - IO::ExtractFilePath(folder, logs.logfile()); + IO::parent_path(folder, logs.logfile()); FindAllLogFiles(pAllUILogs, regex, folder); } @@ -861,7 +855,7 @@ void StudyLogs::enterLoadingMode(const String& filename) String name; String path; IO::ExtractFileName(name, filename); - IO::ExtractFilePath(path, filename); + IO::parent_path(path, filename); // Updating the notebook pNotebook->caption(wxEmptyString); diff --git a/src/ui/simulator/windows/studylogs.h b/src/ui/simulator/windows/studylogs.h index 3779cee36a..66a5321734 100644 --- a/src/ui/simulator/windows/studylogs.h +++ b/src/ui/simulator/windows/studylogs.h @@ -1,32 +1,27 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOWS_STUDY_LOGS_H__ #define __ANTARES_APPLICATION_WINDOWS_STUDY_LOGS_H__ +#include #include #include @@ -186,7 +181,7 @@ class StudyLogs final : public Component::Frame::WxLocalFrame //! Temporary structure used for displaying the list of all available files LogFilenameInfo::Map pLogFilenameInfo; - Yuni::Mutex pLoadingMutex; + std::mutex pLoadingMutex; //! Flag to display all log files bool pShowAllLogsFiles; diff --git a/src/ui/simulator/windows/textinput/input.cpp b/src/ui/simulator/windows/textinput/input.cpp index a54d8c1b50..64165ca695 100644 --- a/src/ui/simulator/windows/textinput/input.cpp +++ b/src/ui/simulator/windows/textinput/input.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include diff --git a/src/ui/simulator/windows/textinput/input.h b/src/ui/simulator/windows/textinput/input.h index 92e14eda2a..b629d2183a 100644 --- a/src/ui/simulator/windows/textinput/input.h +++ b/src/ui/simulator/windows/textinput/input.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_TEXTINPUT_INPUT_H__ #define __ANTARES_WINDOWS_TEXTINPUT_INPUT_H__ diff --git a/src/ui/simulator/windows/thermal/cluster.cpp b/src/ui/simulator/windows/thermal/cluster.cpp index 1be1b88604..762aac9488 100644 --- a/src/ui/simulator/windows/thermal/cluster.cpp +++ b/src/ui/simulator/windows/thermal/cluster.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "cluster.h" diff --git a/src/ui/simulator/windows/thermal/cluster.h b/src/ui/simulator/windows/thermal/cluster.h index 83c90ad857..8af8f04fd0 100644 --- a/src/ui/simulator/windows/thermal/cluster.h +++ b/src/ui/simulator/windows/thermal/cluster.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_APPLICATION_WINDOW_THERMAL_COMMON_H__ #define __ANTARES_APPLICATION_WINDOW_THERMAL_COMMON_H__ diff --git a/src/ui/simulator/windows/thermal/panel.cpp b/src/ui/simulator/windows/thermal/panel.cpp index 9b5eedaeaf..a11a3855cd 100644 --- a/src/ui/simulator/windows/thermal/panel.cpp +++ b/src/ui/simulator/windows/thermal/panel.cpp @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "panel.h" diff --git a/src/ui/simulator/windows/thermal/panel.h b/src/ui/simulator/windows/thermal/panel.h index 432dbdd40b..72b5ab3947 100644 --- a/src/ui/simulator/windows/thermal/panel.h +++ b/src/ui/simulator/windows/thermal/panel.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOW_THERMAL_PANEL_H__ #define __ANTARES_WINDOW_THERMAL_PANEL_H__ diff --git a/src/ui/simulator/windows/version.cpp b/src/ui/simulator/windows/version.cpp index e845bbd325..613c6e89a0 100644 --- a/src/ui/simulator/windows/version.cpp +++ b/src/ui/simulator/windows/version.cpp @@ -1,32 +1,26 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #include "version.h" -#include "../../../config.h" +#include namespace Antares { diff --git a/src/ui/simulator/windows/version.h b/src/ui/simulator/windows/version.h index 44f51833d0..2378dc2e62 100644 --- a/src/ui/simulator/windows/version.h +++ b/src/ui/simulator/windows/version.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOW_VERSION_H__ #define __ANTARES_WINDOW_VERSION_H__ diff --git a/src/ui/simulator/windows/xcast/xcast.h b/src/ui/simulator/windows/xcast/xcast.h index bd21e6485e..0eed4a6c76 100644 --- a/src/ui/simulator/windows/xcast/xcast.h +++ b/src/ui/simulator/windows/xcast/xcast.h @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_XCAST_XCAST_H__ #define __ANTARES_WINDOWS_XCAST_XCAST_H__ diff --git a/src/ui/simulator/windows/xcast/xcast.hxx b/src/ui/simulator/windows/xcast/xcast.hxx index c2535aaa32..73dd21a7fc 100644 --- a/src/ui/simulator/windows/xcast/xcast.hxx +++ b/src/ui/simulator/windows/xcast/xcast.hxx @@ -1,28 +1,22 @@ /* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. +** Copyright 2007-2024, RTE (https://www.rte-france.com) +** See AUTHORS.txt +** SPDX-License-Identifier: MPL-2.0 +** This file is part of Antares-Simulator, +** Adequacy and Performance assessment for interconnected energy networks. ** ** Antares_Simulator 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 +** it under the terms of the Mozilla Public Licence 2.0 as published by +** the Mozilla Foundation, either version 2 of the License, or ** (at your option) any later version. ** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** ** Antares_Simulator 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 Antares_Simulator. If not, see . +** Mozilla Public Licence 2.0 for more details. ** -** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +** You should have received a copy of the Mozilla Public Licence 2.0 +** along with Antares_Simulator. If not, see . */ #ifndef __ANTARES_WINDOWS_XCAST_XCAST_HXX__ #define __ANTARES_WINDOWS_XCAST_XCAST_HXX__ diff --git a/src/vcpkg.json b/src/vcpkg.json new file mode 100644 index 0000000000..08acfb9e79 --- /dev/null +++ b/src/vcpkg.json @@ -0,0 +1,39 @@ +{ + "name": "antares-simulator", + "version-string": "9.1.0", + "builtin-baseline": "9484a57dd560b89f0a583be08af6753611c57fd5", + "vcpkg-configuration": { + "overlay-ports": [ + "./ports" + ], + "overlay-triplets": [ + "./triplets" + ] + }, + "dependencies": [ + { + "name": "sirius-solver", + "version>=": "1.5" + }, + { + "name": "wxwidgets", + "platform": "windows" + }, + { + "name": "boost-test", + "version>=": "1.81.0" + }, + { + "name": "boost-core", + "version>=": "1.81.0" + }, + { + "name": "minizip-ng", + "default-features": false, + "version>=": "4.0.0", + "features": [ + "zlib" + ] + } + ] +} diff --git a/vcpkg_manifest/vcpkg.json b/vcpkg_manifest/vcpkg.json deleted file mode 100644 index 15837160b1..0000000000 --- a/vcpkg_manifest/vcpkg.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "antares-simulator", - "version-string": "8.5.0", - "dependencies": [ - "wxwidgets", - "boost-test" - ] -} \ No newline at end of file